/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-02-19 15:23:08 UTC
  • mto: (5582.12.2 weave-plugin)
  • mto: This revision was merged to the branch mainline in revision 5718.
  • Revision ID: jelmer@samba.org-20110219152308-5shhc4rj0ez4oa12
move xml4 to weave plugin.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
25
25
        bzrdir,
26
26
        cache_utf8,
27
27
        config as _mod_config,
 
28
        controldir,
28
29
        debug,
29
30
        errors,
 
31
        fetch,
 
32
        graph as _mod_graph,
30
33
        lockdir,
31
34
        lockable_files,
 
35
        remote,
32
36
        repository,
33
37
        revision as _mod_revision,
34
38
        rio,
49
53
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
54
from bzrlib.hooks import HookPoint, Hooks
51
55
from bzrlib.inter import InterObject
52
 
from bzrlib.lock import _RelockDebugMixin
 
56
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
57
from bzrlib import registry
54
58
from bzrlib.symbol_versioning import (
55
59
    deprecated_in,
63
67
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
68
 
65
69
 
66
 
class Branch(bzrdir.ControlComponent):
 
70
class Branch(controldir.ControlComponent):
67
71
    """Branch holding a history of revisions.
68
72
 
69
73
    :ivar base:
90
94
        self._revision_id_to_revno_cache = None
91
95
        self._partial_revision_id_to_revno_cache = {}
92
96
        self._partial_revision_history_cache = []
 
97
        self._tags_bytes = None
93
98
        self._last_revision_info_cache = None
94
99
        self._merge_sorted_revisions_cache = None
95
100
        self._open_hook()
102
107
 
103
108
    def _activate_fallback_location(self, url):
104
109
        """Activate the branch/repository from url as a fallback repository."""
 
110
        for existing_fallback_repo in self.repository._fallback_repositories:
 
111
            if existing_fallback_repo.user_url == url:
 
112
                # This fallback is already configured.  This probably only
 
113
                # happens because BzrDir.sprout is a horrible mess.  To avoid
 
114
                # confusing _unstack we don't add this a second time.
 
115
                mutter('duplicate activation of fallback %r on %r', url, self)
 
116
                return
105
117
        repo = self._get_fallback_repository(url)
106
118
        if repo.has_same_location(self.repository):
107
119
            raise errors.UnstackableLocationError(self.user_url, url)
197
209
        return self.supports_tags() and self.tags.get_tag_dict()
198
210
 
199
211
    def get_config(self):
 
212
        """Get a bzrlib.config.BranchConfig for this Branch.
 
213
 
 
214
        This can then be used to get and set configuration options for the
 
215
        branch.
 
216
 
 
217
        :return: A bzrlib.config.BranchConfig.
 
218
        """
200
219
        return BranchConfig(self)
201
220
 
202
221
    def _get_config(self):
218
237
            possible_transports=[self.bzrdir.root_transport])
219
238
        return a_branch.repository
220
239
 
 
240
    @needs_read_lock
221
241
    def _get_tags_bytes(self):
222
242
        """Get the bytes of a serialised tags dict.
223
243
 
230
250
        :return: The bytes of the tags file.
231
251
        :seealso: Branch._set_tags_bytes.
232
252
        """
233
 
        return self._transport.get_bytes('tags')
 
253
        if self._tags_bytes is None:
 
254
            self._tags_bytes = self._transport.get_bytes('tags')
 
255
        return self._tags_bytes
234
256
 
235
257
    def _get_nick(self, local=False, possible_transports=None):
236
258
        config = self.get_config()
238
260
        if not local and not config.has_explicit_nickname():
239
261
            try:
240
262
                master = self.get_master_branch(possible_transports)
 
263
                if master and self.user_url == master.user_url:
 
264
                    raise errors.RecursiveBind(self.user_url)
241
265
                if master is not None:
242
266
                    # return the master branch value
243
267
                    return master.nick
 
268
            except errors.RecursiveBind, e:
 
269
                raise e
244
270
            except errors.BzrError, e:
245
271
                # Silently fall back to local implicit nick if the master is
246
272
                # unavailable
283
309
        new_history.reverse()
284
310
        return new_history
285
311
 
286
 
    def lock_write(self):
 
312
    def lock_write(self, token=None):
 
313
        """Lock the branch for write operations.
 
314
 
 
315
        :param token: A token to permit reacquiring a previously held and
 
316
            preserved lock.
 
317
        :return: A BranchWriteLockResult.
 
318
        """
287
319
        raise NotImplementedError(self.lock_write)
288
320
 
289
321
    def lock_read(self):
 
322
        """Lock the branch for read operations.
 
323
 
 
324
        :return: A bzrlib.lock.LogicalLockResult.
 
325
        """
290
326
        raise NotImplementedError(self.lock_read)
291
327
 
292
328
    def unlock(self):
626
662
        raise errors.UnsupportedOperation(self.get_reference_info, self)
627
663
 
628
664
    @needs_write_lock
629
 
    def fetch(self, from_branch, last_revision=None, pb=None):
 
665
    def fetch(self, from_branch, last_revision=None, pb=None, fetch_spec=None):
630
666
        """Copy revisions from from_branch into this branch.
631
667
 
632
668
        :param from_branch: Where to copy from.
633
669
        :param last_revision: What revision to stop at (None for at the end
634
670
                              of the branch.
635
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.
636
676
        :return: None
637
677
        """
 
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.")
638
681
        if self.base == from_branch.base:
639
682
            return (0, [])
640
683
        if pb is not None:
643
686
                % "pb parameter to fetch()")
644
687
        from_branch.lock_read()
645
688
        try:
646
 
            if last_revision is None:
 
689
            if last_revision is None and fetch_spec is None:
647
690
                last_revision = from_branch.last_revision()
648
691
                last_revision = _mod_revision.ensure_null(last_revision)
649
692
            return self.repository.fetch(from_branch.repository,
650
693
                                         revision_id=last_revision,
651
 
                                         pb=pb)
 
694
                                         pb=pb, fetch_spec=fetch_spec)
652
695
        finally:
653
696
            from_branch.unlock()
654
697
 
782
825
            old_repository = self.repository
783
826
            if len(old_repository._fallback_repositories) != 1:
784
827
                raise AssertionError("can't cope with fallback repositories "
785
 
                    "of %r" % (self.repository,))
786
 
            # unlock it, including unlocking the fallback
 
828
                    "of %r (fallbacks: %r)" % (old_repository,
 
829
                        old_repository._fallback_repositories))
 
830
            # Open the new repository object.
 
831
            # Repositories don't offer an interface to remove fallback
 
832
            # repositories today; take the conceptually simpler option and just
 
833
            # reopen it.  We reopen it starting from the URL so that we
 
834
            # get a separate connection for RemoteRepositories and can
 
835
            # stream from one of them to the other.  This does mean doing
 
836
            # separate SSH connection setup, but unstacking is not a
 
837
            # common operation so it's tolerable.
 
838
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
839
            new_repository = new_bzrdir.find_repository()
 
840
            if new_repository._fallback_repositories:
 
841
                raise AssertionError("didn't expect %r to have "
 
842
                    "fallback_repositories"
 
843
                    % (self.repository,))
 
844
            # Replace self.repository with the new repository.
 
845
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
846
            # lock count) of self.repository to the new repository.
 
847
            lock_token = old_repository.lock_write().repository_token
 
848
            self.repository = new_repository
 
849
            if isinstance(self, remote.RemoteBranch):
 
850
                # Remote branches can have a second reference to the old
 
851
                # repository that need to be replaced.
 
852
                if self._real_branch is not None:
 
853
                    self._real_branch.repository = new_repository
 
854
            self.repository.lock_write(token=lock_token)
 
855
            if lock_token is not None:
 
856
                old_repository.leave_lock_in_place()
787
857
            old_repository.unlock()
 
858
            if lock_token is not None:
 
859
                # XXX: self.repository.leave_lock_in_place() before this
 
860
                # function will not be preserved.  Fortunately that doesn't
 
861
                # affect the current default format (2a), and would be a
 
862
                # corner-case anyway.
 
863
                #  - Andrew Bennetts, 2010/06/30
 
864
                self.repository.dont_leave_lock_in_place()
 
865
            old_lock_count = 0
 
866
            while True:
 
867
                try:
 
868
                    old_repository.unlock()
 
869
                except errors.LockNotHeld:
 
870
                    break
 
871
                old_lock_count += 1
 
872
            if old_lock_count == 0:
 
873
                raise AssertionError(
 
874
                    'old_repository should have been locked at least once.')
 
875
            for i in range(old_lock_count-1):
 
876
                self.repository.lock_write()
 
877
            # Fetch from the old repository into the new.
788
878
            old_repository.lock_read()
789
879
            try:
790
 
                # Repositories don't offer an interface to remove fallback
791
 
                # repositories today; take the conceptually simpler option and just
792
 
                # reopen it.  We reopen it starting from the URL so that we
793
 
                # get a separate connection for RemoteRepositories and can
794
 
                # stream from one of them to the other.  This does mean doing
795
 
                # separate SSH connection setup, but unstacking is not a
796
 
                # common operation so it's tolerable.
797
 
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
798
 
                new_repository = new_bzrdir.find_repository()
799
 
                self.repository = new_repository
800
 
                if self.repository._fallback_repositories:
801
 
                    raise AssertionError("didn't expect %r to have "
802
 
                        "fallback_repositories"
803
 
                        % (self.repository,))
804
 
                # this is not paired with an unlock because it's just restoring
805
 
                # the previous state; the lock's released when set_stacked_on_url
806
 
                # returns
807
 
                self.repository.lock_write()
808
880
                # XXX: If you unstack a branch while it has a working tree
809
881
                # with a pending merge, the pending-merged revisions will no
810
882
                # longer be present.  You can (probably) revert and remerge.
811
 
                #
812
 
                # XXX: This only fetches up to the tip of the repository; it
813
 
                # doesn't bring across any tags.  That's fairly consistent
814
 
                # with how branch works, but perhaps not ideal.
815
 
                self.repository.fetch(old_repository,
816
 
                    revision_id=self.last_revision(),
817
 
                    find_ghosts=True)
 
883
                try:
 
884
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
885
                except errors.TagsNotSupported:
 
886
                    tags_to_fetch = set()
 
887
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
 
888
                    old_repository, required_ids=[self.last_revision()],
 
889
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
890
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
818
891
            finally:
819
892
                old_repository.unlock()
820
893
        finally:
825
898
 
826
899
        :seealso: Branch._get_tags_bytes.
827
900
        """
828
 
        return _run_with_write_locked_target(self, self._transport.put_bytes,
829
 
            'tags', bytes)
 
901
        return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
 
902
                bytes)
 
903
 
 
904
    def _set_tags_bytes_locked(self, bytes):
 
905
        self._tags_bytes = bytes
 
906
        return self._transport.put_bytes('tags', bytes)
830
907
 
831
908
    def _cache_revision_history(self, rev_history):
832
909
        """Set the cached revision history to rev_history.
862
939
        self._merge_sorted_revisions_cache = None
863
940
        self._partial_revision_history_cache = []
864
941
        self._partial_revision_id_to_revno_cache = {}
 
942
        self._tags_bytes = None
865
943
 
866
944
    def _gen_revision_history(self):
867
945
        """Return sequence of revision hashes on to this branch.
951
1029
                raise errors.NoSuchRevision(self, stop_revision)
952
1030
        return other_history[self_len:stop_revision]
953
1031
 
954
 
    @needs_write_lock
955
1032
    def update_revisions(self, other, stop_revision=None, overwrite=False,
956
 
                         graph=None):
 
1033
                         graph=None, fetch_tags=True):
957
1034
        """Pull in new perfect-fit revisions.
958
1035
 
959
1036
        :param other: Another Branch to pull from
962
1039
            to see if it is a proper descendant.
963
1040
        :param graph: A Graph object that can be used to query history
964
1041
            information. This can be None.
 
1042
        :param fetch_tags: Flag that specifies if tags from other should be
 
1043
            fetched too.
965
1044
        :return: None
966
1045
        """
967
1046
        return InterBranch.get(other, self).update_revisions(stop_revision,
968
 
            overwrite, graph)
 
1047
            overwrite, graph, fetch_tags=fetch_tags)
969
1048
 
 
1049
    @deprecated_method(deprecated_in((2, 4, 0)))
970
1050
    def import_last_revision_info(self, source_repo, revno, revid):
971
1051
        """Set the last revision info, importing from another repo if necessary.
972
1052
 
973
 
        This is used by the bound branch code to upload a revision to
974
 
        the master branch first before updating the tip of the local branch.
975
 
 
976
1053
        :param source_repo: Source repository to optionally fetch from
977
1054
        :param revno: Revision number of the new tip
978
1055
        :param revid: Revision id of the new tip
981
1058
            self.repository.fetch(source_repo, revision_id=revid)
982
1059
        self.set_last_revision_info(revno, revid)
983
1060
 
 
1061
    def import_last_revision_info_and_tags(self, source, revno, revid):
 
1062
        """Set the last revision info, importing from another repo if necessary.
 
1063
 
 
1064
        This is used by the bound branch code to upload a revision to
 
1065
        the master branch first before updating the tip of the local branch.
 
1066
        Revisions referenced by source's tags are also transferred.
 
1067
 
 
1068
        :param source: Source branch to optionally fetch from
 
1069
        :param revno: Revision number of the new tip
 
1070
        :param revid: Revision id of the new tip
 
1071
        """
 
1072
        if not self.repository.has_same_location(source.repository):
 
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)
 
1081
        self.set_last_revision_info(revno, revid)
 
1082
 
984
1083
    def revision_id_to_revno(self, revision_id):
985
1084
        """Given a revision id, return its revno"""
986
1085
        if _mod_revision.is_null(revision_id):
1006
1105
            self._extend_partial_history(distance_from_last)
1007
1106
        return self._partial_revision_history_cache[distance_from_last]
1008
1107
 
1009
 
    @needs_write_lock
1010
1108
    def pull(self, source, overwrite=False, stop_revision=None,
1011
1109
             possible_transports=None, *args, **kwargs):
1012
1110
        """Mirror source into this branch.
1208
1306
        return result
1209
1307
 
1210
1308
    @needs_read_lock
1211
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1309
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1310
            repository=None):
1212
1311
        """Create a new line of development from the branch, into to_bzrdir.
1213
1312
 
1214
1313
        to_bzrdir controls the branch format.
1219
1318
        if (repository_policy is not None and
1220
1319
            repository_policy.requires_stacking()):
1221
1320
            to_bzrdir._format.require_stacking(_skip_repo=True)
1222
 
        result = to_bzrdir.create_branch()
 
1321
        result = to_bzrdir.create_branch(repository=repository)
1223
1322
        result.lock_write()
1224
1323
        try:
1225
1324
            if repository_policy is not None:
1255
1354
                revno = 1
1256
1355
        destination.set_last_revision_info(revno, revision_id)
1257
1356
 
1258
 
    @needs_read_lock
1259
1357
    def copy_content_into(self, destination, revision_id=None):
1260
1358
        """Copy the content of self into destination.
1261
1359
 
1262
1360
        revision_id: if not None, the revision history in the new branch will
1263
1361
                     be truncated to end with revision_id.
1264
1362
        """
1265
 
        self.update_references(destination)
1266
 
        self._synchronize_history(destination, revision_id)
1267
 
        try:
1268
 
            parent = self.get_parent()
1269
 
        except errors.InaccessibleParent, e:
1270
 
            mutter('parent was not accessible to copy: %s', e)
1271
 
        else:
1272
 
            if parent:
1273
 
                destination.set_parent(parent)
1274
 
        if self._push_should_merge_tags():
1275
 
            self.tags.merge_to(destination.tags)
 
1363
        return InterBranch.get(self, destination).copy_content_into(
 
1364
            revision_id=revision_id)
1276
1365
 
1277
1366
    def update_references(self, target):
1278
1367
        if not getattr(self._format, 'supports_reference_locations', False):
1323
1412
        """Return the most suitable metadir for a checkout of this branch.
1324
1413
        Weaves are used if this branch's repository uses weaves.
1325
1414
        """
1326
 
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1327
 
            from bzrlib.repofmt import weaverepo
1328
 
            format = bzrdir.BzrDirMetaFormat1()
1329
 
            format.repository_format = weaverepo.RepositoryFormat7()
1330
 
        else:
1331
 
            format = self.repository.bzrdir.checkout_metadir()
1332
 
            format.set_branch_format(self._format)
 
1415
        format = self.repository.bzrdir.checkout_metadir()
 
1416
        format.set_branch_format(self._format)
1333
1417
        return format
1334
1418
 
1335
1419
    def create_clone_on_transport(self, to_transport, revision_id=None,
1336
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1420
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1421
        no_tree=None):
1337
1422
        """Create a clone of this branch and its bzrdir.
1338
1423
 
1339
1424
        :param to_transport: The transport to clone onto.
1346
1431
        """
1347
1432
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1348
1433
        # clone call. Or something. 20090224 RBC/spiv.
 
1434
        # XXX: Should this perhaps clone colocated branches as well, 
 
1435
        # rather than just the default branch? 20100319 JRV
1349
1436
        if revision_id is None:
1350
1437
            revision_id = self.last_revision()
1351
1438
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1352
1439
            revision_id=revision_id, stacked_on=stacked_on,
1353
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1440
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1441
            no_tree=no_tree)
1354
1442
        return dir_to.open_branch()
1355
1443
 
1356
1444
    def create_checkout(self, to_location, revision_id=None,
1481
1569
     * an open routine.
1482
1570
 
1483
1571
    Formats are placed in an dict by their format string for reference
1484
 
    during branch opening. Its not required that these be instances, they
 
1572
    during branch opening. It's not required that these be instances, they
1485
1573
    can be classes themselves with class methods - it simply depends on
1486
1574
    whether state is needed for a given format or not.
1487
1575
 
1496
1584
    _formats = {}
1497
1585
    """The known formats."""
1498
1586
 
 
1587
    _extra_formats = []
 
1588
    """Extra formats that can not be part of a metadir."""
 
1589
 
1499
1590
    can_set_append_revisions_only = True
1500
1591
 
1501
1592
    def __eq__(self, other):
1510
1601
        try:
1511
1602
            transport = a_bzrdir.get_branch_transport(None, name=name)
1512
1603
            format_string = transport.get_bytes("format")
1513
 
            return klass._formats[format_string]
 
1604
            format = klass._formats[format_string]
 
1605
            if isinstance(format, MetaDirBranchFormatFactory):
 
1606
                return format()
 
1607
            return format
1514
1608
        except errors.NoSuchFile:
1515
1609
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1516
1610
        except KeyError:
1521
1615
        """Return the current default format."""
1522
1616
        return klass._default_format
1523
1617
 
1524
 
    def get_reference(self, a_bzrdir):
 
1618
    @classmethod
 
1619
    def get_formats(klass):
 
1620
        """Get all the known formats.
 
1621
 
 
1622
        Warning: This triggers a load of all lazy registered formats: do not
 
1623
        use except when that is desireed.
 
1624
        """
 
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
 
1631
 
 
1632
    def get_reference(self, a_bzrdir, name=None):
1525
1633
        """Get the target reference of the branch in a_bzrdir.
1526
1634
 
1527
1635
        format probing must have been completed before calling
1529
1637
        in a_bzrdir is correct.
1530
1638
 
1531
1639
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1640
        :param name: Name of the colocated branch to fetch
1532
1641
        :return: None if the branch is not a reference branch.
1533
1642
        """
1534
1643
        return None
1535
1644
 
1536
1645
    @classmethod
1537
 
    def set_reference(self, a_bzrdir, to_branch):
 
1646
    def set_reference(self, a_bzrdir, name, to_branch):
1538
1647
        """Set the target reference of the branch in a_bzrdir.
1539
1648
 
1540
1649
        format probing must have been completed before calling
1542
1651
        in a_bzrdir is correct.
1543
1652
 
1544
1653
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1654
        :param name: Name of colocated branch to set, None for default
1545
1655
        :param to_branch: branch that the checkout is to reference
1546
1656
        """
1547
1657
        raise NotImplementedError(self.set_reference)
1563
1673
            hook(params)
1564
1674
 
1565
1675
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1566
 
                           lock_type='metadir', set_format=True):
 
1676
                           repository=None):
1567
1677
        """Initialize a branch in a bzrdir, with specified files
1568
1678
 
1569
1679
        :param a_bzrdir: The bzrdir to initialize the branch in
1570
1680
        :param utf8_files: The files to create as a list of
1571
1681
            (filename, content) tuples
1572
1682
        :param name: Name of colocated branch to create, if any
1573
 
        :param set_format: If True, set the format with
1574
 
            self.get_format_string.  (BzrBranch4 has its format set
1575
 
            elsewhere)
1576
1683
        :return: a branch in this format
1577
1684
        """
1578
1685
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1579
1686
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1580
 
        lock_map = {
1581
 
            'metadir': ('lock', lockdir.LockDir),
1582
 
            'branch4': ('branch-lock', lockable_files.TransportLock),
1583
 
        }
1584
 
        lock_name, lock_class = lock_map[lock_type]
1585
1687
        control_files = lockable_files.LockableFiles(branch_transport,
1586
 
            lock_name, lock_class)
 
1688
            'lock', lockdir.LockDir)
1587
1689
        control_files.create_lock()
 
1690
        control_files.lock_write()
1588
1691
        try:
1589
 
            control_files.lock_write()
1590
 
        except errors.LockContention:
1591
 
            if lock_type != 'branch4':
1592
 
                raise
1593
 
            lock_taken = False
1594
 
        else:
1595
 
            lock_taken = True
1596
 
        if set_format:
1597
1692
            utf8_files += [('format', self.get_format_string())]
1598
 
        try:
1599
1693
            for (filename, content) in utf8_files:
1600
1694
                branch_transport.put_bytes(
1601
1695
                    filename, content,
1602
1696
                    mode=a_bzrdir._get_file_mode())
1603
1697
        finally:
1604
 
            if lock_taken:
1605
 
                control_files.unlock()
1606
 
        branch = self.open(a_bzrdir, name, _found=True)
 
1698
            control_files.unlock()
 
1699
        branch = self.open(a_bzrdir, name, _found=True,
 
1700
                found_repository=repository)
1607
1701
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1608
1702
        return branch
1609
1703
 
1610
 
    def initialize(self, a_bzrdir, name=None):
 
1704
    def initialize(self, a_bzrdir, name=None, repository=None):
1611
1705
        """Create a branch of this format in a_bzrdir.
1612
1706
        
1613
1707
        :param name: Name of the colocated branch to create.
1647
1741
        """
1648
1742
        raise NotImplementedError(self.network_name)
1649
1743
 
1650
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1744
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
1745
            found_repository=None):
1651
1746
        """Return the branch object for a_bzrdir
1652
1747
 
1653
1748
        :param a_bzrdir: A BzrDir that contains a branch.
1660
1755
        raise NotImplementedError(self.open)
1661
1756
 
1662
1757
    @classmethod
 
1758
    def register_extra_format(klass, format):
 
1759
        """Register a branch format that can not be part of a metadir.
 
1760
 
 
1761
        This is mainly useful to allow custom branch formats, such as
 
1762
        older Bazaar formats and foreign formats, to be tested
 
1763
        """
 
1764
        klass._extra_formats.append(format)
 
1765
        network_format_registry.register(
 
1766
            format.network_name(), format.__class__)
 
1767
 
 
1768
    @classmethod
1663
1769
    def register_format(klass, format):
1664
 
        """Register a metadir format."""
 
1770
        """Register a metadir format.
 
1771
        
 
1772
        See MetaDirBranchFormatFactory for the ability to register a format
 
1773
        without loading the code the format needs until it is actually used.
 
1774
        """
1665
1775
        klass._formats[format.get_format_string()] = format
1666
1776
        # Metadir formats have a network name of their format string, and get
1667
 
        # registered as class factories.
1668
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1777
        # registered as factories.
 
1778
        if isinstance(format, MetaDirBranchFormatFactory):
 
1779
            network_format_registry.register(format.get_format_string(), format)
 
1780
        else:
 
1781
            network_format_registry.register(format.get_format_string(),
 
1782
                format.__class__)
1669
1783
 
1670
1784
    @classmethod
1671
1785
    def set_default_format(klass, format):
1683
1797
    def unregister_format(klass, format):
1684
1798
        del klass._formats[format.get_format_string()]
1685
1799
 
 
1800
    @classmethod
 
1801
    def unregister_extra_format(klass, format):
 
1802
        klass._extra_formats.remove(format)
 
1803
 
1686
1804
    def __str__(self):
1687
1805
        return self.get_format_description().rstrip()
1688
1806
 
1691
1809
        return False  # by default
1692
1810
 
1693
1811
 
 
1812
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1813
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1814
    
 
1815
    While none of the built in BranchFormats are lazy registered yet,
 
1816
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1817
    use it, and the bzr-loom plugin uses it as well (see
 
1818
    bzrlib.plugins.loom.formats).
 
1819
    """
 
1820
 
 
1821
    def __init__(self, format_string, module_name, member_name):
 
1822
        """Create a MetaDirBranchFormatFactory.
 
1823
 
 
1824
        :param format_string: The format string the format has.
 
1825
        :param module_name: Module to load the format class from.
 
1826
        :param member_name: Attribute name within the module for the format class.
 
1827
        """
 
1828
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1829
        self._format_string = format_string
 
1830
        
 
1831
    def get_format_string(self):
 
1832
        """See BranchFormat.get_format_string."""
 
1833
        return self._format_string
 
1834
 
 
1835
    def __call__(self):
 
1836
        """Used for network_format_registry support."""
 
1837
        return self.get_obj()()
 
1838
 
 
1839
 
1694
1840
class BranchHooks(Hooks):
1695
1841
    """A dictionary mapping hook name to a list of callables for branch hooks.
1696
1842
 
1723
1869
            "with a bzrlib.branch.PullResult object and only runs in the "
1724
1870
            "bzr client.", (0, 15), None))
1725
1871
        self.create_hook(HookPoint('pre_commit',
1726
 
            "Called after a commit is calculated but before it is is "
 
1872
            "Called after a commit is calculated but before it is "
1727
1873
            "completed. pre_commit is called with (local, master, old_revno, "
1728
1874
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1729
1875
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1766
1912
            "all are called with the url returned from the previous hook."
1767
1913
            "The order is however undefined.", (1, 9), None))
1768
1914
        self.create_hook(HookPoint('automatic_tag_name',
1769
 
            "Called to determine an automatic tag name for a revision."
 
1915
            "Called to determine an automatic tag name for a revision. "
1770
1916
            "automatic_tag_name is called with (branch, revision_id) and "
1771
1917
            "should return a tag name or None if no tag name could be "
1772
1918
            "determined. The first non-None tag name returned will be used.",
1863
2009
        return self.__dict__ == other.__dict__
1864
2010
 
1865
2011
    def __repr__(self):
1866
 
        if self.branch:
1867
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1868
 
        else:
1869
 
            return "<%s of format:%s bzrdir:%s>" % (
1870
 
                self.__class__.__name__, self.branch,
1871
 
                self.format, self.bzrdir)
 
2012
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1872
2013
 
1873
2014
 
1874
2015
class SwitchHookParams(object):
1904
2045
            self.revision_id)
1905
2046
 
1906
2047
 
1907
 
class BzrBranchFormat4(BranchFormat):
1908
 
    """Bzr branch format 4.
1909
 
 
1910
 
    This format has:
1911
 
     - a revision-history file.
1912
 
     - a branch-lock lock file [ to be shared with the bzrdir ]
1913
 
    """
1914
 
 
1915
 
    def get_format_description(self):
1916
 
        """See BranchFormat.get_format_description()."""
1917
 
        return "Branch format 4"
1918
 
 
1919
 
    def initialize(self, a_bzrdir, name=None):
1920
 
        """Create a branch of this format in a_bzrdir."""
1921
 
        utf8_files = [('revision-history', ''),
1922
 
                      ('branch-name', ''),
1923
 
                      ]
1924
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1925
 
                                       lock_type='branch4', set_format=False)
1926
 
 
1927
 
    def __init__(self):
1928
 
        super(BzrBranchFormat4, self).__init__()
1929
 
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1930
 
 
1931
 
    def network_name(self):
1932
 
        """The network name for this format is the control dirs disk label."""
1933
 
        return self._matchingbzrdir.get_format_string()
1934
 
 
1935
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1936
 
        """See BranchFormat.open()."""
1937
 
        if not _found:
1938
 
            # we are being called directly and must probe.
1939
 
            raise NotImplementedError
1940
 
        return BzrBranch(_format=self,
1941
 
                         _control_files=a_bzrdir._control_files,
1942
 
                         a_bzrdir=a_bzrdir,
1943
 
                         name=name,
1944
 
                         _repository=a_bzrdir.open_repository())
1945
 
 
1946
 
    def __str__(self):
1947
 
        return "Bazaar-NG branch format 4"
1948
 
 
1949
 
 
1950
2048
class BranchFormatMetadir(BranchFormat):
1951
2049
    """Common logic for meta-dir based branch formats."""
1952
2050
 
1961
2059
        """
1962
2060
        return self.get_format_string()
1963
2061
 
1964
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
2062
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2063
            found_repository=None):
1965
2064
        """See BranchFormat.open()."""
1966
2065
        if not _found:
1967
2066
            format = BranchFormat.find_format(a_bzrdir, name=name)
1972
2071
        try:
1973
2072
            control_files = lockable_files.LockableFiles(transport, 'lock',
1974
2073
                                                         lockdir.LockDir)
 
2074
            if found_repository is None:
 
2075
                found_repository = a_bzrdir.find_repository()
1975
2076
            return self._branch_class()(_format=self,
1976
2077
                              _control_files=control_files,
1977
2078
                              name=name,
1978
2079
                              a_bzrdir=a_bzrdir,
1979
 
                              _repository=a_bzrdir.find_repository(),
 
2080
                              _repository=found_repository,
1980
2081
                              ignore_fallbacks=ignore_fallbacks)
1981
2082
        except errors.NoSuchFile:
1982
2083
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2014
2115
        """See BranchFormat.get_format_description()."""
2015
2116
        return "Branch format 5"
2016
2117
 
2017
 
    def initialize(self, a_bzrdir, name=None):
 
2118
    def initialize(self, a_bzrdir, name=None, repository=None):
2018
2119
        """Create a branch of this format in a_bzrdir."""
2019
2120
        utf8_files = [('revision-history', ''),
2020
2121
                      ('branch-name', ''),
2021
2122
                      ]
2022
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2123
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2023
2124
 
2024
2125
    def supports_tags(self):
2025
2126
        return False
2047
2148
        """See BranchFormat.get_format_description()."""
2048
2149
        return "Branch format 6"
2049
2150
 
2050
 
    def initialize(self, a_bzrdir, name=None):
 
2151
    def initialize(self, a_bzrdir, name=None, repository=None):
2051
2152
        """Create a branch of this format in a_bzrdir."""
2052
2153
        utf8_files = [('last-revision', '0 null:\n'),
2053
2154
                      ('branch.conf', ''),
2054
2155
                      ('tags', ''),
2055
2156
                      ]
2056
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2157
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2057
2158
 
2058
2159
    def make_tags(self, branch):
2059
2160
        """See bzrlib.branch.BranchFormat.make_tags()."""
2077
2178
        """See BranchFormat.get_format_description()."""
2078
2179
        return "Branch format 8"
2079
2180
 
2080
 
    def initialize(self, a_bzrdir, name=None):
 
2181
    def initialize(self, a_bzrdir, name=None, repository=None):
2081
2182
        """Create a branch of this format in a_bzrdir."""
2082
2183
        utf8_files = [('last-revision', '0 null:\n'),
2083
2184
                      ('branch.conf', ''),
2084
2185
                      ('tags', ''),
2085
2186
                      ('references', '')
2086
2187
                      ]
2087
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2188
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2088
2189
 
2089
2190
    def __init__(self):
2090
2191
        super(BzrBranchFormat8, self).__init__()
2113
2214
    This format was introduced in bzr 1.6.
2114
2215
    """
2115
2216
 
2116
 
    def initialize(self, a_bzrdir, name=None):
 
2217
    def initialize(self, a_bzrdir, name=None, repository=None):
2117
2218
        """Create a branch of this format in a_bzrdir."""
2118
2219
        utf8_files = [('last-revision', '0 null:\n'),
2119
2220
                      ('branch.conf', ''),
2120
2221
                      ('tags', ''),
2121
2222
                      ]
2122
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2223
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2123
2224
 
2124
2225
    def _branch_class(self):
2125
2226
        return BzrBranch7
2157
2258
        """See BranchFormat.get_format_description()."""
2158
2259
        return "Checkout reference format 1"
2159
2260
 
2160
 
    def get_reference(self, a_bzrdir):
 
2261
    def get_reference(self, a_bzrdir, name=None):
2161
2262
        """See BranchFormat.get_reference()."""
2162
 
        transport = a_bzrdir.get_branch_transport(None)
 
2263
        transport = a_bzrdir.get_branch_transport(None, name=name)
2163
2264
        return transport.get_bytes('location')
2164
2265
 
2165
 
    def set_reference(self, a_bzrdir, to_branch):
 
2266
    def set_reference(self, a_bzrdir, name, to_branch):
2166
2267
        """See BranchFormat.set_reference()."""
2167
 
        transport = a_bzrdir.get_branch_transport(None)
 
2268
        transport = a_bzrdir.get_branch_transport(None, name=name)
2168
2269
        location = transport.put_bytes('location', to_branch.base)
2169
2270
 
2170
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
2271
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2272
            repository=None):
2171
2273
        """Create a branch of this format in a_bzrdir."""
2172
2274
        if target_branch is None:
2173
2275
            # this format does not implement branch itself, thus the implicit
2201
2303
        return clone
2202
2304
 
2203
2305
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2204
 
             possible_transports=None, ignore_fallbacks=False):
 
2306
             possible_transports=None, ignore_fallbacks=False,
 
2307
             found_repository=None):
2205
2308
        """Return the branch that the branch reference in a_bzrdir points at.
2206
2309
 
2207
2310
        :param a_bzrdir: A BzrDir that contains a branch.
2221
2324
                raise AssertionError("wrong format %r found for %r" %
2222
2325
                    (format, self))
2223
2326
        if location is None:
2224
 
            location = self.get_reference(a_bzrdir)
 
2327
            location = self.get_reference(a_bzrdir, name)
2225
2328
        real_bzrdir = bzrdir.BzrDir.open(
2226
2329
            location, possible_transports=possible_transports)
2227
2330
        result = real_bzrdir.open_branch(name=name, 
2259
2362
BranchFormat.register_format(__format7)
2260
2363
BranchFormat.register_format(__format8)
2261
2364
BranchFormat.set_default_format(__format7)
2262
 
_legacy_formats = [BzrBranchFormat4(),
2263
 
    ]
2264
 
network_format_registry.register(
2265
 
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2365
 
 
2366
 
 
2367
class BranchWriteLockResult(LogicalLockResult):
 
2368
    """The result of write locking a branch.
 
2369
 
 
2370
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2371
        None.
 
2372
    :ivar unlock: A callable which will unlock the lock.
 
2373
    """
 
2374
 
 
2375
    def __init__(self, unlock, branch_token):
 
2376
        LogicalLockResult.__init__(self, unlock)
 
2377
        self.branch_token = branch_token
 
2378
 
 
2379
    def __repr__(self):
 
2380
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2381
            self.unlock)
2266
2382
 
2267
2383
 
2268
2384
class BzrBranch(Branch, _RelockDebugMixin):
2324
2440
        return self.control_files.is_locked()
2325
2441
 
2326
2442
    def lock_write(self, token=None):
 
2443
        """Lock the branch for write operations.
 
2444
 
 
2445
        :param token: A token to permit reacquiring a previously held and
 
2446
            preserved lock.
 
2447
        :return: A BranchWriteLockResult.
 
2448
        """
2327
2449
        if not self.is_locked():
2328
2450
            self._note_lock('w')
2329
2451
        # All-in-one needs to always unlock/lock.
2335
2457
        else:
2336
2458
            took_lock = False
2337
2459
        try:
2338
 
            return self.control_files.lock_write(token=token)
 
2460
            return BranchWriteLockResult(self.unlock,
 
2461
                self.control_files.lock_write(token=token))
2339
2462
        except:
2340
2463
            if took_lock:
2341
2464
                self.repository.unlock()
2342
2465
            raise
2343
2466
 
2344
2467
    def lock_read(self):
 
2468
        """Lock the branch for read operations.
 
2469
 
 
2470
        :return: A bzrlib.lock.LogicalLockResult.
 
2471
        """
2345
2472
        if not self.is_locked():
2346
2473
            self._note_lock('r')
2347
2474
        # All-in-one needs to always unlock/lock.
2354
2481
            took_lock = False
2355
2482
        try:
2356
2483
            self.control_files.lock_read()
 
2484
            return LogicalLockResult(self.unlock)
2357
2485
        except:
2358
2486
            if took_lock:
2359
2487
                self.repository.unlock()
2515
2643
        result.target_branch = target
2516
2644
        result.old_revno, result.old_revid = target.last_revision_info()
2517
2645
        self.update_references(target)
2518
 
        if result.old_revid != self.last_revision():
 
2646
        if result.old_revid != stop_revision:
2519
2647
            # We assume that during 'push' this repository is closer than
2520
2648
            # the target.
2521
2649
            graph = self.repository.get_graph(target.repository)
2544
2672
                mode=self.bzrdir._get_file_mode())
2545
2673
 
2546
2674
 
 
2675
class BzrBranchPreSplitOut(BzrBranch):
 
2676
 
 
2677
    def _get_checkout_format(self):
 
2678
        """Return the most suitable metadir for a checkout of this branch.
 
2679
        Weaves are used if this branch's repository uses weaves.
 
2680
        """
 
2681
        from bzrlib.repofmt.weaverepo import RepositoryFormat7
 
2682
        from bzrlib.bzrdir import BzrDirMetaFormat1
 
2683
        format = BzrDirMetaFormat1()
 
2684
        format.repository_format = RepositoryFormat7()
 
2685
        return format
 
2686
 
 
2687
 
2547
2688
class BzrBranch5(BzrBranch):
2548
2689
    """A format 5 branch. This supports new features over plain branches.
2549
2690
 
2983
3124
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2984
3125
    """
2985
3126
 
 
3127
    @deprecated_method(deprecated_in((2, 3, 0)))
2986
3128
    def __int__(self):
2987
 
        # DEPRECATED: pull used to return the change in revno
 
3129
        """Return the relative change in revno.
 
3130
 
 
3131
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3132
        """
2988
3133
        return self.new_revno - self.old_revno
2989
3134
 
2990
3135
    def report(self, to_file):
3015
3160
        target, otherwise it will be None.
3016
3161
    """
3017
3162
 
 
3163
    @deprecated_method(deprecated_in((2, 3, 0)))
3018
3164
    def __int__(self):
3019
 
        # DEPRECATED: push used to return the change in revno
 
3165
        """Return the relative change in revno.
 
3166
 
 
3167
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3168
        """
3020
3169
        return self.new_revno - self.old_revno
3021
3170
 
3022
3171
    def report(self, to_file):
3145
3294
    _optimisers = []
3146
3295
    """The available optimised InterBranch types."""
3147
3296
 
3148
 
    @staticmethod
3149
 
    def _get_branch_formats_to_test():
3150
 
        """Return a tuple with the Branch formats to use when testing."""
3151
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3297
    @classmethod
 
3298
    def _get_branch_formats_to_test(klass):
 
3299
        """Return an iterable of format tuples for testing.
 
3300
        
 
3301
        :return: An iterable of (from_format, to_format) to use when testing
 
3302
            this InterBranch class. Each InterBranch class should define this
 
3303
            method itself.
 
3304
        """
 
3305
        raise NotImplementedError(klass._get_branch_formats_to_test)
3152
3306
 
 
3307
    @needs_write_lock
3153
3308
    def pull(self, overwrite=False, stop_revision=None,
3154
3309
             possible_transports=None, local=False):
3155
3310
        """Mirror source into target branch.
3160
3315
        """
3161
3316
        raise NotImplementedError(self.pull)
3162
3317
 
 
3318
    @needs_write_lock
3163
3319
    def update_revisions(self, stop_revision=None, overwrite=False,
3164
 
                         graph=None):
 
3320
                         graph=None, fetch_tags=True):
3165
3321
        """Pull in new perfect-fit revisions.
3166
3322
 
3167
3323
        :param stop_revision: Updated until the given revision
3169
3325
            to see if it is a proper descendant.
3170
3326
        :param graph: A Graph object that can be used to query history
3171
3327
            information. This can be None.
 
3328
        :param fetch_tags: Flag that specifies if tags from source should be
 
3329
            fetched too.
3172
3330
        :return: None
3173
3331
        """
3174
3332
        raise NotImplementedError(self.update_revisions)
3175
3333
 
 
3334
    @needs_write_lock
3176
3335
    def push(self, overwrite=False, stop_revision=None,
3177
3336
             _override_hook_source_branch=None):
3178
3337
        """Mirror the source branch into the target branch.
3181
3340
        """
3182
3341
        raise NotImplementedError(self.push)
3183
3342
 
 
3343
    @needs_write_lock
 
3344
    def copy_content_into(self, revision_id=None):
 
3345
        """Copy the content of source into target
 
3346
 
 
3347
        revision_id: if not None, the revision history in the new branch will
 
3348
                     be truncated to end with revision_id.
 
3349
        """
 
3350
        raise NotImplementedError(self.copy_content_into)
 
3351
 
3184
3352
 
3185
3353
class GenericInterBranch(InterBranch):
3186
 
    """InterBranch implementation that uses public Branch functions.
3187
 
    """
3188
 
 
3189
 
    @staticmethod
3190
 
    def _get_branch_formats_to_test():
3191
 
        return BranchFormat._default_format, BranchFormat._default_format
3192
 
 
 
3354
    """InterBranch implementation that uses public Branch functions."""
 
3355
 
 
3356
    @classmethod
 
3357
    def is_compatible(klass, source, target):
 
3358
        # GenericBranch uses the public API, so always compatible
 
3359
        return True
 
3360
 
 
3361
    @classmethod
 
3362
    def _get_branch_formats_to_test(klass):
 
3363
        return [(BranchFormat._default_format, BranchFormat._default_format)]
 
3364
 
 
3365
    @classmethod
 
3366
    def unwrap_format(klass, format):
 
3367
        if isinstance(format, remote.RemoteBranchFormat):
 
3368
            format._ensure_real()
 
3369
            return format._custom_format
 
3370
        return format
 
3371
 
 
3372
    @needs_write_lock
 
3373
    def copy_content_into(self, revision_id=None):
 
3374
        """Copy the content of source into target
 
3375
 
 
3376
        revision_id: if not None, the revision history in the new branch will
 
3377
                     be truncated to end with revision_id.
 
3378
        """
 
3379
        self.source.update_references(self.target)
 
3380
        self.source._synchronize_history(self.target, revision_id)
 
3381
        try:
 
3382
            parent = self.source.get_parent()
 
3383
        except errors.InaccessibleParent, e:
 
3384
            mutter('parent was not accessible to copy: %s', e)
 
3385
        else:
 
3386
            if parent:
 
3387
                self.target.set_parent(parent)
 
3388
        if self.source._push_should_merge_tags():
 
3389
            self.source.tags.merge_to(self.target.tags)
 
3390
 
 
3391
    @needs_write_lock
3193
3392
    def update_revisions(self, stop_revision=None, overwrite=False,
3194
 
        graph=None):
 
3393
        graph=None, fetch_tags=True):
3195
3394
        """See InterBranch.update_revisions()."""
3196
 
        self.source.lock_read()
3197
 
        try:
3198
 
            other_revno, other_last_revision = self.source.last_revision_info()
3199
 
            stop_revno = None # unknown
3200
 
            if stop_revision is None:
3201
 
                stop_revision = other_last_revision
3202
 
                if _mod_revision.is_null(stop_revision):
3203
 
                    # if there are no commits, we're done.
3204
 
                    return
3205
 
                stop_revno = other_revno
3206
 
 
3207
 
            # what's the current last revision, before we fetch [and change it
3208
 
            # possibly]
3209
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3210
 
            # we fetch here so that we don't process data twice in the common
3211
 
            # case of having something to pull, and so that the check for
3212
 
            # already merged can operate on the just fetched graph, which will
3213
 
            # be cached in memory.
3214
 
            self.target.fetch(self.source, stop_revision)
3215
 
            # Check to see if one is an ancestor of the other
3216
 
            if not overwrite:
3217
 
                if graph is None:
3218
 
                    graph = self.target.repository.get_graph()
3219
 
                if self.target._check_if_descendant_or_diverged(
3220
 
                        stop_revision, last_rev, graph, self.source):
3221
 
                    # stop_revision is a descendant of last_rev, but we aren't
3222
 
                    # overwriting, so we're done.
3223
 
                    return
3224
 
            if stop_revno is None:
3225
 
                if graph is None:
3226
 
                    graph = self.target.repository.get_graph()
3227
 
                this_revno, this_last_revision = \
3228
 
                        self.target.last_revision_info()
3229
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3230
 
                                [(other_last_revision, other_revno),
3231
 
                                 (this_last_revision, this_revno)])
3232
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3233
 
        finally:
3234
 
            self.source.unlock()
3235
 
 
 
3395
        other_revno, other_last_revision = self.source.last_revision_info()
 
3396
        stop_revno = None # unknown
 
3397
        if stop_revision is None:
 
3398
            stop_revision = other_last_revision
 
3399
            if _mod_revision.is_null(stop_revision):
 
3400
                # if there are no commits, we're done.
 
3401
                return
 
3402
            stop_revno = other_revno
 
3403
 
 
3404
        # what's the current last revision, before we fetch [and change it
 
3405
        # possibly]
 
3406
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3407
        # we fetch here so that we don't process data twice in the common
 
3408
        # case of having something to pull, and so that the check for
 
3409
        # already merged can operate on the just fetched graph, which will
 
3410
        # be cached in memory.
 
3411
        if fetch_tags:
 
3412
            fetch_spec_factory = fetch.FetchSpecFactory()
 
3413
            fetch_spec_factory.source_branch = self.source
 
3414
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
3415
            fetch_spec_factory.source_repo = self.source.repository
 
3416
            fetch_spec_factory.target_repo = self.target.repository
 
3417
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
3418
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
3419
        else:
 
3420
            fetch_spec = _mod_graph.NotInOtherForRevs(self.target.repository,
 
3421
                self.source.repository, revision_ids=[stop_revision]).execute()
 
3422
        self.target.fetch(self.source, fetch_spec=fetch_spec)
 
3423
        # Check to see if one is an ancestor of the other
 
3424
        if not overwrite:
 
3425
            if graph is None:
 
3426
                graph = self.target.repository.get_graph()
 
3427
            if self.target._check_if_descendant_or_diverged(
 
3428
                    stop_revision, last_rev, graph, self.source):
 
3429
                # stop_revision is a descendant of last_rev, but we aren't
 
3430
                # overwriting, so we're done.
 
3431
                return
 
3432
        if stop_revno is None:
 
3433
            if graph is None:
 
3434
                graph = self.target.repository.get_graph()
 
3435
            this_revno, this_last_revision = \
 
3436
                    self.target.last_revision_info()
 
3437
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3438
                            [(other_last_revision, other_revno),
 
3439
                             (this_last_revision, this_revno)])
 
3440
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3441
 
 
3442
    @needs_write_lock
3236
3443
    def pull(self, overwrite=False, stop_revision=None,
3237
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3444
             possible_transports=None, run_hooks=True,
3238
3445
             _override_hook_target=None, local=False):
3239
 
        """See Branch.pull.
 
3446
        """Pull from source into self, updating my master if any.
3240
3447
 
3241
 
        :param _hook_master: Private parameter - set the branch to
3242
 
            be supplied as the master to pull hooks.
3243
3448
        :param run_hooks: Private parameter - if false, this branch
3244
3449
            is being called because it's the master of the primary branch,
3245
3450
            so it should not run its hooks.
3246
 
        :param _override_hook_target: Private parameter - set the branch to be
3247
 
            supplied as the target_branch to pull hooks.
3248
 
        :param local: Only update the local branch, and not the bound branch.
3249
3451
        """
3250
 
        # This type of branch can't be bound.
3251
 
        if local:
 
3452
        bound_location = self.target.get_bound_location()
 
3453
        if local and not bound_location:
3252
3454
            raise errors.LocalRequiresBoundBranch()
3253
 
        result = PullResult()
3254
 
        result.source_branch = self.source
3255
 
        if _override_hook_target is None:
3256
 
            result.target_branch = self.target
3257
 
        else:
3258
 
            result.target_branch = _override_hook_target
3259
 
        self.source.lock_read()
 
3455
        master_branch = None
 
3456
        source_is_master = (self.source.user_url == bound_location)
 
3457
        if not local and bound_location and not source_is_master:
 
3458
            # not pulling from master, so we need to update master.
 
3459
            master_branch = self.target.get_master_branch(possible_transports)
 
3460
            master_branch.lock_write()
3260
3461
        try:
3261
 
            # We assume that during 'pull' the target repository is closer than
3262
 
            # the source one.
3263
 
            self.source.update_references(self.target)
3264
 
            graph = self.target.repository.get_graph(self.source.repository)
3265
 
            # TODO: Branch formats should have a flag that indicates 
3266
 
            # that revno's are expensive, and pull() should honor that flag.
3267
 
            # -- JRV20090506
3268
 
            result.old_revno, result.old_revid = \
3269
 
                self.target.last_revision_info()
3270
 
            self.target.update_revisions(self.source, stop_revision,
3271
 
                overwrite=overwrite, graph=graph)
3272
 
            # TODO: The old revid should be specified when merging tags, 
3273
 
            # so a tags implementation that versions tags can only 
3274
 
            # pull in the most recent changes. -- JRV20090506
3275
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3276
 
                overwrite)
3277
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3278
 
            if _hook_master:
3279
 
                result.master_branch = _hook_master
3280
 
                result.local_branch = result.target_branch
3281
 
            else:
3282
 
                result.master_branch = result.target_branch
3283
 
                result.local_branch = None
3284
 
            if run_hooks:
3285
 
                for hook in Branch.hooks['post_pull']:
3286
 
                    hook(result)
 
3462
            if master_branch:
 
3463
                # pull from source into master.
 
3464
                master_branch.pull(self.source, overwrite, stop_revision,
 
3465
                    run_hooks=False)
 
3466
            return self._pull(overwrite,
 
3467
                stop_revision, _hook_master=master_branch,
 
3468
                run_hooks=run_hooks,
 
3469
                _override_hook_target=_override_hook_target,
 
3470
                merge_tags_to_master=not source_is_master)
3287
3471
        finally:
3288
 
            self.source.unlock()
3289
 
        return result
 
3472
            if master_branch:
 
3473
                master_branch.unlock()
3290
3474
 
3291
3475
    def push(self, overwrite=False, stop_revision=None,
3292
3476
             _override_hook_source_branch=None):
3332
3516
                # push into the master from the source branch.
3333
3517
                self.source._basic_push(master_branch, overwrite, stop_revision)
3334
3518
                # and push into the target branch from the source. Note that we
3335
 
                # push from the source branch again, because its considered the
 
3519
                # push from the source branch again, because it's considered the
3336
3520
                # highest bandwidth repository.
3337
3521
                result = self.source._basic_push(self.target, overwrite,
3338
3522
                    stop_revision)
3354
3538
            _run_hooks()
3355
3539
            return result
3356
3540
 
3357
 
    @classmethod
3358
 
    def is_compatible(self, source, target):
3359
 
        # GenericBranch uses the public API, so always compatible
3360
 
        return True
3361
 
 
3362
 
 
3363
 
class InterToBranch5(GenericInterBranch):
3364
 
 
3365
 
    @staticmethod
3366
 
    def _get_branch_formats_to_test():
3367
 
        return BranchFormat._default_format, BzrBranchFormat5()
3368
 
 
3369
 
    def pull(self, overwrite=False, stop_revision=None,
3370
 
             possible_transports=None, run_hooks=True,
3371
 
             _override_hook_target=None, local=False):
3372
 
        """Pull from source into self, updating my master if any.
3373
 
 
 
3541
    def _pull(self, overwrite=False, stop_revision=None,
 
3542
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3543
             _override_hook_target=None, local=False,
 
3544
             merge_tags_to_master=True):
 
3545
        """See Branch.pull.
 
3546
 
 
3547
        This function is the core worker, used by GenericInterBranch.pull to
 
3548
        avoid duplication when pulling source->master and source->local.
 
3549
 
 
3550
        :param _hook_master: Private parameter - set the branch to
 
3551
            be supplied as the master to pull hooks.
3374
3552
        :param run_hooks: Private parameter - if false, this branch
3375
3553
            is being called because it's the master of the primary branch,
3376
3554
            so it should not run its hooks.
 
3555
        :param _override_hook_target: Private parameter - set the branch to be
 
3556
            supplied as the target_branch to pull hooks.
 
3557
        :param local: Only update the local branch, and not the bound branch.
3377
3558
        """
3378
 
        bound_location = self.target.get_bound_location()
3379
 
        if local and not bound_location:
 
3559
        # This type of branch can't be bound.
 
3560
        if local:
3380
3561
            raise errors.LocalRequiresBoundBranch()
3381
 
        master_branch = None
3382
 
        if not local and bound_location and self.source.user_url != bound_location:
3383
 
            # not pulling from master, so we need to update master.
3384
 
            master_branch = self.target.get_master_branch(possible_transports)
3385
 
            master_branch.lock_write()
 
3562
        result = PullResult()
 
3563
        result.source_branch = self.source
 
3564
        if _override_hook_target is None:
 
3565
            result.target_branch = self.target
 
3566
        else:
 
3567
            result.target_branch = _override_hook_target
 
3568
        self.source.lock_read()
3386
3569
        try:
3387
 
            if master_branch:
3388
 
                # pull from source into master.
3389
 
                master_branch.pull(self.source, overwrite, stop_revision,
3390
 
                    run_hooks=False)
3391
 
            return super(InterToBranch5, self).pull(overwrite,
3392
 
                stop_revision, _hook_master=master_branch,
3393
 
                run_hooks=run_hooks,
3394
 
                _override_hook_target=_override_hook_target)
 
3570
            # We assume that during 'pull' the target repository is closer than
 
3571
            # the source one.
 
3572
            self.source.update_references(self.target)
 
3573
            graph = self.target.repository.get_graph(self.source.repository)
 
3574
            # TODO: Branch formats should have a flag that indicates 
 
3575
            # that revno's are expensive, and pull() should honor that flag.
 
3576
            # -- JRV20090506
 
3577
            result.old_revno, result.old_revid = \
 
3578
                self.target.last_revision_info()
 
3579
            self.target.update_revisions(self.source, stop_revision,
 
3580
                overwrite=overwrite, graph=graph)
 
3581
            # TODO: The old revid should be specified when merging tags, 
 
3582
            # so a tags implementation that versions tags can only 
 
3583
            # pull in the most recent changes. -- JRV20090506
 
3584
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3585
                overwrite, ignore_master=not merge_tags_to_master)
 
3586
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3587
            if _hook_master:
 
3588
                result.master_branch = _hook_master
 
3589
                result.local_branch = result.target_branch
 
3590
            else:
 
3591
                result.master_branch = result.target_branch
 
3592
                result.local_branch = None
 
3593
            if run_hooks:
 
3594
                for hook in Branch.hooks['post_pull']:
 
3595
                    hook(result)
3395
3596
        finally:
3396
 
            if master_branch:
3397
 
                master_branch.unlock()
 
3597
            self.source.unlock()
 
3598
        return result
3398
3599
 
3399
3600
 
3400
3601
InterBranch.register_optimiser(GenericInterBranch)
3401
 
InterBranch.register_optimiser(InterToBranch5)