/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: 2009-05-28 16:04:39 UTC
  • mfrom: (4387 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4405.
  • Revision ID: jelmer@samba.org-20090528160439-4z0xlrk5nejobm7q
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
 
18
from cStringIO import StringIO
18
19
import sys
19
20
 
20
21
from bzrlib.lazy_import import lazy_import
30
31
        lockable_files,
31
32
        repository,
32
33
        revision as _mod_revision,
 
34
        rio,
33
35
        symbol_versioning,
34
36
        transport,
35
37
        tsort,
99
101
    def _open_hook(self):
100
102
        """Called by init to allow simpler extension of the base class."""
101
103
 
102
 
    def _activate_fallback_location(self, url):
 
104
    def _activate_fallback_location(self, url, lock_style):
103
105
        """Activate the branch/repository from url as a fallback repository."""
104
 
        self.repository.add_fallback_repository(
105
 
            self._get_fallback_repository(url))
 
106
        repo = self._get_fallback_repository(url)
 
107
        if lock_style == 'write':
 
108
            repo.lock_write()
 
109
        elif lock_style == 'read':
 
110
            repo.lock_read()
 
111
        self.repository.add_fallback_repository(repo)
106
112
 
107
113
    def break_lock(self):
108
114
        """Break a lock if one is present from another instance.
496
502
        """
497
503
        raise errors.UpgradeRequired(self.base)
498
504
 
 
505
    def set_reference_info(self, file_id, tree_path, branch_location):
 
506
        """Set the branch location to use for a tree reference."""
 
507
        raise errors.UnsupportedOperation(self.set_reference_info, self)
 
508
 
 
509
    def get_reference_info(self, file_id):
 
510
        """Get the tree_path and branch_location for a tree reference."""
 
511
        raise errors.UnsupportedOperation(self.get_reference_info, self)
 
512
 
499
513
    @needs_write_lock
500
514
    def fetch(self, from_branch, last_revision=None, pb=None):
501
515
        """Copy revisions from from_branch into this branch.
590
604
    def set_revision_history(self, rev_history):
591
605
        raise NotImplementedError(self.set_revision_history)
592
606
 
 
607
    @needs_write_lock
 
608
    def set_parent(self, url):
 
609
        """See Branch.set_parent."""
 
610
        # TODO: Maybe delete old location files?
 
611
        # URLs should never be unicode, even on the local fs,
 
612
        # FIXUP this and get_parent in a future branch format bump:
 
613
        # read and rewrite the file. RBC 20060125
 
614
        if url is not None:
 
615
            if isinstance(url, unicode):
 
616
                try:
 
617
                    url = url.encode('ascii')
 
618
                except UnicodeEncodeError:
 
619
                    raise errors.InvalidURL(url,
 
620
                        "Urls must be 7-bit ascii, "
 
621
                        "use bzrlib.urlutils.escape")
 
622
            url = urlutils.relative_url(self.base, url)
 
623
        self._set_parent_location(url)
 
624
 
 
625
    @needs_write_lock
593
626
    def set_stacked_on_url(self, url):
594
627
        """Set the URL this branch is stacked against.
595
628
 
608
641
                errors.UnstackableRepositoryFormat):
609
642
                return
610
643
            url = ''
 
644
            # XXX: Lock correctness - should unlock our old repo if we were
 
645
            # locked.
611
646
            # repositories don't offer an interface to remove fallback
612
647
            # repositories today; take the conceptually simpler option and just
613
648
            # reopen it.
614
649
            self.repository = self.bzrdir.find_repository()
 
650
            self.repository.lock_write()
615
651
            # for every revision reference the branch has, ensure it is pulled
616
652
            # in.
617
653
            source_repository = self._get_fallback_repository(old_url)
620
656
                self.repository.fetch(source_repository, revision_id,
621
657
                    find_ghosts=True)
622
658
        else:
623
 
            self._activate_fallback_location(url)
 
659
            self._activate_fallback_location(url, 'write')
624
660
        # write this out after the repository is stacked to avoid setting a
625
661
        # stacked config that doesn't work.
626
662
        self._set_config_location('stacked_on_location', url)
809
845
            raise errors.NoSuchRevision(self, revno)
810
846
        return history[revno - 1]
811
847
 
 
848
    @needs_write_lock
812
849
    def pull(self, source, overwrite=False, stop_revision=None,
813
 
             possible_transports=None, _override_hook_target=None):
 
850
             possible_transports=None, *args, **kwargs):
814
851
        """Mirror source into this branch.
815
852
 
816
853
        This branch is considered to be 'local', having low latency.
817
854
 
818
855
        :returns: PullResult instance
819
856
        """
820
 
        raise NotImplementedError(self.pull)
 
857
        return InterBranch.get(source, self).pull(overwrite=overwrite,
 
858
            stop_revision=stop_revision,
 
859
            possible_transports=possible_transports, *args, **kwargs)
821
860
 
822
 
    def push(self, target, overwrite=False, stop_revision=None):
 
861
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
862
        **kwargs):
823
863
        """Mirror this branch into target.
824
864
 
825
865
        This branch is considered to be 'local', having low latency.
826
866
        """
827
 
        raise NotImplementedError(self.push)
 
867
        return InterBranch.get(self, target).push(overwrite, stop_revision,
 
868
            *args, **kwargs)
 
869
 
 
870
    def lossy_push(self, target, stop_revision=None):
 
871
        """Push deltas into another branch.
 
872
 
 
873
        :note: This does not, like push, retain the revision ids from 
 
874
            the source branch and will, rather than adding bzr-specific 
 
875
            metadata, push only those semantics of the revision that can be 
 
876
            natively represented by this branch' VCS.
 
877
 
 
878
        :param target: Target branch
 
879
        :param stop_revision: Revision to push, defaults to last revision.
 
880
        :return: BranchPushResult with an extra member revidmap: 
 
881
            A dictionary mapping revision ids from the target branch 
 
882
            to new revision ids in the target branch, for each 
 
883
            revision that was pushed.
 
884
        """
 
885
        inter = InterBranch.get(self, target)
 
886
        lossy_push = getattr(inter, "lossy_push", None)
 
887
        if lossy_push is None:
 
888
            raise errors.LossyPushToSameVCS(self, target)
 
889
        return lossy_push(stop_revision)
828
890
 
829
891
    def basis_tree(self):
830
892
        """Return `Tree` object for last revision."""
870
932
            location = None
871
933
        return location
872
934
 
 
935
    def get_child_submit_format(self):
 
936
        """Return the preferred format of submissions to this branch."""
 
937
        return self.get_config().get_user_option("child_submit_format")
 
938
 
873
939
    def get_submit_branch(self):
874
940
        """Return the submit location of the branch.
875
941
 
944
1010
                raise errors.HookFailed(
945
1011
                    'pre_change_branch_tip', hook_name, exc_info)
946
1012
 
947
 
    def set_parent(self, url):
948
 
        raise NotImplementedError(self.set_parent)
949
 
 
950
1013
    @needs_write_lock
951
1014
    def update(self):
952
1015
        """Synchronise this branch with the master branch if any.
982
1045
                     be truncated to end with revision_id.
983
1046
        """
984
1047
        result = to_bzrdir.create_branch()
985
 
        if repository_policy is not None:
986
 
            repository_policy.configure_branch(result)
987
 
        self.copy_content_into(result, revision_id=revision_id)
988
 
        return  result
 
1048
        result.lock_write()
 
1049
        try:
 
1050
            if repository_policy is not None:
 
1051
                repository_policy.configure_branch(result)
 
1052
            self.copy_content_into(result, revision_id=revision_id)
 
1053
        finally:
 
1054
            result.unlock()
 
1055
        return result
989
1056
 
990
1057
    @needs_read_lock
991
1058
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
997
1064
                     be truncated to end with revision_id.
998
1065
        """
999
1066
        result = to_bzrdir.create_branch()
1000
 
        if repository_policy is not None:
1001
 
            repository_policy.configure_branch(result)
1002
 
        self.copy_content_into(result, revision_id=revision_id)
1003
 
        result.set_parent(self.bzrdir.root_transport.base)
 
1067
        result.lock_write()
 
1068
        try:
 
1069
            if repository_policy is not None:
 
1070
                repository_policy.configure_branch(result)
 
1071
            self.copy_content_into(result, revision_id=revision_id)
 
1072
            result.set_parent(self.bzrdir.root_transport.base)
 
1073
        finally:
 
1074
            result.unlock()
1004
1075
        return result
1005
1076
 
1006
1077
    def _synchronize_history(self, destination, revision_id):
1045
1116
        revision_id: if not None, the revision history in the new branch will
1046
1117
                     be truncated to end with revision_id.
1047
1118
        """
 
1119
        self.update_references(destination)
1048
1120
        self._synchronize_history(destination, revision_id)
1049
1121
        try:
1050
1122
            parent = self.get_parent()
1056
1128
        if self._push_should_merge_tags():
1057
1129
            self.tags.merge_to(destination.tags)
1058
1130
 
 
1131
    def update_references(self, target):
 
1132
        if not getattr(self._format, 'supports_reference_locations', False):
 
1133
            return
 
1134
        reference_dict = self._get_all_reference_info()
 
1135
        if len(reference_dict) == 0:
 
1136
            return
 
1137
        old_base = self.base
 
1138
        new_base = target.base
 
1139
        target_reference_dict = target._get_all_reference_info()
 
1140
        for file_id, (tree_path, branch_location) in (
 
1141
            reference_dict.items()):
 
1142
            branch_location = urlutils.rebase_url(branch_location,
 
1143
                                                  old_base, new_base)
 
1144
            target_reference_dict.setdefault(
 
1145
                file_id, (tree_path, branch_location))
 
1146
        target._set_all_reference_info(target_reference_dict)
 
1147
 
1059
1148
    @needs_read_lock
1060
1149
    def check(self):
1061
1150
        """Check consistency of the branch.
1114
1203
        return format
1115
1204
 
1116
1205
    def create_clone_on_transport(self, to_transport, revision_id=None,
1117
 
        stacked_on=None):
 
1206
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1118
1207
        """Create a clone of this branch and its bzrdir.
1119
1208
 
1120
1209
        :param to_transport: The transport to clone onto.
1121
1210
        :param revision_id: The revision id to use as tip in the new branch.
1122
1211
            If None the tip is obtained from this branch.
1123
1212
        :param stacked_on: An optional URL to stack the clone on.
 
1213
        :param create_prefix: Create any missing directories leading up to
 
1214
            to_transport.
 
1215
        :param use_existing_dir: Use an existing directory if one exists.
1124
1216
        """
1125
1217
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1126
1218
        # clone call. Or something. 20090224 RBC/spiv.
1127
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1128
 
            revision_id=revision_id, stacked_on=stacked_on)
 
1219
        if revision_id is None:
 
1220
            revision_id = self.last_revision()
 
1221
        try:
 
1222
            dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1223
                revision_id=revision_id, stacked_on=stacked_on,
 
1224
                create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1225
        except errors.FileExists:
 
1226
            if not use_existing_dir:
 
1227
                raise
 
1228
        except errors.NoSuchFile:
 
1229
            if not create_prefix:
 
1230
                raise
1129
1231
        return dir_to.open_branch()
1130
1232
 
1131
1233
    def create_checkout(self, to_location, revision_id=None,
1185
1287
        reconciler.reconcile()
1186
1288
        return reconciler
1187
1289
 
1188
 
    def reference_parent(self, file_id, path):
 
1290
    def reference_parent(self, file_id, path, possible_transports=None):
1189
1291
        """Return the parent branch for a tree-reference file_id
1190
1292
        :param file_id: The file_id of the tree reference
1191
1293
        :param path: The path of the file_id in the tree
1192
1294
        :return: A branch associated with the file_id
1193
1295
        """
1194
1296
        # FIXME should provide multiple branches, based on config
1195
 
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
 
1297
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
 
1298
                           possible_transports=possible_transports)
1196
1299
 
1197
1300
    def supports_tags(self):
1198
1301
        return self._format.supports_tags()
1335
1438
        control_files = lockable_files.LockableFiles(branch_transport,
1336
1439
            lock_name, lock_class)
1337
1440
        control_files.create_lock()
1338
 
        control_files.lock_write()
 
1441
        try:
 
1442
            control_files.lock_write()
 
1443
        except errors.LockContention:
 
1444
            if lock_type != 'branch4':
 
1445
                raise
 
1446
            lock_taken = False
 
1447
        else:
 
1448
            lock_taken = True
1339
1449
        if set_format:
1340
1450
            utf8_files += [('format', self.get_format_string())]
1341
1451
        try:
1344
1454
                    filename, content,
1345
1455
                    mode=a_bzrdir._get_file_mode())
1346
1456
        finally:
1347
 
            control_files.unlock()
 
1457
            if lock_taken:
 
1458
                control_files.unlock()
1348
1459
        return self.open(a_bzrdir, _found=True)
1349
1460
 
1350
1461
    def initialize(self, a_bzrdir):
1696
1807
 
1697
1808
 
1698
1809
 
1699
 
class BzrBranchFormat7(BranchFormatMetadir):
 
1810
class BzrBranchFormat8(BranchFormatMetadir):
 
1811
    """Metadir format supporting storing locations of subtree branches."""
 
1812
 
 
1813
    def _branch_class(self):
 
1814
        return BzrBranch8
 
1815
 
 
1816
    def get_format_string(self):
 
1817
        """See BranchFormat.get_format_string()."""
 
1818
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
 
1819
 
 
1820
    def get_format_description(self):
 
1821
        """See BranchFormat.get_format_description()."""
 
1822
        return "Branch format 8"
 
1823
 
 
1824
    def initialize(self, a_bzrdir):
 
1825
        """Create a branch of this format in a_bzrdir."""
 
1826
        utf8_files = [('last-revision', '0 null:\n'),
 
1827
                      ('branch.conf', ''),
 
1828
                      ('tags', ''),
 
1829
                      ('references', '')
 
1830
                      ]
 
1831
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1832
 
 
1833
    def __init__(self):
 
1834
        super(BzrBranchFormat8, self).__init__()
 
1835
        self._matchingbzrdir.repository_format = \
 
1836
            RepositoryFormatKnitPack5RichRoot()
 
1837
 
 
1838
    def make_tags(self, branch):
 
1839
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1840
        return BasicTags(branch)
 
1841
 
 
1842
    def supports_stacking(self):
 
1843
        return True
 
1844
 
 
1845
    supports_reference_locations = True
 
1846
 
 
1847
 
 
1848
class BzrBranchFormat7(BzrBranchFormat8):
1700
1849
    """Branch format with last-revision, tags, and a stacked location pointer.
1701
1850
 
1702
1851
    The stacked location pointer is passed down to the repository and requires
1705
1854
    This format was introduced in bzr 1.6.
1706
1855
    """
1707
1856
 
 
1857
    def initialize(self, a_bzrdir):
 
1858
        """Create a branch of this format in a_bzrdir."""
 
1859
        utf8_files = [('last-revision', '0 null:\n'),
 
1860
                      ('branch.conf', ''),
 
1861
                      ('tags', ''),
 
1862
                      ]
 
1863
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1864
 
1708
1865
    def _branch_class(self):
1709
1866
        return BzrBranch7
1710
1867
 
1716
1873
        """See BranchFormat.get_format_description()."""
1717
1874
        return "Branch format 7"
1718
1875
 
1719
 
    def initialize(self, a_bzrdir):
1720
 
        """Create a branch of this format in a_bzrdir."""
1721
 
        utf8_files = [('last-revision', '0 null:\n'),
1722
 
                      ('branch.conf', ''),
1723
 
                      ('tags', ''),
1724
 
                      ]
1725
 
        return self._initialize_helper(a_bzrdir, utf8_files)
1726
 
 
1727
 
    def __init__(self):
1728
 
        super(BzrBranchFormat7, self).__init__()
1729
 
        self._matchingbzrdir.repository_format = \
1730
 
            RepositoryFormatKnitPack5RichRoot()
1731
 
 
1732
 
    def make_tags(self, branch):
1733
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
1734
 
        return BasicTags(branch)
1735
 
 
1736
 
    def supports_stacking(self):
1737
 
        return True
 
1876
    supports_reference_locations = False
1738
1877
 
1739
1878
 
1740
1879
class BranchReferenceFormat(BranchFormat):
1847
1986
__format5 = BzrBranchFormat5()
1848
1987
__format6 = BzrBranchFormat6()
1849
1988
__format7 = BzrBranchFormat7()
 
1989
__format8 = BzrBranchFormat8()
1850
1990
BranchFormat.register_format(__format5)
1851
1991
BranchFormat.register_format(BranchReferenceFormat())
1852
1992
BranchFormat.register_format(__format6)
1853
1993
BranchFormat.register_format(__format7)
 
1994
BranchFormat.register_format(__format8)
1854
1995
BranchFormat.set_default_format(__format6)
1855
1996
_legacy_formats = [BzrBranchFormat4(),
1856
1997
    ]
1910
2051
        return self.control_files.is_locked()
1911
2052
 
1912
2053
    def lock_write(self, token=None):
1913
 
        repo_token = self.repository.lock_write()
 
2054
        # All-in-one needs to always unlock/lock.
 
2055
        repo_control = getattr(self.repository, 'control_files', None)
 
2056
        if self.control_files == repo_control or not self.is_locked():
 
2057
            self.repository.lock_write()
 
2058
            took_lock = True
 
2059
        else:
 
2060
            took_lock = False
1914
2061
        try:
1915
 
            token = self.control_files.lock_write(token=token)
 
2062
            return self.control_files.lock_write(token=token)
1916
2063
        except:
1917
 
            self.repository.unlock()
 
2064
            if took_lock:
 
2065
                self.repository.unlock()
1918
2066
            raise
1919
 
        return token
1920
2067
 
1921
2068
    def lock_read(self):
1922
 
        self.repository.lock_read()
 
2069
        # All-in-one needs to always unlock/lock.
 
2070
        repo_control = getattr(self.repository, 'control_files', None)
 
2071
        if self.control_files == repo_control or not self.is_locked():
 
2072
            self.repository.lock_read()
 
2073
            took_lock = True
 
2074
        else:
 
2075
            took_lock = False
1923
2076
        try:
1924
2077
            self.control_files.lock_read()
1925
2078
        except:
1926
 
            self.repository.unlock()
 
2079
            if took_lock:
 
2080
                self.repository.unlock()
1927
2081
            raise
1928
2082
 
1929
2083
    def unlock(self):
1930
 
        # TODO: test for failed two phase locks. This is known broken.
1931
2084
        try:
1932
2085
            self.control_files.unlock()
1933
2086
        finally:
1934
 
            self.repository.unlock()
1935
 
        if not self.control_files.is_locked():
1936
 
            # we just released the lock
1937
 
            self._clear_cached_state()
 
2087
            # All-in-one needs to always unlock/lock.
 
2088
            repo_control = getattr(self.repository, 'control_files', None)
 
2089
            if (self.control_files == repo_control or
 
2090
                not self.control_files.is_locked()):
 
2091
                self.repository.unlock()
 
2092
            if not self.control_files.is_locked():
 
2093
                # we just released the lock
 
2094
                self._clear_cached_state()
1938
2095
 
1939
2096
    def peek_lock_mode(self):
1940
2097
        if self.control_files._lock_count == 0:
2059
2216
        """See Branch.basis_tree."""
2060
2217
        return self.repository.revision_tree(self.last_revision())
2061
2218
 
2062
 
    @needs_write_lock
2063
 
    def pull(self, source, overwrite=False, stop_revision=None,
2064
 
             _hook_master=None, run_hooks=True, possible_transports=None,
2065
 
             _override_hook_target=None):
2066
 
        """See Branch.pull.
2067
 
 
2068
 
        :param _hook_master: Private parameter - set the branch to
2069
 
            be supplied as the master to pull hooks.
2070
 
        :param run_hooks: Private parameter - if false, this branch
2071
 
            is being called because it's the master of the primary branch,
2072
 
            so it should not run its hooks.
2073
 
        :param _override_hook_target: Private parameter - set the branch to be
2074
 
            supplied as the target_branch to pull hooks.
2075
 
        """
2076
 
        result = PullResult()
2077
 
        result.source_branch = source
2078
 
        if _override_hook_target is None:
2079
 
            result.target_branch = self
2080
 
        else:
2081
 
            result.target_branch = _override_hook_target
2082
 
        source.lock_read()
2083
 
        try:
2084
 
            # We assume that during 'pull' the local repository is closer than
2085
 
            # the remote one.
2086
 
            graph = self.repository.get_graph(source.repository)
2087
 
            result.old_revno, result.old_revid = self.last_revision_info()
2088
 
            self.update_revisions(source, stop_revision, overwrite=overwrite,
2089
 
                                  graph=graph)
2090
 
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
2091
 
            result.new_revno, result.new_revid = self.last_revision_info()
2092
 
            if _hook_master:
2093
 
                result.master_branch = _hook_master
2094
 
                result.local_branch = result.target_branch
2095
 
            else:
2096
 
                result.master_branch = result.target_branch
2097
 
                result.local_branch = None
2098
 
            if run_hooks:
2099
 
                for hook in Branch.hooks['post_pull']:
2100
 
                    hook(result)
2101
 
        finally:
2102
 
            source.unlock()
2103
 
        return result
2104
 
 
2105
2219
    def _get_parent_location(self):
2106
2220
        _locs = ['parent', 'pull', 'x-pull']
2107
2221
        for l in _locs:
2111
2225
                pass
2112
2226
        return None
2113
2227
 
2114
 
    @needs_read_lock
2115
 
    def push(self, target, overwrite=False, stop_revision=None,
2116
 
             _override_hook_source_branch=None):
2117
 
        """See Branch.push.
2118
 
 
2119
 
        This is the basic concrete implementation of push()
2120
 
 
2121
 
        :param _override_hook_source_branch: If specified, run
2122
 
        the hooks passing this Branch as the source, rather than self.
2123
 
        This is for use of RemoteBranch, where push is delegated to the
2124
 
        underlying vfs-based Branch.
2125
 
        """
2126
 
        # TODO: Public option to disable running hooks - should be trivial but
2127
 
        # needs tests.
2128
 
        return _run_with_write_locked_target(
2129
 
            target, self._push_with_bound_branches, target, overwrite,
2130
 
            stop_revision,
2131
 
            _override_hook_source_branch=_override_hook_source_branch)
2132
 
 
2133
 
    def _push_with_bound_branches(self, target, overwrite,
2134
 
            stop_revision,
2135
 
            _override_hook_source_branch=None):
2136
 
        """Push from self into target, and into target's master if any.
2137
 
 
2138
 
        This is on the base BzrBranch class even though it doesn't support
2139
 
        bound branches because the *target* might be bound.
2140
 
        """
2141
 
        def _run_hooks():
2142
 
            if _override_hook_source_branch:
2143
 
                result.source_branch = _override_hook_source_branch
2144
 
            for hook in Branch.hooks['post_push']:
2145
 
                hook(result)
2146
 
 
2147
 
        bound_location = target.get_bound_location()
2148
 
        if bound_location and target.base != bound_location:
2149
 
            # there is a master branch.
2150
 
            #
2151
 
            # XXX: Why the second check?  Is it even supported for a branch to
2152
 
            # be bound to itself? -- mbp 20070507
2153
 
            master_branch = target.get_master_branch()
2154
 
            master_branch.lock_write()
2155
 
            try:
2156
 
                # push into the master from this branch.
2157
 
                self._basic_push(master_branch, overwrite, stop_revision)
2158
 
                # and push into the target branch from this. Note that we push from
2159
 
                # this branch again, because its considered the highest bandwidth
2160
 
                # repository.
2161
 
                result = self._basic_push(target, overwrite, stop_revision)
2162
 
                result.master_branch = master_branch
2163
 
                result.local_branch = target
2164
 
                _run_hooks()
2165
 
                return result
2166
 
            finally:
2167
 
                master_branch.unlock()
2168
 
        else:
2169
 
            # no master branch
2170
 
            result = self._basic_push(target, overwrite, stop_revision)
2171
 
            # TODO: Why set master_branch and local_branch if there's no
2172
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
2173
 
            # 20070504
2174
 
            result.master_branch = target
2175
 
            result.local_branch = None
2176
 
            _run_hooks()
2177
 
            return result
2178
 
 
2179
2228
    def _basic_push(self, target, overwrite, stop_revision):
2180
2229
        """Basic implementation of push without bound branches or hooks.
2181
2230
 
2182
 
        Must be called with self read locked and target write locked.
 
2231
        Must be called with source read locked and target write locked.
2183
2232
        """
2184
2233
        result = BranchPushResult()
2185
2234
        result.source_branch = self
2186
2235
        result.target_branch = target
2187
2236
        result.old_revno, result.old_revid = target.last_revision_info()
 
2237
        self.update_references(target)
2188
2238
        if result.old_revid != self.last_revision():
2189
2239
            # We assume that during 'push' this repository is closer than
2190
2240
            # the target.
2191
2241
            graph = self.repository.get_graph(target.repository)
2192
 
            target.update_revisions(self, stop_revision, overwrite=overwrite,
2193
 
                                    graph=graph)
 
2242
            target.update_revisions(self, stop_revision,
 
2243
                overwrite=overwrite, graph=graph)
2194
2244
        if self._push_should_merge_tags():
2195
 
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
 
2245
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2246
                overwrite)
2196
2247
        result.new_revno, result.new_revid = target.last_revision_info()
2197
2248
        return result
2198
2249
 
2205
2256
            'push_location', location,
2206
2257
            store=_mod_config.STORE_LOCATION_NORECURSE)
2207
2258
 
2208
 
    @needs_write_lock
2209
 
    def set_parent(self, url):
2210
 
        """See Branch.set_parent."""
2211
 
        # TODO: Maybe delete old location files?
2212
 
        # URLs should never be unicode, even on the local fs,
2213
 
        # FIXUP this and get_parent in a future branch format bump:
2214
 
        # read and rewrite the file. RBC 20060125
2215
 
        if url is not None:
2216
 
            if isinstance(url, unicode):
2217
 
                try:
2218
 
                    url = url.encode('ascii')
2219
 
                except UnicodeEncodeError:
2220
 
                    raise errors.InvalidURL(url,
2221
 
                        "Urls must be 7-bit ascii, "
2222
 
                        "use bzrlib.urlutils.escape")
2223
 
            url = urlutils.relative_url(self.base, url)
2224
 
        self._set_parent_location(url)
2225
 
 
2226
2259
    def _set_parent_location(self, url):
2227
2260
        if url is None:
2228
2261
            self._transport.delete('parent')
2237
2270
    It has support for a master_branch which is the data for bound branches.
2238
2271
    """
2239
2272
 
2240
 
    @needs_write_lock
2241
 
    def pull(self, source, overwrite=False, stop_revision=None,
2242
 
             run_hooks=True, possible_transports=None,
2243
 
             _override_hook_target=None):
2244
 
        """Pull from source into self, updating my master if any.
2245
 
 
2246
 
        :param run_hooks: Private parameter - if false, this branch
2247
 
            is being called because it's the master of the primary branch,
2248
 
            so it should not run its hooks.
2249
 
        """
2250
 
        bound_location = self.get_bound_location()
2251
 
        master_branch = None
2252
 
        if bound_location and source.base != bound_location:
2253
 
            # not pulling from master, so we need to update master.
2254
 
            master_branch = self.get_master_branch(possible_transports)
2255
 
            master_branch.lock_write()
2256
 
        try:
2257
 
            if master_branch:
2258
 
                # pull from source into master.
2259
 
                master_branch.pull(source, overwrite, stop_revision,
2260
 
                    run_hooks=False)
2261
 
            return super(BzrBranch5, self).pull(source, overwrite,
2262
 
                stop_revision, _hook_master=master_branch,
2263
 
                run_hooks=run_hooks,
2264
 
                _override_hook_target=_override_hook_target)
2265
 
        finally:
2266
 
            if master_branch:
2267
 
                master_branch.unlock()
2268
 
 
2269
2273
    def get_bound_location(self):
2270
2274
        try:
2271
2275
            return self._transport.get_bytes('bound')[:-1]
2358
2362
        return None
2359
2363
 
2360
2364
 
2361
 
class BzrBranch7(BzrBranch5):
2362
 
    """A branch with support for a fallback repository."""
 
2365
class BzrBranch8(BzrBranch5):
 
2366
    """A branch that stores tree-reference locations."""
2363
2367
 
2364
2368
    def _open_hook(self):
2365
2369
        if self._ignore_fallbacks:
2377
2381
                    raise AssertionError(
2378
2382
                        "'transform_fallback_location' hook %s returned "
2379
2383
                        "None, not a URL." % hook_name)
2380
 
            self._activate_fallback_location(url)
 
2384
            self._activate_fallback_location(url, None)
2381
2385
 
2382
2386
    def __init__(self, *args, **kwargs):
2383
2387
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2384
 
        super(BzrBranch7, self).__init__(*args, **kwargs)
 
2388
        super(BzrBranch8, self).__init__(*args, **kwargs)
2385
2389
        self._last_revision_info_cache = None
2386
2390
        self._partial_revision_history_cache = []
 
2391
        self._reference_info = None
2387
2392
 
2388
2393
    def _clear_cached_state(self):
2389
 
        super(BzrBranch7, self)._clear_cached_state()
 
2394
        super(BzrBranch8, self)._clear_cached_state()
2390
2395
        self._last_revision_info_cache = None
2391
2396
        self._partial_revision_history_cache = []
 
2397
        self._reference_info = None
2392
2398
 
2393
2399
    def _last_revision_info(self):
2394
2400
        revision_string = self._transport.get_bytes('last-revision')
2504
2510
        """Set the parent branch"""
2505
2511
        return self._get_config_location('parent_location')
2506
2512
 
 
2513
    @needs_write_lock
 
2514
    def _set_all_reference_info(self, info_dict):
 
2515
        """Replace all reference info stored in a branch.
 
2516
 
 
2517
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
 
2518
        """
 
2519
        s = StringIO()
 
2520
        writer = rio.RioWriter(s)
 
2521
        for key, (tree_path, branch_location) in info_dict.iteritems():
 
2522
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
 
2523
                                branch_location=branch_location)
 
2524
            writer.write_stanza(stanza)
 
2525
        self._transport.put_bytes('references', s.getvalue())
 
2526
        self._reference_info = info_dict
 
2527
 
 
2528
    @needs_read_lock
 
2529
    def _get_all_reference_info(self):
 
2530
        """Return all the reference info stored in a branch.
 
2531
 
 
2532
        :return: A dict of {file_id: (tree_path, branch_location)}
 
2533
        """
 
2534
        if self._reference_info is not None:
 
2535
            return self._reference_info
 
2536
        rio_file = self._transport.get('references')
 
2537
        try:
 
2538
            stanzas = rio.read_stanzas(rio_file)
 
2539
            info_dict = dict((s['file_id'], (s['tree_path'],
 
2540
                             s['branch_location'])) for s in stanzas)
 
2541
        finally:
 
2542
            rio_file.close()
 
2543
        self._reference_info = info_dict
 
2544
        return info_dict
 
2545
 
 
2546
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2547
        """Set the branch location to use for a tree reference.
 
2548
 
 
2549
        :param file_id: The file-id of the tree reference.
 
2550
        :param tree_path: The path of the tree reference in the tree.
 
2551
        :param branch_location: The location of the branch to retrieve tree
 
2552
            references from.
 
2553
        """
 
2554
        info_dict = self._get_all_reference_info()
 
2555
        info_dict[file_id] = (tree_path, branch_location)
 
2556
        if None in (tree_path, branch_location):
 
2557
            if tree_path is not None:
 
2558
                raise ValueError('tree_path must be None when branch_location'
 
2559
                                 ' is None.')
 
2560
            if branch_location is not None:
 
2561
                raise ValueError('branch_location must be None when tree_path'
 
2562
                                 ' is None.')
 
2563
            del info_dict[file_id]
 
2564
        self._set_all_reference_info(info_dict)
 
2565
 
 
2566
    def get_reference_info(self, file_id):
 
2567
        """Get the tree_path and branch_location for a tree reference.
 
2568
 
 
2569
        :return: a tuple of (tree_path, branch_location)
 
2570
        """
 
2571
        return self._get_all_reference_info().get(file_id, (None, None))
 
2572
 
 
2573
    def reference_parent(self, file_id, path, possible_transports=None):
 
2574
        """Return the parent branch for a tree-reference file_id.
 
2575
 
 
2576
        :param file_id: The file_id of the tree reference
 
2577
        :param path: The path of the file_id in the tree
 
2578
        :return: A branch associated with the file_id
 
2579
        """
 
2580
        branch_location = self.get_reference_info(file_id)[1]
 
2581
        if branch_location is None:
 
2582
            return Branch.reference_parent(self, file_id, path,
 
2583
                                           possible_transports)
 
2584
        branch_location = urlutils.join(self.base, branch_location)
 
2585
        return Branch.open(branch_location,
 
2586
                           possible_transports=possible_transports)
 
2587
 
2507
2588
    def set_push_location(self, location):
2508
2589
        """See Branch.set_push_location."""
2509
2590
        self._set_config_location('push_location', location)
2607
2688
        return self.revno() - index
2608
2689
 
2609
2690
 
 
2691
class BzrBranch7(BzrBranch8):
 
2692
    """A branch with support for a fallback repository."""
 
2693
 
 
2694
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2695
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
 
2696
 
 
2697
    def get_reference_info(self, file_id):
 
2698
        Branch.get_reference_info(self, file_id)
 
2699
 
 
2700
    def reference_parent(self, file_id, path, possible_transports=None):
 
2701
        return Branch.reference_parent(self, file_id, path,
 
2702
                                       possible_transports)
 
2703
 
 
2704
 
2610
2705
class BzrBranch6(BzrBranch7):
2611
2706
    """See BzrBranchFormat6 for the capabilities of this branch.
2612
2707
 
2756
2851
        branch._transport.put_bytes('format', format.get_format_string())
2757
2852
 
2758
2853
 
 
2854
class Converter7to8(object):
 
2855
    """Perform an in-place upgrade of format 6 to format 7"""
 
2856
 
 
2857
    def convert(self, branch):
 
2858
        format = BzrBranchFormat8()
 
2859
        branch._transport.put_bytes('references', '')
 
2860
        # update target format
 
2861
        branch._transport.put_bytes('format', format.get_format_string())
 
2862
 
2759
2863
 
2760
2864
def _run_with_write_locked_target(target, callable, *args, **kwargs):
2761
2865
    """Run ``callable(*args, **kwargs)``, write-locking target for the
2806
2910
        """Return a tuple with the Branch formats to use when testing."""
2807
2911
        raise NotImplementedError(self._get_branch_formats_to_test)
2808
2912
 
 
2913
    def pull(self, overwrite=False, stop_revision=None,
 
2914
             possible_transports=None, local=False):
 
2915
        """Mirror source into target branch.
 
2916
 
 
2917
        The target branch is considered to be 'local', having low latency.
 
2918
 
 
2919
        :returns: PullResult instance
 
2920
        """
 
2921
        raise NotImplementedError(self.pull)
 
2922
 
2809
2923
    def update_revisions(self, stop_revision=None, overwrite=False,
2810
2924
                         graph=None):
2811
2925
        """Pull in new perfect-fit revisions.
2819
2933
        """
2820
2934
        raise NotImplementedError(self.update_revisions)
2821
2935
 
 
2936
    def push(self, overwrite=False, stop_revision=None,
 
2937
             _override_hook_source_branch=None):
 
2938
        """Mirror the source branch into the target branch.
 
2939
 
 
2940
        The source branch is considered to be 'local', having low latency.
 
2941
        """
 
2942
        raise NotImplementedError(self.push)
 
2943
 
2822
2944
 
2823
2945
class GenericInterBranch(InterBranch):
2824
2946
    """InterBranch implementation that uses public Branch functions.
2871
2993
        finally:
2872
2994
            self.source.unlock()
2873
2995
 
 
2996
    def pull(self, overwrite=False, stop_revision=None,
 
2997
             possible_transports=None, _hook_master=None, run_hooks=True,
 
2998
             _override_hook_target=None, local=False):
 
2999
        """See Branch.pull.
 
3000
 
 
3001
        :param _hook_master: Private parameter - set the branch to
 
3002
            be supplied as the master to pull hooks.
 
3003
        :param run_hooks: Private parameter - if false, this branch
 
3004
            is being called because it's the master of the primary branch,
 
3005
            so it should not run its hooks.
 
3006
        :param _override_hook_target: Private parameter - set the branch to be
 
3007
            supplied as the target_branch to pull hooks.
 
3008
        :param local: Only update the local branch, and not the bound branch.
 
3009
        """
 
3010
        # This type of branch can't be bound.
 
3011
        if local:
 
3012
            raise errors.LocalRequiresBoundBranch()
 
3013
        result = PullResult()
 
3014
        result.source_branch = self.source
 
3015
        if _override_hook_target is None:
 
3016
            result.target_branch = self.target
 
3017
        else:
 
3018
            result.target_branch = _override_hook_target
 
3019
        self.source.lock_read()
 
3020
        try:
 
3021
            # We assume that during 'pull' the target repository is closer than
 
3022
            # the source one.
 
3023
            self.source.update_references(self.target)
 
3024
            graph = self.target.repository.get_graph(self.source.repository)
 
3025
            # TODO: Branch formats should have a flag that indicates 
 
3026
            # that revno's are expensive, and pull() should honor that flag.
 
3027
            # -- JRV20090506
 
3028
            result.old_revno, result.old_revid = \
 
3029
                self.target.last_revision_info()
 
3030
            self.target.update_revisions(self.source, stop_revision,
 
3031
                overwrite=overwrite, graph=graph)
 
3032
            # TODO: The old revid should be specified when merging tags, 
 
3033
            # so a tags implementation that versions tags can only 
 
3034
            # pull in the most recent changes. -- JRV20090506
 
3035
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3036
                overwrite)
 
3037
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3038
            if _hook_master:
 
3039
                result.master_branch = _hook_master
 
3040
                result.local_branch = result.target_branch
 
3041
            else:
 
3042
                result.master_branch = result.target_branch
 
3043
                result.local_branch = None
 
3044
            if run_hooks:
 
3045
                for hook in Branch.hooks['post_pull']:
 
3046
                    hook(result)
 
3047
        finally:
 
3048
            self.source.unlock()
 
3049
        return result
 
3050
 
 
3051
    def push(self, overwrite=False, stop_revision=None,
 
3052
             _override_hook_source_branch=None):
 
3053
        """See InterBranch.push.
 
3054
 
 
3055
        This is the basic concrete implementation of push()
 
3056
 
 
3057
        :param _override_hook_source_branch: If specified, run
 
3058
        the hooks passing this Branch as the source, rather than self.
 
3059
        This is for use of RemoteBranch, where push is delegated to the
 
3060
        underlying vfs-based Branch.
 
3061
        """
 
3062
        # TODO: Public option to disable running hooks - should be trivial but
 
3063
        # needs tests.
 
3064
        self.source.lock_read()
 
3065
        try:
 
3066
            return _run_with_write_locked_target(
 
3067
                self.target, self._push_with_bound_branches, overwrite,
 
3068
                stop_revision,
 
3069
                _override_hook_source_branch=_override_hook_source_branch)
 
3070
        finally:
 
3071
            self.source.unlock()
 
3072
        return result
 
3073
 
 
3074
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3075
            _override_hook_source_branch=None):
 
3076
        """Push from source into target, and into target's master if any.
 
3077
        """
 
3078
        def _run_hooks():
 
3079
            if _override_hook_source_branch:
 
3080
                result.source_branch = _override_hook_source_branch
 
3081
            for hook in Branch.hooks['post_push']:
 
3082
                hook(result)
 
3083
 
 
3084
        bound_location = self.target.get_bound_location()
 
3085
        if bound_location and self.target.base != bound_location:
 
3086
            # there is a master branch.
 
3087
            #
 
3088
            # XXX: Why the second check?  Is it even supported for a branch to
 
3089
            # be bound to itself? -- mbp 20070507
 
3090
            master_branch = self.target.get_master_branch()
 
3091
            master_branch.lock_write()
 
3092
            try:
 
3093
                # push into the master from the source branch.
 
3094
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3095
                # and push into the target branch from the source. Note that we
 
3096
                # push from the source branch again, because its considered the
 
3097
                # highest bandwidth repository.
 
3098
                result = self.source._basic_push(self.target, overwrite,
 
3099
                    stop_revision)
 
3100
                result.master_branch = master_branch
 
3101
                result.local_branch = self.target
 
3102
                _run_hooks()
 
3103
                return result
 
3104
            finally:
 
3105
                master_branch.unlock()
 
3106
        else:
 
3107
            # no master branch
 
3108
            result = self.source._basic_push(self.target, overwrite,
 
3109
                stop_revision)
 
3110
            # TODO: Why set master_branch and local_branch if there's no
 
3111
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3112
            # 20070504
 
3113
            result.master_branch = self.target
 
3114
            result.local_branch = None
 
3115
            _run_hooks()
 
3116
            return result
 
3117
 
2874
3118
    @classmethod
2875
3119
    def is_compatible(self, source, target):
2876
3120
        # GenericBranch uses the public API, so always compatible
2877
3121
        return True
2878
3122
 
2879
3123
 
 
3124
class InterToBranch5(GenericInterBranch):
 
3125
 
 
3126
    @staticmethod
 
3127
    def _get_branch_formats_to_test():
 
3128
        return BranchFormat._default_format, BzrBranchFormat5()
 
3129
 
 
3130
    def pull(self, overwrite=False, stop_revision=None,
 
3131
             possible_transports=None, run_hooks=True,
 
3132
             _override_hook_target=None, local=False):
 
3133
        """Pull from source into self, updating my master if any.
 
3134
 
 
3135
        :param run_hooks: Private parameter - if false, this branch
 
3136
            is being called because it's the master of the primary branch,
 
3137
            so it should not run its hooks.
 
3138
        """
 
3139
        bound_location = self.target.get_bound_location()
 
3140
        if local and not bound_location:
 
3141
            raise errors.LocalRequiresBoundBranch()
 
3142
        master_branch = None
 
3143
        if not local and bound_location and self.source.base != bound_location:
 
3144
            # not pulling from master, so we need to update master.
 
3145
            master_branch = self.target.get_master_branch(possible_transports)
 
3146
            master_branch.lock_write()
 
3147
        try:
 
3148
            if master_branch:
 
3149
                # pull from source into master.
 
3150
                master_branch.pull(self.source, overwrite, stop_revision,
 
3151
                    run_hooks=False)
 
3152
            return super(InterToBranch5, self).pull(overwrite,
 
3153
                stop_revision, _hook_master=master_branch,
 
3154
                run_hooks=run_hooks,
 
3155
                _override_hook_target=_override_hook_target)
 
3156
        finally:
 
3157
            if master_branch:
 
3158
                master_branch.unlock()
 
3159
 
 
3160
 
2880
3161
InterBranch.register_optimiser(GenericInterBranch)
 
3162
InterBranch.register_optimiser(InterToBranch5)