~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

Merge pt1 hooks branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
 
18
18
from cStringIO import StringIO
 
19
import sys
19
20
 
20
21
from bzrlib.lazy_import import lazy_import
21
22
lazy_import(globals(), """
22
 
import itertools
 
23
from itertools import chain
23
24
from bzrlib import (
24
25
        bzrdir,
25
26
        cache_utf8,
26
 
        cleanup,
27
27
        config as _mod_config,
 
28
        controldir,
28
29
        debug,
29
30
        errors,
30
31
        fetch,
35
36
        repository,
36
37
        revision as _mod_revision,
37
38
        rio,
38
 
        tag as _mod_tag,
 
39
        symbol_versioning,
39
40
        transport,
 
41
        tsort,
40
42
        ui,
41
43
        urlutils,
42
44
        )
43
 
from bzrlib.i18n import gettext, ngettext
 
45
from bzrlib.config import BranchConfig, TransportConfig
 
46
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
 
47
from bzrlib.tag import (
 
48
    BasicTags,
 
49
    DisabledTags,
 
50
    )
44
51
""")
45
52
 
46
 
from bzrlib import (
47
 
    controldir,
48
 
    )
49
 
from bzrlib.decorators import (
50
 
    needs_read_lock,
51
 
    needs_write_lock,
52
 
    only_raises,
53
 
    )
54
 
from bzrlib.hooks import Hooks
 
53
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
54
from bzrlib.hooks import HookPoint, Hooks
55
55
from bzrlib.inter import InterObject
56
56
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
57
57
from bzrlib import registry
62
62
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
63
63
 
64
64
 
 
65
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
66
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
67
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
68
 
 
69
 
65
70
class Branch(controldir.ControlComponent):
66
71
    """Branch holding a history of revisions.
67
72
 
68
73
    :ivar base:
69
74
        Base directory/url of the branch; using control_url and
70
75
        control_transport is more standardized.
71
 
    :ivar hooks: An instance of BranchHooks.
72
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
73
 
        _clear_cached_state.
 
76
 
 
77
    hooks: An instance of BranchHooks.
74
78
    """
75
79
    # this is really an instance variable - FIXME move it there
76
80
    # - RBC 20060112
92
96
        self._partial_revision_history_cache = []
93
97
        self._tags_bytes = None
94
98
        self._last_revision_info_cache = None
95
 
        self._master_branch_cache = None
96
99
        self._merge_sorted_revisions_cache = None
97
100
        self._open_hook()
98
101
        hooks = Branch.hooks['open']
213
216
 
214
217
        :return: A bzrlib.config.BranchConfig.
215
218
        """
216
 
        return _mod_config.BranchConfig(self)
217
 
 
218
 
    def get_config_stack(self):
219
 
        """Get a bzrlib.config.BranchStack for this Branch.
220
 
 
221
 
        This can then be used to get and set configuration options for the
222
 
        branch.
223
 
 
224
 
        :return: A bzrlib.config.BranchStack.
225
 
        """
226
 
        return _mod_config.BranchStack(self)
 
219
        return BranchConfig(self)
227
220
 
228
221
    def _get_config(self):
229
222
        """Get the concrete config for just the config in this branch.
456
449
            after. If None, the rest of history is included.
457
450
        :param stop_rule: if stop_revision_id is not None, the precise rule
458
451
            to use for termination:
459
 
 
460
452
            * 'exclude' - leave the stop revision out of the result (default)
461
453
            * 'include' - the stop revision is the last item in the result
462
454
            * 'with-merges' - include the stop revision and all of its
464
456
            * 'with-merges-without-common-ancestry' - filter out revisions 
465
457
              that are in both ancestries
466
458
        :param direction: either 'reverse' or 'forward':
467
 
 
468
459
            * reverse means return the start_revision_id first, i.e.
469
460
              start at the most recent revision and go backwards in history
470
461
            * forward returns tuples in the opposite order to reverse.
514
505
        rev_iter = iter(merge_sorted_revisions)
515
506
        if start_revision_id is not None:
516
507
            for node in rev_iter:
517
 
                rev_id = node.key
 
508
                rev_id = node.key[-1]
518
509
                if rev_id != start_revision_id:
519
510
                    continue
520
511
                else:
521
512
                    # The decision to include the start or not
522
513
                    # depends on the stop_rule if a stop is provided
523
514
                    # so pop this node back into the iterator
524
 
                    rev_iter = itertools.chain(iter([node]), rev_iter)
 
515
                    rev_iter = chain(iter([node]), rev_iter)
525
516
                    break
526
517
        if stop_revision_id is None:
527
518
            # Yield everything
528
519
            for node in rev_iter:
529
 
                rev_id = node.key
 
520
                rev_id = node.key[-1]
530
521
                yield (rev_id, node.merge_depth, node.revno,
531
522
                       node.end_of_merge)
532
523
        elif stop_rule == 'exclude':
533
524
            for node in rev_iter:
534
 
                rev_id = node.key
 
525
                rev_id = node.key[-1]
535
526
                if rev_id == stop_revision_id:
536
527
                    return
537
528
                yield (rev_id, node.merge_depth, node.revno,
538
529
                       node.end_of_merge)
539
530
        elif stop_rule == 'include':
540
531
            for node in rev_iter:
541
 
                rev_id = node.key
 
532
                rev_id = node.key[-1]
542
533
                yield (rev_id, node.merge_depth, node.revno,
543
534
                       node.end_of_merge)
544
535
                if rev_id == stop_revision_id:
550
541
            ancestors = graph.find_unique_ancestors(start_revision_id,
551
542
                                                    [stop_revision_id])
552
543
            for node in rev_iter:
553
 
                rev_id = node.key
 
544
                rev_id = node.key[-1]
554
545
                if rev_id not in ancestors:
555
546
                    continue
556
547
                yield (rev_id, node.merge_depth, node.revno,
566
557
            reached_stop_revision_id = False
567
558
            revision_id_whitelist = []
568
559
            for node in rev_iter:
569
 
                rev_id = node.key
 
560
                rev_id = node.key[-1]
570
561
                if rev_id == left_parent:
571
562
                    # reached the left parent after the stop_revision
572
563
                    return
652
643
        """
653
644
        raise errors.UpgradeRequired(self.user_url)
654
645
 
655
 
    def get_append_revisions_only(self):
656
 
        """Whether it is only possible to append revisions to the history.
657
 
        """
658
 
        if not self._format.supports_set_append_revisions_only():
659
 
            return False
660
 
        return self.get_config(
661
 
            ).get_user_option_as_bool('append_revisions_only')
662
 
 
663
646
    def set_append_revisions_only(self, enabled):
664
647
        if not self._format.supports_set_append_revisions_only():
665
648
            raise errors.UpgradeRequired(self.user_url)
679
662
        raise errors.UnsupportedOperation(self.get_reference_info, self)
680
663
 
681
664
    @needs_write_lock
682
 
    def fetch(self, from_branch, last_revision=None, limit=None):
 
665
    def fetch(self, from_branch, last_revision=None, pb=None, fetch_spec=None):
683
666
        """Copy revisions from from_branch into this branch.
684
667
 
685
668
        :param from_branch: Where to copy from.
686
669
        :param last_revision: What revision to stop at (None for at the end
687
670
                              of the branch.
688
 
        :param limit: Optional rough limit of revisions to fetch
 
671
        :param pb: An optional progress bar to use.
 
672
        :param fetch_spec: If specified, a SearchResult or
 
673
            PendingAncestryResult that describes which revisions to copy.  This
 
674
            allows copying multiple heads at once.  Mutually exclusive with
 
675
            last_revision.
689
676
        :return: None
690
677
        """
691
 
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
678
        if fetch_spec is not None and last_revision is not None:
 
679
            raise AssertionError(
 
680
                "fetch_spec and last_revision are mutually exclusive.")
 
681
        if self.base == from_branch.base:
 
682
            return (0, [])
 
683
        if pb is not None:
 
684
            symbol_versioning.warn(
 
685
                symbol_versioning.deprecated_in((1, 14, 0))
 
686
                % "pb parameter to fetch()")
 
687
        from_branch.lock_read()
 
688
        try:
 
689
            if last_revision is None and fetch_spec is None:
 
690
                last_revision = from_branch.last_revision()
 
691
                last_revision = _mod_revision.ensure_null(last_revision)
 
692
            return self.repository.fetch(from_branch.repository,
 
693
                                         revision_id=last_revision,
 
694
                                         pb=pb, fetch_spec=fetch_spec)
 
695
        finally:
 
696
            from_branch.unlock()
692
697
 
693
698
    def get_bound_location(self):
694
699
        """Return the URL of the branch we are bound to.
705
710
 
706
711
    def get_commit_builder(self, parents, config=None, timestamp=None,
707
712
                           timezone=None, committer=None, revprops=None,
708
 
                           revision_id=None, lossy=False):
 
713
                           revision_id=None):
709
714
        """Obtain a CommitBuilder for this branch.
710
715
 
711
716
        :param parents: Revision ids of the parents of the new revision.
715
720
        :param committer: Optional committer to set for commit.
716
721
        :param revprops: Optional dictionary of revision properties.
717
722
        :param revision_id: Optional revision id.
718
 
        :param lossy: Whether to discard data that can not be natively
719
 
            represented, when pushing to a foreign VCS 
720
723
        """
721
724
 
722
725
        if config is None:
723
726
            config = self.get_config()
724
727
 
725
728
        return self.repository.get_commit_builder(self, parents, config,
726
 
            timestamp, timezone, committer, revprops, revision_id,
727
 
            lossy)
 
729
            timestamp, timezone, committer, revprops, revision_id)
728
730
 
729
731
    def get_master_branch(self, possible_transports=None):
730
732
        """Return the branch we are bound to.
757
759
        """Print `file` to stdout."""
758
760
        raise NotImplementedError(self.print_file)
759
761
 
760
 
    @deprecated_method(deprecated_in((2, 4, 0)))
761
762
    def set_revision_history(self, rev_history):
762
 
        """See Branch.set_revision_history."""
763
 
        self._set_revision_history(rev_history)
764
 
 
765
 
    @needs_write_lock
766
 
    def _set_revision_history(self, rev_history):
767
 
        if len(rev_history) == 0:
768
 
            revid = _mod_revision.NULL_REVISION
769
 
        else:
770
 
            revid = rev_history[-1]
771
 
        if rev_history != self._lefthand_history(revid):
772
 
            raise errors.NotLefthandHistory(rev_history)
773
 
        self.set_last_revision_info(len(rev_history), revid)
774
 
        self._cache_revision_history(rev_history)
775
 
        for hook in Branch.hooks['set_rh']:
776
 
            hook(self, rev_history)
777
 
 
778
 
    @needs_write_lock
779
 
    def set_last_revision_info(self, revno, revision_id):
780
 
        """Set the last revision of this branch.
781
 
 
782
 
        The caller is responsible for checking that the revno is correct
783
 
        for this revision id.
784
 
 
785
 
        It may be possible to set the branch last revision to an id not
786
 
        present in the repository.  However, branches can also be
787
 
        configured to check constraints on history, in which case this may not
788
 
        be permitted.
789
 
        """
790
 
        raise NotImplementedError(self.set_last_revision_info)
791
 
 
792
 
    @needs_write_lock
793
 
    def generate_revision_history(self, revision_id, last_rev=None,
794
 
                                  other_branch=None):
795
 
        """See Branch.generate_revision_history"""
796
 
        graph = self.repository.get_graph()
797
 
        (last_revno, last_revid) = self.last_revision_info()
798
 
        known_revision_ids = [
799
 
            (last_revid, last_revno),
800
 
            (_mod_revision.NULL_REVISION, 0),
801
 
            ]
802
 
        if last_rev is not None:
803
 
            if not graph.is_ancestor(last_rev, revision_id):
804
 
                # our previous tip is not merged into stop_revision
805
 
                raise errors.DivergedBranches(self, other_branch)
806
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
807
 
        self.set_last_revision_info(revno, revision_id)
 
763
        raise NotImplementedError(self.set_revision_history)
808
764
 
809
765
    @needs_write_lock
810
766
    def set_parent(self, url):
854
810
 
855
811
    def _unstack(self):
856
812
        """Change a branch to be unstacked, copying data as needed.
857
 
 
 
813
        
858
814
        Don't call this directly, use set_stacked_on_url(None).
859
815
        """
860
816
        pb = ui.ui_factory.nested_progress_bar()
861
817
        try:
862
 
            pb.update(gettext("Unstacking"))
 
818
            pb.update("Unstacking")
863
819
            # The basic approach here is to fetch the tip of the branch,
864
820
            # including all available ghosts, from the existing stacked
865
821
            # repository into a new repository object without the fallbacks. 
942
898
 
943
899
        :seealso: Branch._get_tags_bytes.
944
900
        """
945
 
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
946
 
        op.add_cleanup(self.lock_write().unlock)
947
 
        return op.run_simple(bytes)
 
901
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
902
                bytes)
948
903
 
949
904
    def _set_tags_bytes_locked(self, bytes):
950
905
        self._tags_bytes = bytes
981
936
        self._revision_history_cache = None
982
937
        self._revision_id_to_revno_cache = None
983
938
        self._last_revision_info_cache = None
984
 
        self._master_branch_cache = None
985
939
        self._merge_sorted_revisions_cache = None
986
940
        self._partial_revision_history_cache = []
987
941
        self._partial_revision_id_to_revno_cache = {}
1041
995
        :return: A tuple (revno, revision_id).
1042
996
        """
1043
997
        if self._last_revision_info_cache is None:
1044
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
998
            self._last_revision_info_cache = self._last_revision_info()
1045
999
        return self._last_revision_info_cache
1046
1000
 
1047
 
    def _read_last_revision_info(self):
1048
 
        raise NotImplementedError(self._read_last_revision_info)
 
1001
    def _last_revision_info(self):
 
1002
        rh = self.revision_history()
 
1003
        revno = len(rh)
 
1004
        if revno:
 
1005
            return (revno, rh[-1])
 
1006
        else:
 
1007
            return (0, _mod_revision.NULL_REVISION)
 
1008
 
 
1009
    @deprecated_method(deprecated_in((1, 6, 0)))
 
1010
    def missing_revisions(self, other, stop_revision=None):
 
1011
        """Return a list of new revisions that would perfectly fit.
 
1012
 
 
1013
        If self and other have not diverged, return a list of the revisions
 
1014
        present in other, but missing from self.
 
1015
        """
 
1016
        self_history = self.revision_history()
 
1017
        self_len = len(self_history)
 
1018
        other_history = other.revision_history()
 
1019
        other_len = len(other_history)
 
1020
        common_index = min(self_len, other_len) -1
 
1021
        if common_index >= 0 and \
 
1022
            self_history[common_index] != other_history[common_index]:
 
1023
            raise errors.DivergedBranches(self, other)
 
1024
 
 
1025
        if stop_revision is None:
 
1026
            stop_revision = other_len
 
1027
        else:
 
1028
            if stop_revision > other_len:
 
1029
                raise errors.NoSuchRevision(self, stop_revision)
 
1030
        return other_history[self_len:stop_revision]
 
1031
 
 
1032
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
1033
                         graph=None, fetch_tags=True):
 
1034
        """Pull in new perfect-fit revisions.
 
1035
 
 
1036
        :param other: Another Branch to pull from
 
1037
        :param stop_revision: Updated until the given revision
 
1038
        :param overwrite: Always set the branch pointer, rather than checking
 
1039
            to see if it is a proper descendant.
 
1040
        :param graph: A Graph object that can be used to query history
 
1041
            information. This can be None.
 
1042
        :param fetch_tags: Flag that specifies if tags from other should be
 
1043
            fetched too.
 
1044
        :return: None
 
1045
        """
 
1046
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
1047
            overwrite, graph, fetch_tags=fetch_tags)
1049
1048
 
1050
1049
    @deprecated_method(deprecated_in((2, 4, 0)))
1051
1050
    def import_last_revision_info(self, source_repo, revno, revid):
1059
1058
            self.repository.fetch(source_repo, revision_id=revid)
1060
1059
        self.set_last_revision_info(revno, revid)
1061
1060
 
1062
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1063
 
                                           lossy=False):
 
1061
    def import_last_revision_info_and_tags(self, source, revno, revid):
1064
1062
        """Set the last revision info, importing from another repo if necessary.
1065
1063
 
1066
1064
        This is used by the bound branch code to upload a revision to
1070
1068
        :param source: Source branch to optionally fetch from
1071
1069
        :param revno: Revision number of the new tip
1072
1070
        :param revid: Revision id of the new tip
1073
 
        :param lossy: Whether to discard metadata that can not be
1074
 
            natively represented
1075
 
        :return: Tuple with the new revision number and revision id
1076
 
            (should only be different from the arguments when lossy=True)
1077
1071
        """
1078
1072
        if not self.repository.has_same_location(source.repository):
1079
 
            self.fetch(source, revid)
 
1073
            try:
 
1074
                tags_to_fetch = set(source.tags.get_reverse_tag_dict())
 
1075
            except errors.TagsNotSupported:
 
1076
                tags_to_fetch = set()
 
1077
            fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
1078
                source.repository, [revid],
 
1079
                if_present_ids=tags_to_fetch).execute()
 
1080
            self.repository.fetch(source.repository, fetch_spec=fetch_spec)
1080
1081
        self.set_last_revision_info(revno, revid)
1081
 
        return (revno, revid)
1082
1082
 
1083
1083
    def revision_id_to_revno(self, revision_id):
1084
1084
        """Given a revision id, return its revno"""
1117
1117
            stop_revision=stop_revision,
1118
1118
            possible_transports=possible_transports, *args, **kwargs)
1119
1119
 
1120
 
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1121
 
            *args, **kwargs):
 
1120
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
1121
        **kwargs):
1122
1122
        """Mirror this branch into target.
1123
1123
 
1124
1124
        This branch is considered to be 'local', having low latency.
1125
1125
        """
1126
1126
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1127
 
            lossy, *args, **kwargs)
 
1127
            *args, **kwargs)
 
1128
 
 
1129
    def lossy_push(self, target, stop_revision=None):
 
1130
        """Push deltas into another branch.
 
1131
 
 
1132
        :note: This does not, like push, retain the revision ids from 
 
1133
            the source branch and will, rather than adding bzr-specific 
 
1134
            metadata, push only those semantics of the revision that can be 
 
1135
            natively represented by this branch' VCS.
 
1136
 
 
1137
        :param target: Target branch
 
1138
        :param stop_revision: Revision to push, defaults to last revision.
 
1139
        :return: BranchPushResult with an extra member revidmap: 
 
1140
            A dictionary mapping revision ids from the target branch 
 
1141
            to new revision ids in the target branch, for each 
 
1142
            revision that was pushed.
 
1143
        """
 
1144
        inter = InterBranch.get(self, target)
 
1145
        lossy_push = getattr(inter, "lossy_push", None)
 
1146
        if lossy_push is None:
 
1147
            raise errors.LossyPushToSameVCS(self, target)
 
1148
        return lossy_push(stop_revision)
1128
1149
 
1129
1150
    def basis_tree(self):
1130
1151
        """Return `Tree` object for last revision."""
1303
1324
            if repository_policy is not None:
1304
1325
                repository_policy.configure_branch(result)
1305
1326
            self.copy_content_into(result, revision_id=revision_id)
1306
 
            master_url = self.get_bound_location()
1307
 
            if master_url is None:
1308
 
                result.set_parent(self.bzrdir.root_transport.base)
1309
 
            else:
1310
 
                result.set_parent(master_url)
 
1327
            result.set_parent(self.bzrdir.root_transport.base)
1311
1328
        finally:
1312
1329
            result.unlock()
1313
1330
        return result
1391
1408
        # specific check.
1392
1409
        return result
1393
1410
 
1394
 
    def _get_checkout_format(self, lightweight=False):
 
1411
    def _get_checkout_format(self):
1395
1412
        """Return the most suitable metadir for a checkout of this branch.
1396
1413
        Weaves are used if this branch's repository uses weaves.
1397
1414
        """
1432
1449
        :param to_location: The url to produce the checkout at
1433
1450
        :param revision_id: The revision to check out
1434
1451
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1435
 
            produce a bound branch (heavyweight checkout)
 
1452
        produce a bound branch (heavyweight checkout)
1436
1453
        :param accelerator_tree: A tree which can be used for retrieving file
1437
1454
            contents more quickly than the revision tree, i.e. a workingtree.
1438
1455
            The revision tree will be used for cases where accelerator_tree's
1443
1460
        """
1444
1461
        t = transport.get_transport(to_location)
1445
1462
        t.ensure_base()
1446
 
        format = self._get_checkout_format(lightweight=lightweight)
1447
1463
        if lightweight:
 
1464
            format = self._get_checkout_format()
1448
1465
            checkout = format.initialize_on_transport(t)
1449
1466
            from_branch = BranchReferenceFormat().initialize(checkout, 
1450
1467
                target_branch=self)
1451
1468
        else:
 
1469
            format = self._get_checkout_format()
1452
1470
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1453
1471
                to_location, force_new_tree=False, format=format)
1454
1472
            checkout = checkout_branch.bzrdir
1483
1501
 
1484
1502
    def reference_parent(self, file_id, path, possible_transports=None):
1485
1503
        """Return the parent branch for a tree-reference file_id
1486
 
 
1487
1504
        :param file_id: The file_id of the tree reference
1488
1505
        :param path: The path of the file_id in the tree
1489
1506
        :return: A branch associated with the file_id
1542
1559
        else:
1543
1560
            raise AssertionError("invalid heads: %r" % (heads,))
1544
1561
 
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 if_present_fetch
1555
 
        # are the tags.
1556
 
        must_fetch = set([self.last_revision()])
1557
 
        if_present_fetch = set()
1558
 
        c = self.get_config()
1559
 
        include_tags = c.get_user_option_as_bool('branch.fetch_tags',
1560
 
                                                 default=False)
1561
 
        if include_tags:
1562
 
            try:
1563
 
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
1564
 
            except errors.TagsNotSupported:
1565
 
                pass
1566
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1567
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1568
 
        return must_fetch, if_present_fetch
1569
 
 
1570
 
 
1571
 
class BranchFormat(controldir.ControlComponentFormat):
 
1562
 
 
1563
class BranchFormat(object):
1572
1564
    """An encapsulation of the initialization and open routines for a format.
1573
1565
 
1574
1566
    Formats provide three things:
1586
1578
    object will be created every time regardless.
1587
1579
    """
1588
1580
 
 
1581
    _default_format = None
 
1582
    """The default format used for new branches."""
 
1583
 
 
1584
    _formats = {}
 
1585
    """The known formats."""
 
1586
 
 
1587
    _extra_formats = []
 
1588
    """Extra formats that can not be part of a metadir."""
 
1589
 
 
1590
    can_set_append_revisions_only = True
 
1591
 
1589
1592
    def __eq__(self, other):
1590
1593
        return self.__class__ is other.__class__
1591
1594
 
1598
1601
        try:
1599
1602
            transport = a_bzrdir.get_branch_transport(None, name=name)
1600
1603
            format_string = transport.get_bytes("format")
1601
 
            return format_registry.get(format_string)
 
1604
            format = klass._formats[format_string]
 
1605
            if isinstance(format, MetaDirBranchFormatFactory):
 
1606
                return format()
 
1607
            return format
1602
1608
        except errors.NoSuchFile:
1603
1609
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1604
1610
        except KeyError:
1605
1611
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1606
1612
 
1607
1613
    @classmethod
1608
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1609
1614
    def get_default_format(klass):
1610
1615
        """Return the current default format."""
1611
 
        return format_registry.get_default()
 
1616
        return klass._default_format
1612
1617
 
1613
1618
    @classmethod
1614
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1615
1619
    def get_formats(klass):
1616
1620
        """Get all the known formats.
1617
1621
 
1618
1622
        Warning: This triggers a load of all lazy registered formats: do not
1619
1623
        use except when that is desireed.
1620
1624
        """
1621
 
        return format_registry._get_all()
 
1625
        result = []
 
1626
        for fmt in klass._formats.values():
 
1627
            if isinstance(fmt, MetaDirBranchFormatFactory):
 
1628
                fmt = fmt()
 
1629
            result.append(fmt)
 
1630
        return result + klass._extra_formats
1622
1631
 
1623
1632
    def get_reference(self, a_bzrdir, name=None):
1624
1633
        """Get the target reference of the branch in a_bzrdir.
1663
1672
        for hook in hooks:
1664
1673
            hook(params)
1665
1674
 
1666
 
    def initialize(self, a_bzrdir, name=None, repository=None,
1667
 
                   append_revisions_only=None):
 
1675
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1676
                           repository=None, lock_type='metadir',
 
1677
                           set_format=True):
 
1678
        """Initialize a branch in a bzrdir, with specified files
 
1679
 
 
1680
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1681
        :param utf8_files: The files to create as a list of
 
1682
            (filename, content) tuples
 
1683
        :param name: Name of colocated branch to create, if any
 
1684
        :param set_format: If True, set the format with
 
1685
            self.get_format_string.  (BzrBranch4 has its format set
 
1686
            elsewhere)
 
1687
        :return: a branch in this format
 
1688
        """
 
1689
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1690
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1691
        lock_map = {
 
1692
            'metadir': ('lock', lockdir.LockDir),
 
1693
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1694
        }
 
1695
        lock_name, lock_class = lock_map[lock_type]
 
1696
        control_files = lockable_files.LockableFiles(branch_transport,
 
1697
            lock_name, lock_class)
 
1698
        control_files.create_lock()
 
1699
        try:
 
1700
            control_files.lock_write()
 
1701
        except errors.LockContention:
 
1702
            if lock_type != 'branch4':
 
1703
                raise
 
1704
            lock_taken = False
 
1705
        else:
 
1706
            lock_taken = True
 
1707
        if set_format:
 
1708
            utf8_files += [('format', self.get_format_string())]
 
1709
        try:
 
1710
            for (filename, content) in utf8_files:
 
1711
                branch_transport.put_bytes(
 
1712
                    filename, content,
 
1713
                    mode=a_bzrdir._get_file_mode())
 
1714
        finally:
 
1715
            if lock_taken:
 
1716
                control_files.unlock()
 
1717
        branch = self.open(a_bzrdir, name, _found=True,
 
1718
                found_repository=repository)
 
1719
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1720
        return branch
 
1721
 
 
1722
    def initialize(self, a_bzrdir, name=None, repository=None):
1668
1723
        """Create a branch of this format in a_bzrdir.
1669
1724
        
1670
1725
        :param name: Name of the colocated branch to create.
1692
1747
        Note that it is normal for branch to be a RemoteBranch when using tags
1693
1748
        on a RemoteBranch.
1694
1749
        """
1695
 
        return _mod_tag.DisabledTags(branch)
 
1750
        return DisabledTags(branch)
1696
1751
 
1697
1752
    def network_name(self):
1698
1753
        """A simple byte string uniquely identifying this format for RPC calls.
1718
1773
        raise NotImplementedError(self.open)
1719
1774
 
1720
1775
    @classmethod
1721
 
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1776
    def register_extra_format(klass, format):
 
1777
        """Register a branch format that can not be part of a metadir.
 
1778
 
 
1779
        This is mainly useful to allow custom branch formats, such as
 
1780
        older Bazaar formats and foreign formats, to be tested
 
1781
        """
 
1782
        klass._extra_formats.append(format)
 
1783
        network_format_registry.register(
 
1784
            format.network_name(), format.__class__)
 
1785
 
 
1786
    @classmethod
1722
1787
    def register_format(klass, format):
1723
1788
        """Register a metadir format.
1724
 
 
 
1789
        
1725
1790
        See MetaDirBranchFormatFactory for the ability to register a format
1726
1791
        without loading the code the format needs until it is actually used.
1727
1792
        """
1728
 
        format_registry.register(format)
 
1793
        klass._formats[format.get_format_string()] = format
 
1794
        # Metadir formats have a network name of their format string, and get
 
1795
        # registered as factories.
 
1796
        if isinstance(format, MetaDirBranchFormatFactory):
 
1797
            network_format_registry.register(format.get_format_string(), format)
 
1798
        else:
 
1799
            network_format_registry.register(format.get_format_string(),
 
1800
                format.__class__)
1729
1801
 
1730
1802
    @classmethod
1731
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1732
1803
    def set_default_format(klass, format):
1733
 
        format_registry.set_default(format)
 
1804
        klass._default_format = format
1734
1805
 
1735
1806
    def supports_set_append_revisions_only(self):
1736
1807
        """True if this format supports set_append_revisions_only."""
1740
1811
        """True if this format records a stacked-on branch."""
1741
1812
        return False
1742
1813
 
1743
 
    def supports_leaving_lock(self):
1744
 
        """True if this format supports leaving locks in place."""
1745
 
        return False # by default
1746
 
 
1747
1814
    @classmethod
1748
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1749
1815
    def unregister_format(klass, format):
1750
 
        format_registry.remove(format)
 
1816
        del klass._formats[format.get_format_string()]
 
1817
 
 
1818
    @classmethod
 
1819
    def unregister_extra_format(klass, format):
 
1820
        klass._extra_formats.remove(format)
1751
1821
 
1752
1822
    def __str__(self):
1753
1823
        return self.get_format_description().rstrip()
1756
1826
        """True if this format supports tags stored in the branch"""
1757
1827
        return False  # by default
1758
1828
 
1759
 
    def tags_are_versioned(self):
1760
 
        """Whether the tag container for this branch versions tags."""
1761
 
        return False
1762
 
 
1763
 
    def supports_tags_referencing_ghosts(self):
1764
 
        """True if tags can reference ghost revisions."""
1765
 
        return True
1766
 
 
1767
1829
 
1768
1830
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1769
1831
    """A factory for a BranchFormat object, permitting simple lazy registration.
1806
1868
        These are all empty initially, because by default nothing should get
1807
1869
        notified.
1808
1870
        """
1809
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1810
 
        self.add_hook('set_rh',
 
1871
        Hooks.__init__(self)
 
1872
        self.create_hook(HookPoint('set_rh',
1811
1873
            "Invoked whenever the revision history has been set via "
1812
1874
            "set_revision_history. The api signature is (branch, "
1813
1875
            "revision_history), and the branch will be write-locked. "
1814
1876
            "The set_rh hook can be expensive for bzr to trigger, a better "
1815
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1816
 
        self.add_hook('open',
 
1877
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1878
        self.create_hook(HookPoint('open',
1817
1879
            "Called with the Branch object that has been opened after a "
1818
 
            "branch is opened.", (1, 8))
1819
 
        self.add_hook('post_push',
 
1880
            "branch is opened.", (1, 8), None))
 
1881
        self.create_hook(HookPoint('post_push',
1820
1882
            "Called after a push operation completes. post_push is called "
1821
1883
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1822
 
            "bzr client.", (0, 15))
1823
 
        self.add_hook('post_pull',
 
1884
            "bzr client.", (0, 15), None))
 
1885
        self.create_hook(HookPoint('post_pull',
1824
1886
            "Called after a pull operation completes. post_pull is called "
1825
1887
            "with a bzrlib.branch.PullResult object and only runs in the "
1826
 
            "bzr client.", (0, 15))
1827
 
        self.add_hook('pre_commit',
 
1888
            "bzr client.", (0, 15), None))
 
1889
        self.create_hook(HookPoint('pre_commit',
1828
1890
            "Called after a commit is calculated but before it is "
1829
1891
            "completed. pre_commit is called with (local, master, old_revno, "
1830
1892
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1833
1895
            "basis revision. hooks MUST NOT modify this delta. "
1834
1896
            " future_tree is an in-memory tree obtained from "
1835
1897
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1836
 
            "tree.", (0,91))
1837
 
        self.add_hook('post_commit',
 
1898
            "tree.", (0,91), None))
 
1899
        self.create_hook(HookPoint('post_commit',
1838
1900
            "Called in the bzr client after a commit has completed. "
1839
1901
            "post_commit is called with (local, master, old_revno, old_revid, "
1840
1902
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1841
 
            "commit to a branch.", (0, 15))
1842
 
        self.add_hook('post_uncommit',
 
1903
            "commit to a branch.", (0, 15), None))
 
1904
        self.create_hook(HookPoint('post_uncommit',
1843
1905
            "Called in the bzr client after an uncommit completes. "
1844
1906
            "post_uncommit is called with (local, master, old_revno, "
1845
1907
            "old_revid, new_revno, new_revid) where local is the local branch "
1846
1908
            "or None, master is the target branch, and an empty branch "
1847
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1848
 
        self.add_hook('pre_change_branch_tip',
 
1909
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1910
        self.create_hook(HookPoint('pre_change_branch_tip',
1849
1911
            "Called in bzr client and server before a change to the tip of a "
1850
1912
            "branch is made. pre_change_branch_tip is called with a "
1851
1913
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1852
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1853
 
        self.add_hook('post_change_branch_tip',
 
1914
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1915
        self.create_hook(HookPoint('post_change_branch_tip',
1854
1916
            "Called in bzr client and server after a change to the tip of a "
1855
1917
            "branch is made. post_change_branch_tip is called with a "
1856
1918
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1857
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1858
 
        self.add_hook('transform_fallback_location',
 
1919
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1920
        self.create_hook(HookPoint('transform_fallback_location',
1859
1921
            "Called when a stacked branch is activating its fallback "
1860
1922
            "locations. transform_fallback_location is called with (branch, "
1861
1923
            "url), and should return a new url. Returning the same url "
1866
1928
            "fallback locations have not been activated. When there are "
1867
1929
            "multiple hooks installed for transform_fallback_location, "
1868
1930
            "all are called with the url returned from the previous hook."
1869
 
            "The order is however undefined.", (1, 9))
1870
 
        self.add_hook('automatic_tag_name',
 
1931
            "The order is however undefined.", (1, 9), None))
 
1932
        self.create_hook(HookPoint('automatic_tag_name',
1871
1933
            "Called to determine an automatic tag name for a revision. "
1872
1934
            "automatic_tag_name is called with (branch, revision_id) and "
1873
1935
            "should return a tag name or None if no tag name could be "
1874
1936
            "determined. The first non-None tag name returned will be used.",
1875
 
            (2, 2))
1876
 
        self.add_hook('post_branch_init',
 
1937
            (2, 2), None))
 
1938
        self.create_hook(HookPoint('post_branch_init',
1877
1939
            "Called after new branch initialization completes. "
1878
1940
            "post_branch_init is called with a "
1879
1941
            "bzrlib.branch.BranchInitHookParams. "
1880
1942
            "Note that init, branch and checkout (both heavyweight and "
1881
 
            "lightweight) will all trigger this hook.", (2, 2))
1882
 
        self.add_hook('post_switch',
 
1943
            "lightweight) will all trigger this hook.", (2, 2), None))
 
1944
        self.create_hook(HookPoint('post_switch',
1883
1945
            "Called after a checkout switches branch. "
1884
1946
            "post_switch is called with a "
1885
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
 
1947
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1886
1948
 
1887
1949
 
1888
1950
 
1891
1953
 
1892
1954
 
1893
1955
class ChangeBranchTipParams(object):
1894
 
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1956
    """Object holding parameters passed to *_change_branch_tip hooks.
1895
1957
 
1896
1958
    There are 5 fields that hooks may wish to access:
1897
1959
 
1929
1991
 
1930
1992
 
1931
1993
class BranchInitHookParams(object):
1932
 
    """Object holding parameters passed to `*_branch_init` hooks.
 
1994
    """Object holding parameters passed to *_branch_init hooks.
1933
1995
 
1934
1996
    There are 4 fields that hooks may wish to access:
1935
1997
 
1969
2031
 
1970
2032
 
1971
2033
class SwitchHookParams(object):
1972
 
    """Object holding parameters passed to `*_switch` hooks.
 
2034
    """Object holding parameters passed to *_switch hooks.
1973
2035
 
1974
2036
    There are 4 fields that hooks may wish to access:
1975
2037
 
2001
2063
            self.revision_id)
2002
2064
 
2003
2065
 
 
2066
class BzrBranchFormat4(BranchFormat):
 
2067
    """Bzr branch format 4.
 
2068
 
 
2069
    This format has:
 
2070
     - a revision-history file.
 
2071
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
2072
    """
 
2073
 
 
2074
    def get_format_description(self):
 
2075
        """See BranchFormat.get_format_description()."""
 
2076
        return "Branch format 4"
 
2077
 
 
2078
    def initialize(self, a_bzrdir, name=None, repository=None):
 
2079
        """Create a branch of this format in a_bzrdir."""
 
2080
        if repository is not None:
 
2081
            raise NotImplementedError(
 
2082
                "initialize(repository=<not None>) on %r" % (self,))
 
2083
        utf8_files = [('revision-history', ''),
 
2084
                      ('branch-name', ''),
 
2085
                      ]
 
2086
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
2087
                                       lock_type='branch4', set_format=False)
 
2088
 
 
2089
    def __init__(self):
 
2090
        super(BzrBranchFormat4, self).__init__()
 
2091
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
2092
 
 
2093
    def network_name(self):
 
2094
        """The network name for this format is the control dirs disk label."""
 
2095
        return self._matchingbzrdir.get_format_string()
 
2096
 
 
2097
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2098
            found_repository=None):
 
2099
        """See BranchFormat.open()."""
 
2100
        if not _found:
 
2101
            # we are being called directly and must probe.
 
2102
            raise NotImplementedError
 
2103
        if found_repository is None:
 
2104
            found_repository = a_bzrdir.open_repository()
 
2105
        return BzrBranchPreSplitOut(_format=self,
 
2106
                         _control_files=a_bzrdir._control_files,
 
2107
                         a_bzrdir=a_bzrdir,
 
2108
                         name=name,
 
2109
                         _repository=found_repository)
 
2110
 
 
2111
    def __str__(self):
 
2112
        return "Bazaar-NG branch format 4"
 
2113
 
 
2114
 
2004
2115
class BranchFormatMetadir(BranchFormat):
2005
2116
    """Common logic for meta-dir based branch formats."""
2006
2117
 
2008
2119
        """What class to instantiate on open calls."""
2009
2120
        raise NotImplementedError(self._branch_class)
2010
2121
 
2011
 
    def _get_initial_config(self, append_revisions_only=None):
2012
 
        if append_revisions_only:
2013
 
            return "append_revisions_only = True\n"
2014
 
        else:
2015
 
            # Avoid writing anything if append_revisions_only is disabled,
2016
 
            # as that is the default.
2017
 
            return ""
2018
 
 
2019
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2020
 
                           repository=None):
2021
 
        """Initialize a branch in a bzrdir, with specified files
2022
 
 
2023
 
        :param a_bzrdir: The bzrdir to initialize the branch in
2024
 
        :param utf8_files: The files to create as a list of
2025
 
            (filename, content) tuples
2026
 
        :param name: Name of colocated branch to create, if any
2027
 
        :return: a branch in this format
2028
 
        """
2029
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2030
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2031
 
        control_files = lockable_files.LockableFiles(branch_transport,
2032
 
            'lock', lockdir.LockDir)
2033
 
        control_files.create_lock()
2034
 
        control_files.lock_write()
2035
 
        try:
2036
 
            utf8_files += [('format', self.get_format_string())]
2037
 
            for (filename, content) in utf8_files:
2038
 
                branch_transport.put_bytes(
2039
 
                    filename, content,
2040
 
                    mode=a_bzrdir._get_file_mode())
2041
 
        finally:
2042
 
            control_files.unlock()
2043
 
        branch = self.open(a_bzrdir, name, _found=True,
2044
 
                found_repository=repository)
2045
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2046
 
        return branch
2047
 
 
2048
2122
    def network_name(self):
2049
2123
        """A simple byte string uniquely identifying this format for RPC calls.
2050
2124
 
2083
2157
    def supports_tags(self):
2084
2158
        return True
2085
2159
 
2086
 
    def supports_leaving_lock(self):
2087
 
        return True
2088
 
 
2089
2160
 
2090
2161
class BzrBranchFormat5(BranchFormatMetadir):
2091
2162
    """Bzr branch format 5.
2111
2182
        """See BranchFormat.get_format_description()."""
2112
2183
        return "Branch format 5"
2113
2184
 
2114
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2115
 
                   append_revisions_only=None):
 
2185
    def initialize(self, a_bzrdir, name=None, repository=None):
2116
2186
        """Create a branch of this format in a_bzrdir."""
2117
 
        if append_revisions_only:
2118
 
            raise errors.UpgradeRequired(a_bzrdir.user_url)
2119
2187
        utf8_files = [('revision-history', ''),
2120
2188
                      ('branch-name', ''),
2121
2189
                      ]
2147
2215
        """See BranchFormat.get_format_description()."""
2148
2216
        return "Branch format 6"
2149
2217
 
2150
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2151
 
                   append_revisions_only=None):
 
2218
    def initialize(self, a_bzrdir, name=None, repository=None):
2152
2219
        """Create a branch of this format in a_bzrdir."""
2153
2220
        utf8_files = [('last-revision', '0 null:\n'),
2154
 
                      ('branch.conf',
2155
 
                          self._get_initial_config(append_revisions_only)),
 
2221
                      ('branch.conf', ''),
2156
2222
                      ('tags', ''),
2157
2223
                      ]
2158
2224
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2159
2225
 
2160
2226
    def make_tags(self, branch):
2161
2227
        """See bzrlib.branch.BranchFormat.make_tags()."""
2162
 
        return _mod_tag.BasicTags(branch)
 
2228
        return BasicTags(branch)
2163
2229
 
2164
2230
    def supports_set_append_revisions_only(self):
2165
2231
        return True
2179
2245
        """See BranchFormat.get_format_description()."""
2180
2246
        return "Branch format 8"
2181
2247
 
2182
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2183
 
                   append_revisions_only=None):
 
2248
    def initialize(self, a_bzrdir, name=None, repository=None):
2184
2249
        """Create a branch of this format in a_bzrdir."""
2185
2250
        utf8_files = [('last-revision', '0 null:\n'),
2186
 
                      ('branch.conf',
2187
 
                          self._get_initial_config(append_revisions_only)),
 
2251
                      ('branch.conf', ''),
2188
2252
                      ('tags', ''),
2189
2253
                      ('references', '')
2190
2254
                      ]
2191
2255
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2192
2256
 
 
2257
    def __init__(self):
 
2258
        super(BzrBranchFormat8, self).__init__()
 
2259
        self._matchingbzrdir.repository_format = \
 
2260
            RepositoryFormatKnitPack5RichRoot()
 
2261
 
2193
2262
    def make_tags(self, branch):
2194
2263
        """See bzrlib.branch.BranchFormat.make_tags()."""
2195
 
        return _mod_tag.BasicTags(branch)
 
2264
        return BasicTags(branch)
2196
2265
 
2197
2266
    def supports_set_append_revisions_only(self):
2198
2267
        return True
2203
2272
    supports_reference_locations = True
2204
2273
 
2205
2274
 
2206
 
class BzrBranchFormat7(BranchFormatMetadir):
 
2275
class BzrBranchFormat7(BzrBranchFormat8):
2207
2276
    """Branch format with last-revision, tags, and a stacked location pointer.
2208
2277
 
2209
2278
    The stacked location pointer is passed down to the repository and requires
2212
2281
    This format was introduced in bzr 1.6.
2213
2282
    """
2214
2283
 
2215
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2216
 
                   append_revisions_only=None):
 
2284
    def initialize(self, a_bzrdir, name=None, repository=None):
2217
2285
        """Create a branch of this format in a_bzrdir."""
2218
2286
        utf8_files = [('last-revision', '0 null:\n'),
2219
 
                      ('branch.conf',
2220
 
                          self._get_initial_config(append_revisions_only)),
 
2287
                      ('branch.conf', ''),
2221
2288
                      ('tags', ''),
2222
2289
                      ]
2223
2290
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2236
2303
    def supports_set_append_revisions_only(self):
2237
2304
        return True
2238
2305
 
2239
 
    def supports_stacking(self):
2240
 
        return True
2241
 
 
2242
 
    def make_tags(self, branch):
2243
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2244
 
        return _mod_tag.BasicTags(branch)
2245
 
 
2246
2306
    supports_reference_locations = False
2247
2307
 
2248
2308
 
2276
2336
        location = transport.put_bytes('location', to_branch.base)
2277
2337
 
2278
2338
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2279
 
            repository=None, append_revisions_only=None):
 
2339
            repository=None):
2280
2340
        """Create a branch of this format in a_bzrdir."""
2281
2341
        if target_branch is None:
2282
2342
            # this format does not implement branch itself, thus the implicit
2283
2343
            # creation contract must see it as uninitializable
2284
2344
            raise errors.UninitializableFormat(self)
2285
2345
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2286
 
        if a_bzrdir._format.fixed_components:
2287
 
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
2288
2346
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2289
2347
        branch_transport.put_bytes('location',
2290
2348
            target_branch.bzrdir.user_url)
2350
2408
        return result
2351
2409
 
2352
2410
 
2353
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2354
 
    """Branch format registry."""
2355
 
 
2356
 
    def __init__(self, other_registry=None):
2357
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2358
 
        self._default_format = None
2359
 
 
2360
 
    def set_default(self, format):
2361
 
        self._default_format = format
2362
 
 
2363
 
    def get_default(self):
2364
 
        return self._default_format
2365
 
 
2366
 
 
2367
2411
network_format_registry = registry.FormatRegistry()
2368
2412
"""Registry of formats indexed by their network name.
2369
2413
 
2372
2416
BranchFormat.network_name() for more detail.
2373
2417
"""
2374
2418
 
2375
 
format_registry = BranchFormatRegistry(network_format_registry)
2376
 
 
2377
2419
 
2378
2420
# formats which have no format string are not discoverable
2379
2421
# and not independently creatable, so are not registered.
2381
2423
__format6 = BzrBranchFormat6()
2382
2424
__format7 = BzrBranchFormat7()
2383
2425
__format8 = BzrBranchFormat8()
2384
 
format_registry.register(__format5)
2385
 
format_registry.register(BranchReferenceFormat())
2386
 
format_registry.register(__format6)
2387
 
format_registry.register(__format7)
2388
 
format_registry.register(__format8)
2389
 
format_registry.set_default(__format7)
 
2426
BranchFormat.register_format(__format5)
 
2427
BranchFormat.register_format(BranchReferenceFormat())
 
2428
BranchFormat.register_format(__format6)
 
2429
BranchFormat.register_format(__format7)
 
2430
BranchFormat.register_format(__format8)
 
2431
BranchFormat.set_default_format(__format7)
 
2432
BranchFormat.register_extra_format(BzrBranchFormat4())
2390
2433
 
2391
2434
 
2392
2435
class BranchWriteLockResult(LogicalLockResult):
2459
2502
    base = property(_get_base, doc="The URL for the root of this branch.")
2460
2503
 
2461
2504
    def _get_config(self):
2462
 
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
 
2505
        return TransportConfig(self._transport, 'branch.conf')
2463
2506
 
2464
2507
    def is_locked(self):
2465
2508
        return self.control_files.is_locked()
2540
2583
        """See Branch.print_file."""
2541
2584
        return self.repository.print_file(file, revision_id)
2542
2585
 
 
2586
    def _write_revision_history(self, history):
 
2587
        """Factored out of set_revision_history.
 
2588
 
 
2589
        This performs the actual writing to disk.
 
2590
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2591
        self._transport.put_bytes(
 
2592
            'revision-history', '\n'.join(history),
 
2593
            mode=self.bzrdir._get_file_mode())
 
2594
 
 
2595
    @needs_write_lock
 
2596
    def set_revision_history(self, rev_history):
 
2597
        """See Branch.set_revision_history."""
 
2598
        if 'evil' in debug.debug_flags:
 
2599
            mutter_callsite(3, "set_revision_history scales with history.")
 
2600
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2601
        for rev_id in rev_history:
 
2602
            check_not_reserved_id(rev_id)
 
2603
        if Branch.hooks['post_change_branch_tip']:
 
2604
            # Don't calculate the last_revision_info() if there are no hooks
 
2605
            # that will use it.
 
2606
            old_revno, old_revid = self.last_revision_info()
 
2607
        if len(rev_history) == 0:
 
2608
            revid = _mod_revision.NULL_REVISION
 
2609
        else:
 
2610
            revid = rev_history[-1]
 
2611
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2612
        self._write_revision_history(rev_history)
 
2613
        self._clear_cached_state()
 
2614
        self._cache_revision_history(rev_history)
 
2615
        for hook in Branch.hooks['set_rh']:
 
2616
            hook(self, rev_history)
 
2617
        if Branch.hooks['post_change_branch_tip']:
 
2618
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2619
 
 
2620
    def _synchronize_history(self, destination, revision_id):
 
2621
        """Synchronize last revision and revision history between branches.
 
2622
 
 
2623
        This version is most efficient when the destination is also a
 
2624
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2625
        history is the true lefthand parent history, and all of the revisions
 
2626
        are in the destination's repository.  If not, set_revision_history
 
2627
        will fail.
 
2628
 
 
2629
        :param destination: The branch to copy the history into
 
2630
        :param revision_id: The revision-id to truncate history at.  May
 
2631
          be None to copy complete history.
 
2632
        """
 
2633
        if not isinstance(destination._format, BzrBranchFormat5):
 
2634
            super(BzrBranch, self)._synchronize_history(
 
2635
                destination, revision_id)
 
2636
            return
 
2637
        if revision_id == _mod_revision.NULL_REVISION:
 
2638
            new_history = []
 
2639
        else:
 
2640
            new_history = self.revision_history()
 
2641
        if revision_id is not None and new_history != []:
 
2642
            try:
 
2643
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2644
            except ValueError:
 
2645
                rev = self.repository.get_revision(revision_id)
 
2646
                new_history = rev.get_history(self.repository)[1:]
 
2647
        destination.set_revision_history(new_history)
 
2648
 
2543
2649
    @needs_write_lock
2544
2650
    def set_last_revision_info(self, revno, revision_id):
2545
 
        if not revision_id or not isinstance(revision_id, basestring):
2546
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2651
        """Set the last revision of this branch.
 
2652
 
 
2653
        The caller is responsible for checking that the revno is correct
 
2654
        for this revision id.
 
2655
 
 
2656
        It may be possible to set the branch last revision to an id not
 
2657
        present in the repository.  However, branches can also be
 
2658
        configured to check constraints on history, in which case this may not
 
2659
        be permitted.
 
2660
        """
2547
2661
        revision_id = _mod_revision.ensure_null(revision_id)
2548
 
        old_revno, old_revid = self.last_revision_info()
2549
 
        if self.get_append_revisions_only():
2550
 
            self._check_history_violation(revision_id)
2551
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2552
 
        self._write_last_revision_info(revno, revision_id)
2553
 
        self._clear_cached_state()
2554
 
        self._last_revision_info_cache = revno, revision_id
2555
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2662
        # this old format stores the full history, but this api doesn't
 
2663
        # provide it, so we must generate, and might as well check it's
 
2664
        # correct
 
2665
        history = self._lefthand_history(revision_id)
 
2666
        if len(history) != revno:
 
2667
            raise AssertionError('%d != %d' % (len(history), revno))
 
2668
        self.set_revision_history(history)
 
2669
 
 
2670
    def _gen_revision_history(self):
 
2671
        history = self._transport.get_bytes('revision-history').split('\n')
 
2672
        if history[-1:] == ['']:
 
2673
            # There shouldn't be a trailing newline, but just in case.
 
2674
            history.pop()
 
2675
        return history
 
2676
 
 
2677
    @needs_write_lock
 
2678
    def generate_revision_history(self, revision_id, last_rev=None,
 
2679
        other_branch=None):
 
2680
        """Create a new revision history that will finish with revision_id.
 
2681
 
 
2682
        :param revision_id: the new tip to use.
 
2683
        :param last_rev: The previous last_revision. If not None, then this
 
2684
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2685
        :param other_branch: The other branch that DivergedBranches should
 
2686
            raise with respect to.
 
2687
        """
 
2688
        self.set_revision_history(self._lefthand_history(revision_id,
 
2689
            last_rev, other_branch))
2556
2690
 
2557
2691
    def basis_tree(self):
2558
2692
        """See Branch.basis_tree."""
2567
2701
                pass
2568
2702
        return None
2569
2703
 
 
2704
    def _basic_push(self, target, overwrite, stop_revision):
 
2705
        """Basic implementation of push without bound branches or hooks.
 
2706
 
 
2707
        Must be called with source read locked and target write locked.
 
2708
        """
 
2709
        result = BranchPushResult()
 
2710
        result.source_branch = self
 
2711
        result.target_branch = target
 
2712
        result.old_revno, result.old_revid = target.last_revision_info()
 
2713
        self.update_references(target)
 
2714
        if result.old_revid != stop_revision:
 
2715
            # We assume that during 'push' this repository is closer than
 
2716
            # the target.
 
2717
            graph = self.repository.get_graph(target.repository)
 
2718
            target.update_revisions(self, stop_revision,
 
2719
                overwrite=overwrite, graph=graph)
 
2720
        if self._push_should_merge_tags():
 
2721
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2722
                overwrite)
 
2723
        result.new_revno, result.new_revid = target.last_revision_info()
 
2724
        return result
 
2725
 
2570
2726
    def get_stacked_on_url(self):
2571
2727
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2572
2728
 
2583
2739
            self._transport.put_bytes('parent', url + '\n',
2584
2740
                mode=self.bzrdir._get_file_mode())
2585
2741
 
 
2742
 
 
2743
class BzrBranchPreSplitOut(BzrBranch):
 
2744
 
 
2745
    def _get_checkout_format(self):
 
2746
        """Return the most suitable metadir for a checkout of this branch.
 
2747
        Weaves are used if this branch's repository uses weaves.
 
2748
        """
 
2749
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2750
        from bzrlib.bzrdir import BzrDirMetaFormat1
 
2751
        format = BzrDirMetaFormat1()
 
2752
        format.repository_format = RepositoryFormat7()
 
2753
        return format
 
2754
 
 
2755
 
 
2756
class BzrBranch5(BzrBranch):
 
2757
    """A format 5 branch. This supports new features over plain branches.
 
2758
 
 
2759
    It has support for a master_branch which is the data for bound branches.
 
2760
    """
 
2761
 
 
2762
    def get_bound_location(self):
 
2763
        try:
 
2764
            return self._transport.get_bytes('bound')[:-1]
 
2765
        except errors.NoSuchFile:
 
2766
            return None
 
2767
 
 
2768
    @needs_read_lock
 
2769
    def get_master_branch(self, possible_transports=None):
 
2770
        """Return the branch we are bound to.
 
2771
 
 
2772
        :return: Either a Branch, or None
 
2773
 
 
2774
        This could memoise the branch, but if thats done
 
2775
        it must be revalidated on each new lock.
 
2776
        So for now we just don't memoise it.
 
2777
        # RBC 20060304 review this decision.
 
2778
        """
 
2779
        bound_loc = self.get_bound_location()
 
2780
        if not bound_loc:
 
2781
            return None
 
2782
        try:
 
2783
            return Branch.open(bound_loc,
 
2784
                               possible_transports=possible_transports)
 
2785
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2786
            raise errors.BoundBranchConnectionFailure(
 
2787
                    self, bound_loc, e)
 
2788
 
2586
2789
    @needs_write_lock
2587
 
    def unbind(self):
2588
 
        """If bound, unbind"""
2589
 
        return self.set_bound_location(None)
 
2790
    def set_bound_location(self, location):
 
2791
        """Set the target where this branch is bound to.
 
2792
 
 
2793
        :param location: URL to the target branch
 
2794
        """
 
2795
        if location:
 
2796
            self._transport.put_bytes('bound', location+'\n',
 
2797
                mode=self.bzrdir._get_file_mode())
 
2798
        else:
 
2799
            try:
 
2800
                self._transport.delete('bound')
 
2801
            except errors.NoSuchFile:
 
2802
                return False
 
2803
            return True
2590
2804
 
2591
2805
    @needs_write_lock
2592
2806
    def bind(self, other):
2614
2828
        # history around
2615
2829
        self.set_bound_location(other.base)
2616
2830
 
2617
 
    def get_bound_location(self):
2618
 
        try:
2619
 
            return self._transport.get_bytes('bound')[:-1]
2620
 
        except errors.NoSuchFile:
2621
 
            return None
2622
 
 
2623
 
    @needs_read_lock
2624
 
    def get_master_branch(self, possible_transports=None):
2625
 
        """Return the branch we are bound to.
2626
 
 
2627
 
        :return: Either a Branch, or None
2628
 
        """
2629
 
        if self._master_branch_cache is None:
2630
 
            self._master_branch_cache = self._get_master_branch(
2631
 
                possible_transports)
2632
 
        return self._master_branch_cache
2633
 
 
2634
 
    def _get_master_branch(self, possible_transports):
2635
 
        bound_loc = self.get_bound_location()
2636
 
        if not bound_loc:
2637
 
            return None
2638
 
        try:
2639
 
            return Branch.open(bound_loc,
2640
 
                               possible_transports=possible_transports)
2641
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2642
 
            raise errors.BoundBranchConnectionFailure(
2643
 
                    self, bound_loc, e)
2644
 
 
2645
2831
    @needs_write_lock
2646
 
    def set_bound_location(self, location):
2647
 
        """Set the target where this branch is bound to.
2648
 
 
2649
 
        :param location: URL to the target branch
2650
 
        """
2651
 
        self._master_branch_cache = None
2652
 
        if location:
2653
 
            self._transport.put_bytes('bound', location+'\n',
2654
 
                mode=self.bzrdir._get_file_mode())
2655
 
        else:
2656
 
            try:
2657
 
                self._transport.delete('bound')
2658
 
            except errors.NoSuchFile:
2659
 
                return False
2660
 
            return True
 
2832
    def unbind(self):
 
2833
        """If bound, unbind"""
 
2834
        return self.set_bound_location(None)
2661
2835
 
2662
2836
    @needs_write_lock
2663
2837
    def update(self, possible_transports=None):
2676
2850
            return old_tip
2677
2851
        return None
2678
2852
 
2679
 
    def _read_last_revision_info(self):
2680
 
        revision_string = self._transport.get_bytes('last-revision')
2681
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2682
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2683
 
        revno = int(revno)
2684
 
        return revno, revision_id
2685
 
 
2686
 
    def _write_last_revision_info(self, revno, revision_id):
2687
 
        """Simply write out the revision id, with no checks.
2688
 
 
2689
 
        Use set_last_revision_info to perform this safely.
2690
 
 
2691
 
        Does not update the revision_history cache.
2692
 
        """
2693
 
        revision_id = _mod_revision.ensure_null(revision_id)
2694
 
        out_string = '%d %s\n' % (revno, revision_id)
2695
 
        self._transport.put_bytes('last-revision', out_string,
2696
 
            mode=self.bzrdir._get_file_mode())
2697
 
 
2698
 
 
2699
 
class FullHistoryBzrBranch(BzrBranch):
2700
 
    """Bzr branch which contains the full revision history."""
2701
 
 
2702
 
    @needs_write_lock
2703
 
    def set_last_revision_info(self, revno, revision_id):
2704
 
        if not revision_id or not isinstance(revision_id, basestring):
2705
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2706
 
        revision_id = _mod_revision.ensure_null(revision_id)
2707
 
        # this old format stores the full history, but this api doesn't
2708
 
        # provide it, so we must generate, and might as well check it's
2709
 
        # correct
2710
 
        history = self._lefthand_history(revision_id)
2711
 
        if len(history) != revno:
2712
 
            raise AssertionError('%d != %d' % (len(history), revno))
2713
 
        self._set_revision_history(history)
2714
 
 
2715
 
    def _read_last_revision_info(self):
2716
 
        rh = self.revision_history()
2717
 
        revno = len(rh)
2718
 
        if revno:
2719
 
            return (revno, rh[-1])
2720
 
        else:
2721
 
            return (0, _mod_revision.NULL_REVISION)
2722
 
 
2723
 
    @deprecated_method(deprecated_in((2, 4, 0)))
2724
 
    @needs_write_lock
2725
 
    def set_revision_history(self, rev_history):
2726
 
        """See Branch.set_revision_history."""
2727
 
        self._set_revision_history(rev_history)
2728
 
 
2729
 
    def _set_revision_history(self, rev_history):
2730
 
        if 'evil' in debug.debug_flags:
2731
 
            mutter_callsite(3, "set_revision_history scales with history.")
2732
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2733
 
        for rev_id in rev_history:
2734
 
            check_not_reserved_id(rev_id)
2735
 
        if Branch.hooks['post_change_branch_tip']:
2736
 
            # Don't calculate the last_revision_info() if there are no hooks
2737
 
            # that will use it.
2738
 
            old_revno, old_revid = self.last_revision_info()
2739
 
        if len(rev_history) == 0:
2740
 
            revid = _mod_revision.NULL_REVISION
2741
 
        else:
2742
 
            revid = rev_history[-1]
2743
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2744
 
        self._write_revision_history(rev_history)
2745
 
        self._clear_cached_state()
2746
 
        self._cache_revision_history(rev_history)
2747
 
        for hook in Branch.hooks['set_rh']:
2748
 
            hook(self, rev_history)
2749
 
        if Branch.hooks['post_change_branch_tip']:
2750
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2751
 
 
2752
 
    def _write_revision_history(self, history):
2753
 
        """Factored out of set_revision_history.
2754
 
 
2755
 
        This performs the actual writing to disk.
2756
 
        It is intended to be called by set_revision_history."""
2757
 
        self._transport.put_bytes(
2758
 
            'revision-history', '\n'.join(history),
2759
 
            mode=self.bzrdir._get_file_mode())
2760
 
 
2761
 
    def _gen_revision_history(self):
2762
 
        history = self._transport.get_bytes('revision-history').split('\n')
2763
 
        if history[-1:] == ['']:
2764
 
            # There shouldn't be a trailing newline, but just in case.
2765
 
            history.pop()
2766
 
        return history
2767
 
 
2768
 
    def _synchronize_history(self, destination, revision_id):
2769
 
        if not isinstance(destination, FullHistoryBzrBranch):
2770
 
            super(BzrBranch, self)._synchronize_history(
2771
 
                destination, revision_id)
2772
 
            return
2773
 
        if revision_id == _mod_revision.NULL_REVISION:
2774
 
            new_history = []
2775
 
        else:
2776
 
            new_history = self.revision_history()
2777
 
        if revision_id is not None and new_history != []:
2778
 
            try:
2779
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2780
 
            except ValueError:
2781
 
                rev = self.repository.get_revision(revision_id)
2782
 
                new_history = rev.get_history(self.repository)[1:]
2783
 
        destination._set_revision_history(new_history)
2784
 
 
2785
 
    @needs_write_lock
2786
 
    def generate_revision_history(self, revision_id, last_rev=None,
2787
 
        other_branch=None):
2788
 
        """Create a new revision history that will finish with revision_id.
2789
 
 
2790
 
        :param revision_id: the new tip to use.
2791
 
        :param last_rev: The previous last_revision. If not None, then this
2792
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2793
 
        :param other_branch: The other branch that DivergedBranches should
2794
 
            raise with respect to.
2795
 
        """
2796
 
        self._set_revision_history(self._lefthand_history(revision_id,
2797
 
            last_rev, other_branch))
2798
 
 
2799
 
 
2800
 
class BzrBranch5(FullHistoryBzrBranch):
2801
 
    """A format 5 branch. This supports new features over plain branches.
2802
 
 
2803
 
    It has support for a master_branch which is the data for bound branches.
2804
 
    """
2805
 
 
2806
 
 
2807
 
class BzrBranch8(BzrBranch):
 
2853
 
 
2854
class BzrBranch8(BzrBranch5):
2808
2855
    """A branch that stores tree-reference locations."""
2809
2856
 
2810
2857
    def _open_hook(self):
2836
2883
        self._last_revision_info_cache = None
2837
2884
        self._reference_info = None
2838
2885
 
 
2886
    def _last_revision_info(self):
 
2887
        revision_string = self._transport.get_bytes('last-revision')
 
2888
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2889
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2890
        revno = int(revno)
 
2891
        return revno, revision_id
 
2892
 
 
2893
    def _write_last_revision_info(self, revno, revision_id):
 
2894
        """Simply write out the revision id, with no checks.
 
2895
 
 
2896
        Use set_last_revision_info to perform this safely.
 
2897
 
 
2898
        Does not update the revision_history cache.
 
2899
        Intended to be called by set_last_revision_info and
 
2900
        _write_revision_history.
 
2901
        """
 
2902
        revision_id = _mod_revision.ensure_null(revision_id)
 
2903
        out_string = '%d %s\n' % (revno, revision_id)
 
2904
        self._transport.put_bytes('last-revision', out_string,
 
2905
            mode=self.bzrdir._get_file_mode())
 
2906
 
 
2907
    @needs_write_lock
 
2908
    def set_last_revision_info(self, revno, revision_id):
 
2909
        revision_id = _mod_revision.ensure_null(revision_id)
 
2910
        old_revno, old_revid = self.last_revision_info()
 
2911
        if self._get_append_revisions_only():
 
2912
            self._check_history_violation(revision_id)
 
2913
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2914
        self._write_last_revision_info(revno, revision_id)
 
2915
        self._clear_cached_state()
 
2916
        self._last_revision_info_cache = revno, revision_id
 
2917
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2918
 
 
2919
    def _synchronize_history(self, destination, revision_id):
 
2920
        """Synchronize last revision and revision history between branches.
 
2921
 
 
2922
        :see: Branch._synchronize_history
 
2923
        """
 
2924
        # XXX: The base Branch has a fast implementation of this method based
 
2925
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2926
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2927
        # but wants the fast implementation, so it calls
 
2928
        # Branch._synchronize_history directly.
 
2929
        Branch._synchronize_history(self, destination, revision_id)
 
2930
 
2839
2931
    def _check_history_violation(self, revision_id):
2840
 
        current_revid = self.last_revision()
2841
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2932
        last_revision = _mod_revision.ensure_null(self.last_revision())
2842
2933
        if _mod_revision.is_null(last_revision):
2843
2934
            return
2844
 
        graph = self.repository.get_graph()
2845
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2846
 
            if lh_ancestor == current_revid:
2847
 
                return
2848
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2935
        if last_revision not in self._lefthand_history(revision_id):
 
2936
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
2849
2937
 
2850
2938
    def _gen_revision_history(self):
2851
2939
        """Generate the revision history from last revision
2854
2942
        self._extend_partial_history(stop_index=last_revno-1)
2855
2943
        return list(reversed(self._partial_revision_history_cache))
2856
2944
 
 
2945
    def _write_revision_history(self, history):
 
2946
        """Factored out of set_revision_history.
 
2947
 
 
2948
        This performs the actual writing to disk, with format-specific checks.
 
2949
        It is intended to be called by BzrBranch5.set_revision_history.
 
2950
        """
 
2951
        if len(history) == 0:
 
2952
            last_revision = 'null:'
 
2953
        else:
 
2954
            if history != self._lefthand_history(history[-1]):
 
2955
                raise errors.NotLefthandHistory(history)
 
2956
            last_revision = history[-1]
 
2957
        if self._get_append_revisions_only():
 
2958
            self._check_history_violation(last_revision)
 
2959
        self._write_last_revision_info(len(history), last_revision)
 
2960
 
2857
2961
    @needs_write_lock
2858
2962
    def _set_parent_location(self, url):
2859
2963
        """Set the parent branch"""
2945
3049
 
2946
3050
    def set_bound_location(self, location):
2947
3051
        """See Branch.set_push_location."""
2948
 
        self._master_branch_cache = None
2949
3052
        result = None
2950
3053
        config = self.get_config()
2951
3054
        if location is None:
2982
3085
        # you can always ask for the URL; but you might not be able to use it
2983
3086
        # if the repo can't support stacking.
2984
3087
        ## self._check_stackable_repo()
2985
 
        # stacked_on_location is only ever defined in branch.conf, so don't
2986
 
        # waste effort reading the whole stack of config files.
2987
 
        config = self.get_config()._get_branch_data_config()
2988
 
        stacked_url = self._get_config_location('stacked_on_location',
2989
 
            config=config)
 
3088
        stacked_url = self._get_config_location('stacked_on_location')
2990
3089
        if stacked_url is None:
2991
3090
            raise errors.NotStacked(self)
2992
3091
        return stacked_url
2993
3092
 
 
3093
    def _get_append_revisions_only(self):
 
3094
        return self.get_config(
 
3095
            ).get_user_option_as_bool('append_revisions_only')
 
3096
 
 
3097
    @needs_write_lock
 
3098
    def generate_revision_history(self, revision_id, last_rev=None,
 
3099
                                  other_branch=None):
 
3100
        """See BzrBranch5.generate_revision_history"""
 
3101
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
3102
        revno = len(history)
 
3103
        self.set_last_revision_info(revno, revision_id)
 
3104
 
2994
3105
    @needs_read_lock
2995
3106
    def get_rev_id(self, revno, history=None):
2996
3107
        """Find the revision id of the specified revno."""
3020
3131
        try:
3021
3132
            index = self._partial_revision_history_cache.index(revision_id)
3022
3133
        except ValueError:
3023
 
            try:
3024
 
                self._extend_partial_history(stop_revision=revision_id)
3025
 
            except errors.RevisionNotPresent, e:
3026
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
3134
            self._extend_partial_history(stop_revision=revision_id)
3027
3135
            index = len(self._partial_revision_history_cache) - 1
3028
3136
            if self._partial_revision_history_cache[index] != revision_id:
3029
3137
                raise errors.NoSuchRevision(self, revision_id)
3082
3190
    :ivar local_branch: target branch if there is a Master, else None
3083
3191
    :ivar target_branch: Target/destination branch object. (write locked)
3084
3192
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3085
 
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
3086
3193
    """
3087
3194
 
3088
3195
    @deprecated_method(deprecated_in((2, 3, 0)))
3094
3201
        return self.new_revno - self.old_revno
3095
3202
 
3096
3203
    def report(self, to_file):
3097
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
3098
 
        tag_updates = getattr(self, "tag_updates", None)
3099
3204
        if not is_quiet():
3100
 
            if self.old_revid != self.new_revid:
 
3205
            if self.old_revid == self.new_revid:
 
3206
                to_file.write('No revisions to pull.\n')
 
3207
            else:
3101
3208
                to_file.write('Now on revision %d.\n' % self.new_revno)
3102
 
            if tag_updates:
3103
 
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3104
 
            if self.old_revid == self.new_revid and not tag_updates:
3105
 
                if not tag_conflicts:
3106
 
                    to_file.write('No revisions or tags to pull.\n')
3107
 
                else:
3108
 
                    to_file.write('No revisions to pull.\n')
3109
3209
        self._show_tag_conficts(to_file)
3110
3210
 
3111
3211
 
3137
3237
        return self.new_revno - self.old_revno
3138
3238
 
3139
3239
    def report(self, to_file):
3140
 
        # TODO: This function gets passed a to_file, but then
3141
 
        # ignores it and calls note() instead. This is also
3142
 
        # inconsistent with PullResult(), which writes to stdout.
3143
 
        # -- JRV20110901, bug #838853
3144
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
3145
 
        tag_updates = getattr(self, "tag_updates", None)
3146
 
        if not is_quiet():
3147
 
            if self.old_revid != self.new_revid:
3148
 
                note(gettext('Pushed up to revision %d.') % self.new_revno)
3149
 
            if tag_updates:
3150
 
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3151
 
            if self.old_revid == self.new_revid and not tag_updates:
3152
 
                if not tag_conflicts:
3153
 
                    note(gettext('No new revisions or tags to push.'))
3154
 
                else:
3155
 
                    note(gettext('No new revisions to push.'))
 
3240
        """Write a human-readable description of the result."""
 
3241
        if self.old_revid == self.new_revid:
 
3242
            note('No new revisions to push.')
 
3243
        else:
 
3244
            note('Pushed up to revision %d.' % self.new_revno)
3156
3245
        self._show_tag_conficts(to_file)
3157
3246
 
3158
3247
 
3172
3261
        :param verbose: Requests more detailed display of what was checked,
3173
3262
            if any.
3174
3263
        """
3175
 
        note(gettext('checked branch {0} format {1}').format(
3176
 
                                self.branch.user_url, self.branch._format))
 
3264
        note('checked branch %s format %s', self.branch.user_url,
 
3265
            self.branch._format)
3177
3266
        for error in self.errors:
3178
 
            note(gettext('found error:%s'), error)
 
3267
            note('found error:%s', error)
3179
3268
 
3180
3269
 
3181
3270
class Converter5to6(object):
3220
3309
 
3221
3310
 
3222
3311
class Converter7to8(object):
3223
 
    """Perform an in-place upgrade of format 7 to format 8"""
 
3312
    """Perform an in-place upgrade of format 6 to format 7"""
3224
3313
 
3225
3314
    def convert(self, branch):
3226
3315
        format = BzrBranchFormat8()
3229
3318
        branch._transport.put_bytes('format', format.get_format_string())
3230
3319
 
3231
3320
 
 
3321
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
3322
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
3323
    duration.
 
3324
 
 
3325
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
3326
 
 
3327
    If an exception is raised by callable, then that exception *will* be
 
3328
    propagated, even if the unlock attempt raises its own error.  Thus
 
3329
    _run_with_write_locked_target should be preferred to simply doing::
 
3330
 
 
3331
        target.lock_write()
 
3332
        try:
 
3333
            return callable(*args, **kwargs)
 
3334
        finally:
 
3335
            target.unlock()
 
3336
 
 
3337
    """
 
3338
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
3339
    # should share code?
 
3340
    target.lock_write()
 
3341
    try:
 
3342
        result = callable(*args, **kwargs)
 
3343
    except:
 
3344
        exc_info = sys.exc_info()
 
3345
        try:
 
3346
            target.unlock()
 
3347
        finally:
 
3348
            raise exc_info[0], exc_info[1], exc_info[2]
 
3349
    else:
 
3350
        target.unlock()
 
3351
        return result
 
3352
 
 
3353
 
3232
3354
class InterBranch(InterObject):
3233
3355
    """This class represents operations taking place between two branches.
3234
3356
 
3262
3384
        raise NotImplementedError(self.pull)
3263
3385
 
3264
3386
    @needs_write_lock
3265
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
3387
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3388
                         graph=None, fetch_tags=True):
 
3389
        """Pull in new perfect-fit revisions.
 
3390
 
 
3391
        :param stop_revision: Updated until the given revision
 
3392
        :param overwrite: Always set the branch pointer, rather than checking
 
3393
            to see if it is a proper descendant.
 
3394
        :param graph: A Graph object that can be used to query history
 
3395
            information. This can be None.
 
3396
        :param fetch_tags: Flag that specifies if tags from source should be
 
3397
            fetched too.
 
3398
        :return: None
 
3399
        """
 
3400
        raise NotImplementedError(self.update_revisions)
 
3401
 
 
3402
    @needs_write_lock
 
3403
    def push(self, overwrite=False, stop_revision=None,
3266
3404
             _override_hook_source_branch=None):
3267
3405
        """Mirror the source branch into the target branch.
3268
3406
 
3279
3417
        """
3280
3418
        raise NotImplementedError(self.copy_content_into)
3281
3419
 
3282
 
    @needs_write_lock
3283
 
    def fetch(self, stop_revision=None, limit=None):
3284
 
        """Fetch revisions.
3285
 
 
3286
 
        :param stop_revision: Last revision to fetch
3287
 
        :param limit: Optional rough limit of revisions to fetch
3288
 
        """
3289
 
        raise NotImplementedError(self.fetch)
3290
 
 
3291
3420
 
3292
3421
class GenericInterBranch(InterBranch):
3293
3422
    """InterBranch implementation that uses public Branch functions."""
3299
3428
 
3300
3429
    @classmethod
3301
3430
    def _get_branch_formats_to_test(klass):
3302
 
        return [(format_registry.get_default(), format_registry.get_default())]
 
3431
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3303
3432
 
3304
3433
    @classmethod
3305
3434
    def unwrap_format(klass, format):
3328
3457
            self.source.tags.merge_to(self.target.tags)
3329
3458
 
3330
3459
    @needs_write_lock
3331
 
    def fetch(self, stop_revision=None, limit=None):
3332
 
        if self.target.base == self.source.base:
3333
 
            return (0, [])
3334
 
        self.source.lock_read()
3335
 
        try:
3336
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3337
 
            fetch_spec_factory.source_branch = self.source
3338
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3339
 
            fetch_spec_factory.source_repo = self.source.repository
3340
 
            fetch_spec_factory.target_repo = self.target.repository
3341
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3342
 
            fetch_spec_factory.limit = limit
3343
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3344
 
            return self.target.repository.fetch(self.source.repository,
3345
 
                fetch_spec=fetch_spec)
3346
 
        finally:
3347
 
            self.source.unlock()
3348
 
 
3349
 
    @needs_write_lock
3350
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3351
 
            graph=None):
 
3460
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3461
        graph=None, fetch_tags=True):
 
3462
        """See InterBranch.update_revisions()."""
3352
3463
        other_revno, other_last_revision = self.source.last_revision_info()
3353
3464
        stop_revno = None # unknown
3354
3465
        if stop_revision is None:
3365
3476
        # case of having something to pull, and so that the check for
3366
3477
        # already merged can operate on the just fetched graph, which will
3367
3478
        # be cached in memory.
3368
 
        self.fetch(stop_revision=stop_revision)
 
3479
        if fetch_tags:
 
3480
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3481
            fetch_spec_factory.source_branch = self.source
 
3482
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3483
            fetch_spec_factory.source_repo = self.source.repository
 
3484
            fetch_spec_factory.target_repo = self.target.repository
 
3485
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3486
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3487
        else:
 
3488
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3489
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3490
        self.target.fetch(self.source, fetch_spec=fetch_spec)
3369
3491
        # Check to see if one is an ancestor of the other
3370
3492
        if not overwrite:
3371
3493
            if graph is None:
3399
3521
        if local and not bound_location:
3400
3522
            raise errors.LocalRequiresBoundBranch()
3401
3523
        master_branch = None
3402
 
        source_is_master = False
3403
 
        if bound_location:
3404
 
            # bound_location comes from a config file, some care has to be
3405
 
            # taken to relate it to source.user_url
3406
 
            normalized = urlutils.normalize_url(bound_location)
3407
 
            try:
3408
 
                relpath = self.source.user_transport.relpath(normalized)
3409
 
                source_is_master = (relpath == '')
3410
 
            except (errors.PathNotChild, errors.InvalidURL):
3411
 
                source_is_master = False
 
3524
        source_is_master = (self.source.user_url == bound_location)
3412
3525
        if not local and bound_location and not source_is_master:
3413
3526
            # not pulling from master, so we need to update master.
3414
3527
            master_branch = self.target.get_master_branch(possible_transports)
3427
3540
            if master_branch:
3428
3541
                master_branch.unlock()
3429
3542
 
3430
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
3543
    def push(self, overwrite=False, stop_revision=None,
3431
3544
             _override_hook_source_branch=None):
3432
3545
        """See InterBranch.push.
3433
3546
 
3434
3547
        This is the basic concrete implementation of push()
3435
3548
 
3436
 
        :param _override_hook_source_branch: If specified, run the hooks
3437
 
            passing this Branch as the source, rather than self.  This is for
3438
 
            use of RemoteBranch, where push is delegated to the underlying
3439
 
            vfs-based Branch.
 
3549
        :param _override_hook_source_branch: If specified, run
 
3550
        the hooks passing this Branch as the source, rather than self.
 
3551
        This is for use of RemoteBranch, where push is delegated to the
 
3552
        underlying vfs-based Branch.
3440
3553
        """
3441
 
        if lossy:
3442
 
            raise errors.LossyPushToSameVCS(self.source, self.target)
3443
3554
        # TODO: Public option to disable running hooks - should be trivial but
3444
3555
        # needs tests.
3445
 
 
3446
 
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3447
 
        op.add_cleanup(self.source.lock_read().unlock)
3448
 
        op.add_cleanup(self.target.lock_write().unlock)
3449
 
        return op.run(overwrite, stop_revision,
3450
 
            _override_hook_source_branch=_override_hook_source_branch)
3451
 
 
3452
 
    def _basic_push(self, overwrite, stop_revision):
3453
 
        """Basic implementation of push without bound branches or hooks.
3454
 
 
3455
 
        Must be called with source read locked and target write locked.
3456
 
        """
3457
 
        result = BranchPushResult()
3458
 
        result.source_branch = self.source
3459
 
        result.target_branch = self.target
3460
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3461
 
        self.source.update_references(self.target)
3462
 
        if result.old_revid != stop_revision:
3463
 
            # We assume that during 'push' this repository is closer than
3464
 
            # the target.
3465
 
            graph = self.source.repository.get_graph(self.target.repository)
3466
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3467
 
                    graph=graph)
3468
 
        if self.source._push_should_merge_tags():
3469
 
            result.tag_updates, result.tag_conflicts = (
3470
 
                self.source.tags.merge_to(self.target.tags, overwrite))
3471
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3472
 
        return result
3473
 
 
3474
 
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
 
3556
        self.source.lock_read()
 
3557
        try:
 
3558
            return _run_with_write_locked_target(
 
3559
                self.target, self._push_with_bound_branches, overwrite,
 
3560
                stop_revision,
 
3561
                _override_hook_source_branch=_override_hook_source_branch)
 
3562
        finally:
 
3563
            self.source.unlock()
 
3564
 
 
3565
    def _push_with_bound_branches(self, overwrite, stop_revision,
3475
3566
            _override_hook_source_branch=None):
3476
3567
        """Push from source into target, and into target's master if any.
3477
3568
        """
3489
3580
            # be bound to itself? -- mbp 20070507
3490
3581
            master_branch = self.target.get_master_branch()
3491
3582
            master_branch.lock_write()
3492
 
            operation.add_cleanup(master_branch.unlock)
3493
 
            # push into the master from the source branch.
3494
 
            master_inter = InterBranch.get(self.source, master_branch)
3495
 
            master_inter._basic_push(overwrite, stop_revision)
3496
 
            # and push into the target branch from the source. Note that
3497
 
            # we push from the source branch again, because it's considered
3498
 
            # the highest bandwidth repository.
3499
 
            result = self._basic_push(overwrite, stop_revision)
3500
 
            result.master_branch = master_branch
3501
 
            result.local_branch = self.target
 
3583
            try:
 
3584
                # push into the master from the source branch.
 
3585
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3586
                # and push into the target branch from the source. Note that we
 
3587
                # push from the source branch again, because it's considered the
 
3588
                # highest bandwidth repository.
 
3589
                result = self.source._basic_push(self.target, overwrite,
 
3590
                    stop_revision)
 
3591
                result.master_branch = master_branch
 
3592
                result.local_branch = self.target
 
3593
                _run_hooks()
 
3594
                return result
 
3595
            finally:
 
3596
                master_branch.unlock()
3502
3597
        else:
3503
 
            master_branch = None
3504
3598
            # no master branch
3505
 
            result = self._basic_push(overwrite, stop_revision)
 
3599
            result = self.source._basic_push(self.target, overwrite,
 
3600
                stop_revision)
3506
3601
            # TODO: Why set master_branch and local_branch if there's no
3507
3602
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3508
3603
            # 20070504
3509
3604
            result.master_branch = self.target
3510
3605
            result.local_branch = None
3511
 
        _run_hooks()
3512
 
        return result
 
3606
            _run_hooks()
 
3607
            return result
3513
3608
 
3514
3609
    def _pull(self, overwrite=False, stop_revision=None,
3515
3610
             possible_transports=None, _hook_master=None, run_hooks=True,
3525
3620
        :param run_hooks: Private parameter - if false, this branch
3526
3621
            is being called because it's the master of the primary branch,
3527
3622
            so it should not run its hooks.
3528
 
            is being called because it's the master of the primary branch,
3529
 
            so it should not run its hooks.
3530
3623
        :param _override_hook_target: Private parameter - set the branch to be
3531
3624
            supplied as the target_branch to pull hooks.
3532
3625
        :param local: Only update the local branch, and not the bound branch.
3551
3644
            # -- JRV20090506
3552
3645
            result.old_revno, result.old_revid = \
3553
3646
                self.target.last_revision_info()
3554
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3555
 
                graph=graph)
 
3647
            self.target.update_revisions(self.source, stop_revision,
 
3648
                overwrite=overwrite, graph=graph)
3556
3649
            # TODO: The old revid should be specified when merging tags, 
3557
3650
            # so a tags implementation that versions tags can only 
3558
3651
            # pull in the most recent changes. -- JRV20090506
3559
 
            result.tag_updates, result.tag_conflicts = (
3560
 
                self.source.tags.merge_to(self.target.tags, overwrite,
3561
 
                    ignore_master=not merge_tags_to_master))
 
3652
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3653
                overwrite, ignore_master=not merge_tags_to_master)
3562
3654
            result.new_revno, result.new_revid = self.target.last_revision_info()
3563
3655
            if _hook_master:
3564
3656
                result.master_branch = _hook_master