~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

Revert the dirstate/transform changes, so we have a pure 'lstat/fstat' change.

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
    check,
26
26
    chk_map,
27
27
    config,
 
28
    controldir,
28
29
    debug,
29
 
    errors,
30
30
    fetch as _mod_fetch,
31
31
    fifo_cache,
32
32
    generate_ids,
34
34
    graph,
35
35
    inventory,
36
36
    inventory_delta,
37
 
    lazy_regex,
38
37
    lockable_files,
39
38
    lockdir,
40
39
    lru_cache,
41
40
    osutils,
 
41
    pyutils,
42
42
    revision as _mod_revision,
43
43
    static_tuple,
44
 
    symbol_versioning,
45
44
    trace,
46
45
    tsort,
47
 
    ui,
48
46
    versionedfile,
49
47
    )
50
48
from bzrlib.bundle import serializer
 
49
from bzrlib.recordcounter import RecordCounter
51
50
from bzrlib.revisiontree import RevisionTree
52
51
from bzrlib.store.versioned import VersionedFileStore
53
52
from bzrlib.testament import Testament
54
53
""")
55
54
 
 
55
from bzrlib import (
 
56
    errors,
 
57
    registry,
 
58
    symbol_versioning,
 
59
    ui,
 
60
    )
56
61
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
57
62
from bzrlib.inter import InterObject
58
63
from bzrlib.inventory import (
61
66
    ROOT_ID,
62
67
    entry_factory,
63
68
    )
64
 
from bzrlib.lock import _RelockDebugMixin
65
 
from bzrlib import registry
 
69
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
66
70
from bzrlib.trace import (
67
71
    log_exception_quietly, note, mutter, mutter_callsite, warning)
68
72
 
71
75
_deprecation_warning_done = False
72
76
 
73
77
 
 
78
class IsInWriteGroupError(errors.InternalBzrError):
 
79
 
 
80
    _fmt = "May not refresh_data of repo %(repo)s while in a write group."
 
81
 
 
82
    def __init__(self, repo):
 
83
        errors.InternalBzrError.__init__(self, repo=repo)
 
84
 
 
85
 
74
86
class CommitBuilder(object):
75
87
    """Provides an interface to build up a commit.
76
88
 
82
94
    record_root_entry = True
83
95
    # the default CommitBuilder does not manage trees whose root is versioned.
84
96
    _versioned_root = False
 
97
    # this commit builder supports the record_entry_contents interface
 
98
    supports_record_entry_contents = True
85
99
 
86
100
    def __init__(self, repository, parents, config, timestamp=None,
87
101
                 timezone=None, committer=None, revprops=None,
101
115
 
102
116
        if committer is None:
103
117
            self._committer = self._config.username()
 
118
        elif not isinstance(committer, unicode):
 
119
            self._committer = committer.decode() # throw if non-ascii
104
120
        else:
105
121
            self._committer = committer
106
122
 
160
176
            self._validate_unicode_text(value,
161
177
                                        'revision property (%s)' % (key,))
162
178
 
 
179
    def _ensure_fallback_inventories(self):
 
180
        """Ensure that appropriate inventories are available.
 
181
 
 
182
        This only applies to repositories that are stacked, and is about
 
183
        enusring the stacking invariants. Namely, that for any revision that is
 
184
        present, we either have all of the file content, or we have the parent
 
185
        inventory and the delta file content.
 
186
        """
 
187
        if not self.repository._fallback_repositories:
 
188
            return
 
189
        if not self.repository._format.supports_chks:
 
190
            raise errors.BzrError("Cannot commit directly to a stacked branch"
 
191
                " in pre-2a formats. See "
 
192
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
 
193
        # This is a stacked repo, we need to make sure we have the parent
 
194
        # inventories for the parents.
 
195
        parent_keys = [(p,) for p in self.parents]
 
196
        parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
 
197
        missing_parent_keys = set([pk for pk in parent_keys
 
198
                                       if pk not in parent_map])
 
199
        fallback_repos = list(reversed(self.repository._fallback_repositories))
 
200
        missing_keys = [('inventories', pk[0])
 
201
                        for pk in missing_parent_keys]
 
202
        resume_tokens = []
 
203
        while missing_keys and fallback_repos:
 
204
            fallback_repo = fallback_repos.pop()
 
205
            source = fallback_repo._get_source(self.repository._format)
 
206
            sink = self.repository._get_sink()
 
207
            stream = source.get_stream_for_missing_keys(missing_keys)
 
208
            missing_keys = sink.insert_stream_without_locking(stream,
 
209
                self.repository._format)
 
210
        if missing_keys:
 
211
            raise errors.BzrError('Unable to fill in parent inventories for a'
 
212
                                  ' stacked branch')
 
213
 
163
214
    def commit(self, message):
164
215
        """Make the actual commit.
165
216
 
177
228
        rev.parent_ids = self.parents
178
229
        self.repository.add_revision(self._new_revision_id, rev,
179
230
            self.new_inventory, self._config)
 
231
        self._ensure_fallback_inventories()
180
232
        self.repository.commit_write_group()
181
233
        return self._new_revision_id
182
234
 
231
283
 
232
284
    def _gen_revision_id(self):
233
285
        """Return new revision-id."""
234
 
        return generate_ids.gen_revision_id(self._config.username(),
235
 
                                            self._timestamp)
 
286
        return generate_ids.gen_revision_id(self._committer, self._timestamp)
236
287
 
237
288
    def _generate_revision_if_needed(self):
238
289
        """Create a revision id if None was supplied.
278
329
 
279
330
        :param tree: The tree which is being committed.
280
331
        """
281
 
        # NB: if there are no parents then this method is not called, so no
282
 
        # need to guard on parents having length.
 
332
        if len(self.parents) == 0:
 
333
            raise errors.RootMissing()
283
334
        entry = entry_factory['directory'](tree.path2id(''), '',
284
335
            None)
285
336
        entry.revision = self._new_revision_id
423
474
            else:
424
475
                # we don't need to commit this, because the caller already
425
476
                # determined that an existing revision of this file is
426
 
                # appropriate. If its not being considered for committing then
 
477
                # appropriate. If it's not being considered for committing then
427
478
                # it and all its parents to the root must be unaltered so
428
479
                # no-change against the basis.
429
480
                if ie.revision == self._new_revision_id:
745
796
                    # after iter_changes examines and decides it has changed,
746
797
                    # we will unconditionally record a new version even if some
747
798
                    # other process reverts it while commit is running (with
748
 
                    # the revert happening after iter_changes did it's
 
799
                    # the revert happening after iter_changes did its
749
800
                    # examination).
750
801
                    if change[7][1]:
751
802
                        entry.executable = True
860
911
        # versioned roots do not change unless the tree found a change.
861
912
 
862
913
 
863
 
class RepositoryWriteLockResult(object):
 
914
class RepositoryWriteLockResult(LogicalLockResult):
864
915
    """The result of write locking a repository.
865
916
 
866
917
    :ivar repository_token: The token obtained from the underlying lock, or
869
920
    """
870
921
 
871
922
    def __init__(self, unlock, repository_token):
 
923
        LogicalLockResult.__init__(self, unlock)
872
924
        self.repository_token = repository_token
873
 
        self.unlock = unlock
874
925
 
875
 
    def __str__(self):
 
926
    def __repr__(self):
876
927
        return "RepositoryWriteLockResult(%s, %s)" % (self.repository_token,
877
928
            self.unlock)
878
929
 
881
932
# Repositories
882
933
 
883
934
 
884
 
class Repository(_RelockDebugMixin, bzrdir.ControlComponent):
 
935
class Repository(_RelockDebugMixin, controldir.ControlComponent):
885
936
    """Repository holding history for one or more branches.
886
937
 
887
938
    The repository holds and retrieves historical information including
934
985
        pointing to .bzr/repository.
935
986
    """
936
987
 
937
 
    # What class to use for a CommitBuilder. Often its simpler to change this
 
988
    # What class to use for a CommitBuilder. Often it's simpler to change this
938
989
    # in a Repository class subclass rather than to override
939
990
    # get_commit_builder.
940
991
    _commit_builder_class = CommitBuilder
941
 
    # The search regex used by xml based repositories to determine what things
942
 
    # where changed in a single commit.
943
 
    _file_ids_altered_regex = lazy_regex.lazy_compile(
944
 
        r'file_id="(?P<file_id>[^"]+)"'
945
 
        r'.* revision="(?P<revision_id>[^"]+)"'
946
 
        )
947
992
 
948
993
    def abort_write_group(self, suppress_errors=False):
949
994
        """Commit the contents accrued within the current write group.
1035
1080
                " id and insertion revid (%r, %r)"
1036
1081
                % (inv.revision_id, revision_id))
1037
1082
        if inv.root is None:
1038
 
            raise AssertionError()
 
1083
            raise errors.RootMissing()
1039
1084
        return self._add_inventory_checked(revision_id, inv, parents)
1040
1085
 
1041
1086
    def _add_inventory_checked(self, revision_id, inv, parents):
1434
1479
            for repo in self._fallback_repositories:
1435
1480
                repo.lock_read()
1436
1481
            self._refresh_data()
1437
 
        return self
 
1482
        return LogicalLockResult(self.unlock)
1438
1483
 
1439
1484
    def get_physical_lock_status(self):
1440
1485
        return self.control_files.get_physical_lock_status()
1546
1591
        return ret
1547
1592
 
1548
1593
    @needs_read_lock
1549
 
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
 
1594
    def search_missing_revision_ids(self, other,
 
1595
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
 
1596
            find_ghosts=True, revision_ids=None, if_present_ids=None):
1550
1597
        """Return the revision ids that other has that this does not.
1551
1598
 
1552
1599
        These are returned in topological order.
1553
1600
 
1554
1601
        revision_id: only return revision ids included by revision_id.
1555
1602
        """
 
1603
        if symbol_versioning.deprecated_passed(revision_id):
 
1604
            symbol_versioning.warn(
 
1605
                'search_missing_revision_ids(revision_id=...) was '
 
1606
                'deprecated in 2.4.  Use revision_ids=[...] instead.',
 
1607
                DeprecationWarning, stacklevel=3)
 
1608
            if revision_ids is not None:
 
1609
                raise AssertionError(
 
1610
                    'revision_ids is mutually exclusive with revision_id')
 
1611
            if revision_id is not None:
 
1612
                revision_ids = [revision_id]
1556
1613
        return InterRepository.get(other, self).search_missing_revision_ids(
1557
 
            revision_id, find_ghosts)
 
1614
            find_ghosts=find_ghosts, revision_ids=revision_ids,
 
1615
            if_present_ids=if_present_ids)
1558
1616
 
1559
1617
    @staticmethod
1560
1618
    def open(base):
1658
1716
        return missing_keys
1659
1717
 
1660
1718
    def refresh_data(self):
1661
 
        """Re-read any data needed to to synchronise with disk.
 
1719
        """Re-read any data needed to synchronise with disk.
1662
1720
 
1663
1721
        This method is intended to be called after another repository instance
1664
1722
        (such as one used by a smart server) has inserted data into the
1665
 
        repository. It may not be called during a write group, but may be
1666
 
        called at any other time.
 
1723
        repository. On all repositories this will work outside of write groups.
 
1724
        Some repository formats (pack and newer for bzrlib native formats)
 
1725
        support refresh_data inside write groups. If called inside a write
 
1726
        group on a repository that does not support refreshing in a write group
 
1727
        IsInWriteGroupError will be raised.
1667
1728
        """
1668
 
        if self.is_in_write_group():
1669
 
            raise errors.InternalBzrError(
1670
 
                "May not refresh_data while in a write group.")
1671
1729
        self._refresh_data()
1672
1730
 
1673
1731
    def resume_write_group(self, tokens):
1682
1740
    def _resume_write_group(self, tokens):
1683
1741
        raise errors.UnsuspendableWriteGroup(self)
1684
1742
 
1685
 
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
1743
    def fetch(self, source, revision_id=None, find_ghosts=False,
1686
1744
            fetch_spec=None):
1687
1745
        """Fetch the content required to construct revision_id from source.
1688
1746
 
1712
1770
                "May not fetch while in a write group.")
1713
1771
        # fast path same-url fetch operations
1714
1772
        # TODO: lift out to somewhere common with RemoteRepository
1715
 
        # <https://bugs.edge.launchpad.net/bzr/+bug/401646>
 
1773
        # <https://bugs.launchpad.net/bzr/+bug/401646>
1716
1774
        if (self.has_same_location(source)
1717
1775
            and fetch_spec is None
1718
1776
            and self._has_same_fallbacks(source)):
1722
1780
                not _mod_revision.is_null(revision_id)):
1723
1781
                self.get_revision(revision_id)
1724
1782
            return 0, []
1725
 
        # if there is no specific appropriate InterRepository, this will get
1726
 
        # the InterRepository base class, which raises an
1727
 
        # IncompatibleRepositories when asked to fetch.
1728
1783
        inter = InterRepository.get(source, self)
1729
 
        return inter.fetch(revision_id=revision_id, pb=pb,
 
1784
        return inter.fetch(revision_id=revision_id,
1730
1785
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1731
1786
 
1732
1787
    def create_bundle(self, target, base, fileobj, format=None):
1746
1801
        :param revprops: Optional dictionary of revision properties.
1747
1802
        :param revision_id: Optional revision id.
1748
1803
        """
1749
 
        if self._fallback_repositories:
1750
 
            raise errors.BzrError("Cannot commit from a lightweight checkout "
1751
 
                "to a stacked branch. See "
 
1804
        if self._fallback_repositories and not self._format.supports_chks:
 
1805
            raise errors.BzrError("Cannot commit directly to a stacked branch"
 
1806
                " in pre-2a formats. See "
1752
1807
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1753
1808
        result = self._commit_builder_class(self, parents, config,
1754
1809
            timestamp, timezone, committer, revprops, revision_id)
2003
2058
        w = self.inventories
2004
2059
        pb = ui.ui_factory.nested_progress_bar()
2005
2060
        try:
2006
 
            return self._find_text_key_references_from_xml_inventory_lines(
 
2061
            return self._serializer._find_text_key_references(
2007
2062
                w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
2008
2063
        finally:
2009
2064
            pb.finished()
2010
2065
 
2011
 
    def _find_text_key_references_from_xml_inventory_lines(self,
2012
 
        line_iterator):
2013
 
        """Core routine for extracting references to texts from inventories.
2014
 
 
2015
 
        This performs the translation of xml lines to revision ids.
2016
 
 
2017
 
        :param line_iterator: An iterator of lines, origin_version_id
2018
 
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
2019
 
            to whether they were referred to by the inventory of the
2020
 
            revision_id that they contain. Note that if that revision_id was
2021
 
            not part of the line_iterator's output then False will be given -
2022
 
            even though it may actually refer to that key.
2023
 
        """
2024
 
        if not self._serializer.support_altered_by_hack:
2025
 
            raise AssertionError(
2026
 
                "_find_text_key_references_from_xml_inventory_lines only "
2027
 
                "supported for branches which store inventory as unnested xml"
2028
 
                ", not on %r" % self)
2029
 
        result = {}
2030
 
 
2031
 
        # this code needs to read every new line in every inventory for the
2032
 
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
2033
 
        # not present in one of those inventories is unnecessary but not
2034
 
        # harmful because we are filtering by the revision id marker in the
2035
 
        # inventory lines : we only select file ids altered in one of those
2036
 
        # revisions. We don't need to see all lines in the inventory because
2037
 
        # only those added in an inventory in rev X can contain a revision=X
2038
 
        # line.
2039
 
        unescape_revid_cache = {}
2040
 
        unescape_fileid_cache = {}
2041
 
 
2042
 
        # jam 20061218 In a big fetch, this handles hundreds of thousands
2043
 
        # of lines, so it has had a lot of inlining and optimizing done.
2044
 
        # Sorry that it is a little bit messy.
2045
 
        # Move several functions to be local variables, since this is a long
2046
 
        # running loop.
2047
 
        search = self._file_ids_altered_regex.search
2048
 
        unescape = _unescape_xml
2049
 
        setdefault = result.setdefault
2050
 
        for line, line_key in line_iterator:
2051
 
            match = search(line)
2052
 
            if match is None:
2053
 
                continue
2054
 
            # One call to match.group() returning multiple items is quite a
2055
 
            # bit faster than 2 calls to match.group() each returning 1
2056
 
            file_id, revision_id = match.group('file_id', 'revision_id')
2057
 
 
2058
 
            # Inlining the cache lookups helps a lot when you make 170,000
2059
 
            # lines and 350k ids, versus 8.4 unique ids.
2060
 
            # Using a cache helps in 2 ways:
2061
 
            #   1) Avoids unnecessary decoding calls
2062
 
            #   2) Re-uses cached strings, which helps in future set and
2063
 
            #      equality checks.
2064
 
            # (2) is enough that removing encoding entirely along with
2065
 
            # the cache (so we are using plain strings) results in no
2066
 
            # performance improvement.
2067
 
            try:
2068
 
                revision_id = unescape_revid_cache[revision_id]
2069
 
            except KeyError:
2070
 
                unescaped = unescape(revision_id)
2071
 
                unescape_revid_cache[revision_id] = unescaped
2072
 
                revision_id = unescaped
2073
 
 
2074
 
            # Note that unconditionally unescaping means that we deserialise
2075
 
            # every fileid, which for general 'pull' is not great, but we don't
2076
 
            # really want to have some many fulltexts that this matters anyway.
2077
 
            # RBC 20071114.
2078
 
            try:
2079
 
                file_id = unescape_fileid_cache[file_id]
2080
 
            except KeyError:
2081
 
                unescaped = unescape(file_id)
2082
 
                unescape_fileid_cache[file_id] = unescaped
2083
 
                file_id = unescaped
2084
 
 
2085
 
            key = (file_id, revision_id)
2086
 
            setdefault(key, False)
2087
 
            if revision_id == line_key[-1]:
2088
 
                result[key] = True
2089
 
        return result
2090
 
 
2091
2066
    def _inventory_xml_lines_for_keys(self, keys):
2092
2067
        """Get a line iterator of the sort needed for findind references.
2093
2068
 
2123
2098
        revision_ids. Each altered file-ids has the exact revision_ids that
2124
2099
        altered it listed explicitly.
2125
2100
        """
2126
 
        seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2101
        seen = set(self._serializer._find_text_key_references(
2127
2102
                line_iterator).iterkeys())
2128
2103
        parent_keys = self._find_parent_keys_of_revisions(revision_keys)
2129
 
        parent_seen = set(self._find_text_key_references_from_xml_inventory_lines(
 
2104
        parent_seen = set(self._serializer._find_text_key_references(
2130
2105
            self._inventory_xml_lines_for_keys(parent_keys)))
2131
2106
        new_keys = seen - parent_seen
2132
2107
        result = {}
2500
2475
            ancestors will be traversed.
2501
2476
        """
2502
2477
        graph = self.get_graph()
2503
 
        next_id = revision_id
2504
 
        while True:
2505
 
            if next_id in (None, _mod_revision.NULL_REVISION):
2506
 
                return
2507
 
            try:
2508
 
                parents = graph.get_parent_map([next_id])[next_id]
2509
 
            except KeyError:
2510
 
                raise errors.RevisionNotPresent(next_id, self)
2511
 
            yield next_id
2512
 
            if len(parents) == 0:
2513
 
                return
2514
 
            else:
2515
 
                next_id = parents[0]
 
2478
        stop_revisions = (None, _mod_revision.NULL_REVISION)
 
2479
        return graph.iter_lefthand_ancestry(revision_id, stop_revisions)
2516
2480
 
2517
2481
    def is_shared(self):
2518
2482
        """Return True if this repository is flagged as a shared repository."""
2619
2583
        types it should be a no-op that just returns.
2620
2584
 
2621
2585
        This stub method does not require a lock, but subclasses should use
2622
 
        @needs_write_lock as this is a long running call its reasonable to
 
2586
        @needs_write_lock as this is a long running call it's reasonable to
2623
2587
        implicitly lock for the user.
2624
2588
 
2625
2589
        :param hint: If not supplied, the whole repository is packed.
2771
2735
        return result
2772
2736
 
2773
2737
    def _warn_if_deprecated(self, branch=None):
 
2738
        if not self._format.is_deprecated():
 
2739
            return
2774
2740
        global _deprecation_warning_done
2775
2741
        if _deprecation_warning_done:
2776
2742
            return
2818
2784
        raise NotImplementedError(self.revision_graph_can_have_wrong_parents)
2819
2785
 
2820
2786
 
2821
 
# remove these delegates a while after bzr 0.15
2822
 
def __make_delegated(name, from_module):
2823
 
    def _deprecated_repository_forwarder():
2824
 
        symbol_versioning.warn('%s moved to %s in bzr 0.15'
2825
 
            % (name, from_module),
2826
 
            DeprecationWarning,
2827
 
            stacklevel=2)
2828
 
        m = __import__(from_module, globals(), locals(), [name])
2829
 
        try:
2830
 
            return getattr(m, name)
2831
 
        except AttributeError:
2832
 
            raise AttributeError('module %s has no name %s'
2833
 
                    % (m, name))
2834
 
    globals()[name] = _deprecated_repository_forwarder
2835
 
 
2836
 
for _name in [
2837
 
        'AllInOneRepository',
2838
 
        'WeaveMetaDirRepository',
2839
 
        'PreSplitOutRepositoryFormat',
2840
 
        'RepositoryFormat4',
2841
 
        'RepositoryFormat5',
2842
 
        'RepositoryFormat6',
2843
 
        'RepositoryFormat7',
2844
 
        ]:
2845
 
    __make_delegated(_name, 'bzrlib.repofmt.weaverepo')
2846
 
 
2847
 
for _name in [
2848
 
        'KnitRepository',
2849
 
        'RepositoryFormatKnit',
2850
 
        'RepositoryFormatKnit1',
2851
 
        ]:
2852
 
    __make_delegated(_name, 'bzrlib.repofmt.knitrepo')
2853
 
 
2854
 
 
2855
2787
def install_revision(repository, rev, revision_tree):
2856
2788
    """Install all revision data into a repository."""
2857
2789
    install_revisions(repository, [(rev, revision_tree, None)])
2989
2921
            control_files)
2990
2922
 
2991
2923
 
 
2924
class RepositoryFormatRegistry(controldir.ControlComponentFormatRegistry):
 
2925
    """Repository format registry."""
 
2926
 
 
2927
    def get_default(self):
 
2928
        """Return the current default format."""
 
2929
        from bzrlib import bzrdir
 
2930
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
2931
 
 
2932
 
2992
2933
network_format_registry = registry.FormatRegistry()
2993
2934
"""Registry of formats indexed by their network name.
2994
2935
 
2998
2939
"""
2999
2940
 
3000
2941
 
3001
 
format_registry = registry.FormatRegistry(network_format_registry)
 
2942
format_registry = RepositoryFormatRegistry(network_format_registry)
3002
2943
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
3003
2944
 
3004
2945
This can contain either format instances themselves, or classes/factories that
3009
2950
#####################################################################
3010
2951
# Repository Formats
3011
2952
 
3012
 
class RepositoryFormat(object):
 
2953
class RepositoryFormat(controldir.ControlComponentFormat):
3013
2954
    """A repository format.
3014
2955
 
3015
2956
    Formats provide four things:
3076
3017
    supports_tree_reference = None
3077
3018
    # Is the format experimental ?
3078
3019
    experimental = False
 
3020
    # Does this repository format escape funky characters, or does it create files with
 
3021
    # similar names as the versioned files in its contents on disk ?
 
3022
    supports_funky_characters = None
 
3023
    # Does this repository format support leaving locks?
 
3024
    supports_leaving_lock = None
 
3025
    # Does this format support the full VersionedFiles interface?
 
3026
    supports_full_versioned_files = None
3079
3027
 
3080
3028
    def __repr__(self):
3081
3029
        return "%s()" % self.__class__.__name__
3106
3054
                                            kind='repository')
3107
3055
 
3108
3056
    @classmethod
 
3057
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3109
3058
    def register_format(klass, format):
3110
 
        format_registry.register(format.get_format_string(), format)
 
3059
        format_registry.register(format)
3111
3060
 
3112
3061
    @classmethod
 
3062
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3113
3063
    def unregister_format(klass, format):
3114
 
        format_registry.remove(format.get_format_string())
 
3064
        format_registry.remove(format)
3115
3065
 
3116
3066
    @classmethod
 
3067
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3117
3068
    def get_default_format(klass):
3118
3069
        """Return the current default format."""
3119
 
        from bzrlib import bzrdir
3120
 
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
3070
        return format_registry.get_default()
3121
3071
 
3122
3072
    def get_format_string(self):
3123
3073
        """Return the ASCII format string that identifies this format.
3174
3124
        """
3175
3125
        return True
3176
3126
 
 
3127
    def is_deprecated(self):
 
3128
        """Is this format deprecated?
 
3129
 
 
3130
        Deprecated formats may trigger a user-visible warning recommending
 
3131
        the user to upgrade. They are still fully supported.
 
3132
        """
 
3133
        return False
 
3134
 
3177
3135
    def network_name(self):
3178
3136
        """A simple byte string uniquely identifying this format for RPC calls.
3179
3137
 
3218
3176
    rich_root_data = False
3219
3177
    supports_tree_reference = False
3220
3178
    supports_external_lookups = False
 
3179
    supports_leaving_lock = True
3221
3180
 
3222
3181
    @property
3223
3182
    def _matchingbzrdir(self):
3261
3220
        return self.get_format_string()
3262
3221
 
3263
3222
 
3264
 
# Pre-0.8 formats that don't have a disk format string (because they are
3265
 
# versioned by the matching control directory). We use the control directories
3266
 
# disk format string as a key for the network_name because they meet the
3267
 
# constraints (simple string, unique, immutable).
3268
 
network_format_registry.register_lazy(
3269
 
    "Bazaar-NG branch, format 5\n",
3270
 
    'bzrlib.repofmt.weaverepo',
3271
 
    'RepositoryFormat5',
3272
 
)
3273
 
network_format_registry.register_lazy(
3274
 
    "Bazaar-NG branch, format 6\n",
3275
 
    'bzrlib.repofmt.weaverepo',
3276
 
    'RepositoryFormat6',
3277
 
)
3278
 
 
3279
3223
# formats which have no format string are not discoverable or independently
3280
3224
# creatable on disk, so are not registered in format_registry.  They're
3281
 
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
 
3225
# all in bzrlib.repofmt.knitreponow.  When an instance of one of these is
3282
3226
# needed, it's constructed directly by the BzrDir.  Non-native formats where
3283
3227
# the repository is not separately opened are similar.
3284
3228
 
3285
3229
format_registry.register_lazy(
3286
 
    'Bazaar-NG Repository format 7',
3287
 
    'bzrlib.repofmt.weaverepo',
3288
 
    'RepositoryFormat7'
3289
 
    )
3290
 
 
3291
 
format_registry.register_lazy(
3292
3230
    'Bazaar-NG Knit Repository Format 1',
3293
3231
    'bzrlib.repofmt.knitrepo',
3294
3232
    'RepositoryFormatKnit1',
3349
3287
    'bzrlib.repofmt.pack_repo',
3350
3288
    'RepositoryFormatKnitPack6RichRoot',
3351
3289
    )
 
3290
format_registry.register_lazy(
 
3291
    'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
3292
    'bzrlib.repofmt.groupcompress_repo',
 
3293
    'RepositoryFormat2a',
 
3294
    )
3352
3295
 
3353
3296
# Development formats.
3354
 
# Obsolete but kept pending a CHK based subtree format.
 
3297
# Check their docstrings to see if/when they are obsolete.
3355
3298
format_registry.register_lazy(
3356
3299
    ("Bazaar development format 2 with subtree support "
3357
3300
        "(needs bzr.dev from before 1.8)\n"),
3358
3301
    'bzrlib.repofmt.pack_repo',
3359
3302
    'RepositoryFormatPackDevelopment2Subtree',
3360
3303
    )
3361
 
 
3362
 
# 1.14->1.16 go below here
3363
 
format_registry.register_lazy(
3364
 
    'Bazaar development format - group compression and chk inventory'
3365
 
        ' (needs bzr.dev from 1.14)\n',
3366
 
    'bzrlib.repofmt.groupcompress_repo',
3367
 
    'RepositoryFormatCHK1',
3368
 
    )
3369
 
 
3370
 
format_registry.register_lazy(
3371
 
    'Bazaar development format - chk repository with bencode revision '
3372
 
        'serialization (needs bzr.dev from 1.16)\n',
3373
 
    'bzrlib.repofmt.groupcompress_repo',
3374
 
    'RepositoryFormatCHK2',
3375
 
    )
3376
 
format_registry.register_lazy(
3377
 
    'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
3378
 
    'bzrlib.repofmt.groupcompress_repo',
3379
 
    'RepositoryFormat2a',
 
3304
format_registry.register_lazy(
 
3305
    'Bazaar development format 8\n',
 
3306
    'bzrlib.repofmt.groupcompress_repo',
 
3307
    'RepositoryFormat2aSubtree',
3380
3308
    )
3381
3309
 
3382
3310
 
3413
3341
        self.target.fetch(self.source, revision_id=revision_id)
3414
3342
 
3415
3343
    @needs_write_lock
3416
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3344
    def fetch(self, revision_id=None, find_ghosts=False,
3417
3345
            fetch_spec=None):
3418
3346
        """Fetch the content required to construct revision_id.
3419
3347
 
3421
3349
 
3422
3350
        :param revision_id: if None all content is copied, if NULL_REVISION no
3423
3351
                            content is copied.
3424
 
        :param pb: ignored.
3425
3352
        :return: None.
3426
3353
        """
3427
3354
        ui.ui_factory.warn_experimental_format_fetch(self)
3437
3364
                               fetch_spec=fetch_spec,
3438
3365
                               find_ghosts=find_ghosts)
3439
3366
 
3440
 
    def _walk_to_common_revisions(self, revision_ids):
 
3367
    def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
3441
3368
        """Walk out from revision_ids in source to revisions target has.
3442
3369
 
3443
3370
        :param revision_ids: The start point for the search.
3445
3372
        """
3446
3373
        target_graph = self.target.get_graph()
3447
3374
        revision_ids = frozenset(revision_ids)
 
3375
        if if_present_ids:
 
3376
            all_wanted_revs = revision_ids.union(if_present_ids)
 
3377
        else:
 
3378
            all_wanted_revs = revision_ids
3448
3379
        missing_revs = set()
3449
3380
        source_graph = self.source.get_graph()
3450
3381
        # ensure we don't pay silly lookup costs.
3451
 
        searcher = source_graph._make_breadth_first_searcher(revision_ids)
 
3382
        searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
3452
3383
        null_set = frozenset([_mod_revision.NULL_REVISION])
3453
3384
        searcher_exhausted = False
3454
3385
        while True:
3490
3421
        return searcher.get_result()
3491
3422
 
3492
3423
    @needs_read_lock
3493
 
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
3424
    def search_missing_revision_ids(self,
 
3425
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
 
3426
            find_ghosts=True, revision_ids=None, if_present_ids=None):
3494
3427
        """Return the revision ids that source has that target does not.
3495
3428
 
3496
3429
        :param revision_id: only return revision ids included by this
3497
 
                            revision_id.
 
3430
            revision_id.
 
3431
        :param revision_ids: return revision ids included by these
 
3432
            revision_ids.  NoSuchRevision will be raised if any of these
 
3433
            revisions are not present.
 
3434
        :param if_present_ids: like revision_ids, but will not cause
 
3435
            NoSuchRevision if any of these are absent, instead they will simply
 
3436
            not be in the result.  This is useful for e.g. finding revisions
 
3437
            to fetch for tags, which may reference absent revisions.
3498
3438
        :param find_ghosts: If True find missing revisions in deep history
3499
3439
            rather than just finding the surface difference.
3500
3440
        :return: A bzrlib.graph.SearchResult.
3501
3441
        """
 
3442
        if symbol_versioning.deprecated_passed(revision_id):
 
3443
            symbol_versioning.warn(
 
3444
                'search_missing_revision_ids(revision_id=...) was '
 
3445
                'deprecated in 2.4.  Use revision_ids=[...] instead.',
 
3446
                DeprecationWarning, stacklevel=2)
 
3447
            if revision_ids is not None:
 
3448
                raise AssertionError(
 
3449
                    'revision_ids is mutually exclusive with revision_id')
 
3450
            if revision_id is not None:
 
3451
                revision_ids = [revision_id]
 
3452
        del revision_id
3502
3453
        # stop searching at found target revisions.
3503
 
        if not find_ghosts and revision_id is not None:
3504
 
            return self._walk_to_common_revisions([revision_id])
 
3454
        if not find_ghosts and (revision_ids is not None or if_present_ids is
 
3455
                not None):
 
3456
            return self._walk_to_common_revisions(revision_ids,
 
3457
                    if_present_ids=if_present_ids)
3505
3458
        # generic, possibly worst case, slow code path.
3506
3459
        target_ids = set(self.target.all_revision_ids())
3507
 
        if revision_id is not None:
3508
 
            source_ids = self.source.get_ancestry(revision_id)
3509
 
            if source_ids[0] is not None:
3510
 
                raise AssertionError()
3511
 
            source_ids.pop(0)
3512
 
        else:
3513
 
            source_ids = self.source.all_revision_ids()
 
3460
        source_ids = self._present_source_revisions_for(
 
3461
            revision_ids, if_present_ids)
3514
3462
        result_set = set(source_ids).difference(target_ids)
3515
3463
        return self.source.revision_ids_to_search_result(result_set)
3516
3464
 
 
3465
    def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
 
3466
        """Returns set of all revisions in ancestry of revision_ids present in
 
3467
        the source repo.
 
3468
 
 
3469
        :param revision_ids: if None, all revisions in source are returned.
 
3470
        :param if_present_ids: like revision_ids, but if any/all of these are
 
3471
            absent no error is raised.
 
3472
        """
 
3473
        if revision_ids is not None or if_present_ids is not None:
 
3474
            # First, ensure all specified revisions exist.  Callers expect
 
3475
            # NoSuchRevision when they pass absent revision_ids here.
 
3476
            if revision_ids is None:
 
3477
                revision_ids = set()
 
3478
            if if_present_ids is None:
 
3479
                if_present_ids = set()
 
3480
            revision_ids = set(revision_ids)
 
3481
            if_present_ids = set(if_present_ids)
 
3482
            all_wanted_ids = revision_ids.union(if_present_ids)
 
3483
            graph = self.source.get_graph()
 
3484
            present_revs = set(graph.get_parent_map(all_wanted_ids))
 
3485
            missing = revision_ids.difference(present_revs)
 
3486
            if missing:
 
3487
                raise errors.NoSuchRevision(self.source, missing.pop())
 
3488
            found_ids = all_wanted_ids.intersection(present_revs)
 
3489
            source_ids = [rev_id for (rev_id, parents) in
 
3490
                          graph.iter_ancestry(found_ids)
 
3491
                          if rev_id != _mod_revision.NULL_REVISION
 
3492
                          and parents is not None]
 
3493
        else:
 
3494
            source_ids = self.source.all_revision_ids()
 
3495
        return set(source_ids)
 
3496
 
3517
3497
    @staticmethod
3518
3498
    def _same_model(source, target):
3519
3499
        """True if source and target have the same data representation.
3560
3540
        return InterRepository._same_model(source, target)
3561
3541
 
3562
3542
 
3563
 
class InterWeaveRepo(InterSameDataRepository):
3564
 
    """Optimised code paths between Weave based repositories.
3565
 
 
3566
 
    This should be in bzrlib/repofmt/weaverepo.py but we have not yet
3567
 
    implemented lazy inter-object optimisation.
3568
 
    """
3569
 
 
3570
 
    @classmethod
3571
 
    def _get_repo_format_to_test(self):
3572
 
        from bzrlib.repofmt import weaverepo
3573
 
        return weaverepo.RepositoryFormat7()
3574
 
 
3575
 
    @staticmethod
3576
 
    def is_compatible(source, target):
3577
 
        """Be compatible with known Weave formats.
3578
 
 
3579
 
        We don't test for the stores being of specific types because that
3580
 
        could lead to confusing results, and there is no need to be
3581
 
        overly general.
3582
 
        """
3583
 
        from bzrlib.repofmt.weaverepo import (
3584
 
                RepositoryFormat5,
3585
 
                RepositoryFormat6,
3586
 
                RepositoryFormat7,
3587
 
                )
3588
 
        try:
3589
 
            return (isinstance(source._format, (RepositoryFormat5,
3590
 
                                                RepositoryFormat6,
3591
 
                                                RepositoryFormat7)) and
3592
 
                    isinstance(target._format, (RepositoryFormat5,
3593
 
                                                RepositoryFormat6,
3594
 
                                                RepositoryFormat7)))
3595
 
        except AttributeError:
3596
 
            return False
3597
 
 
3598
 
    @needs_write_lock
3599
 
    def copy_content(self, revision_id=None):
3600
 
        """See InterRepository.copy_content()."""
3601
 
        # weave specific optimised path:
3602
 
        try:
3603
 
            self.target.set_make_working_trees(self.source.make_working_trees())
3604
 
        except (errors.RepositoryUpgradeRequired, NotImplemented):
3605
 
            pass
3606
 
        # FIXME do not peek!
3607
 
        if self.source._transport.listable():
3608
 
            pb = ui.ui_factory.nested_progress_bar()
3609
 
            try:
3610
 
                self.target.texts.insert_record_stream(
3611
 
                    self.source.texts.get_record_stream(
3612
 
                        self.source.texts.keys(), 'topological', False))
3613
 
                pb.update('Copying inventory', 0, 1)
3614
 
                self.target.inventories.insert_record_stream(
3615
 
                    self.source.inventories.get_record_stream(
3616
 
                        self.source.inventories.keys(), 'topological', False))
3617
 
                self.target.signatures.insert_record_stream(
3618
 
                    self.source.signatures.get_record_stream(
3619
 
                        self.source.signatures.keys(),
3620
 
                        'unordered', True))
3621
 
                self.target.revisions.insert_record_stream(
3622
 
                    self.source.revisions.get_record_stream(
3623
 
                        self.source.revisions.keys(),
3624
 
                        'topological', True))
3625
 
            finally:
3626
 
                pb.finished()
3627
 
        else:
3628
 
            self.target.fetch(self.source, revision_id=revision_id)
3629
 
 
3630
 
    @needs_read_lock
3631
 
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
3632
 
        """See InterRepository.missing_revision_ids()."""
3633
 
        # we want all revisions to satisfy revision_id in source.
3634
 
        # but we don't want to stat every file here and there.
3635
 
        # we want then, all revisions other needs to satisfy revision_id
3636
 
        # checked, but not those that we have locally.
3637
 
        # so the first thing is to get a subset of the revisions to
3638
 
        # satisfy revision_id in source, and then eliminate those that
3639
 
        # we do already have.
3640
 
        # this is slow on high latency connection to self, but as this
3641
 
        # disk format scales terribly for push anyway due to rewriting
3642
 
        # inventory.weave, this is considered acceptable.
3643
 
        # - RBC 20060209
3644
 
        if revision_id is not None:
3645
 
            source_ids = self.source.get_ancestry(revision_id)
3646
 
            if source_ids[0] is not None:
3647
 
                raise AssertionError()
3648
 
            source_ids.pop(0)
3649
 
        else:
3650
 
            source_ids = self.source._all_possible_ids()
3651
 
        source_ids_set = set(source_ids)
3652
 
        # source_ids is the worst possible case we may need to pull.
3653
 
        # now we want to filter source_ids against what we actually
3654
 
        # have in target, but don't try to check for existence where we know
3655
 
        # we do not have a revision as that would be pointless.
3656
 
        target_ids = set(self.target._all_possible_ids())
3657
 
        possibly_present_revisions = target_ids.intersection(source_ids_set)
3658
 
        actually_present_revisions = set(
3659
 
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
3660
 
        required_revisions = source_ids_set.difference(actually_present_revisions)
3661
 
        if revision_id is not None:
3662
 
            # we used get_ancestry to determine source_ids then we are assured all
3663
 
            # revisions referenced are present as they are installed in topological order.
3664
 
            # and the tip revision was validated by get_ancestry.
3665
 
            result_set = required_revisions
3666
 
        else:
3667
 
            # if we just grabbed the possibly available ids, then
3668
 
            # we only have an estimate of whats available and need to validate
3669
 
            # that against the revision records.
3670
 
            result_set = set(
3671
 
                self.source._eliminate_revisions_not_present(required_revisions))
3672
 
        return self.source.revision_ids_to_search_result(result_set)
3673
 
 
3674
 
 
3675
 
class InterKnitRepo(InterSameDataRepository):
3676
 
    """Optimised code paths between Knit based repositories."""
3677
 
 
3678
 
    @classmethod
3679
 
    def _get_repo_format_to_test(self):
3680
 
        from bzrlib.repofmt import knitrepo
3681
 
        return knitrepo.RepositoryFormatKnit1()
3682
 
 
3683
 
    @staticmethod
3684
 
    def is_compatible(source, target):
3685
 
        """Be compatible with known Knit formats.
3686
 
 
3687
 
        We don't test for the stores being of specific types because that
3688
 
        could lead to confusing results, and there is no need to be
3689
 
        overly general.
3690
 
        """
3691
 
        from bzrlib.repofmt.knitrepo import RepositoryFormatKnit
3692
 
        try:
3693
 
            are_knits = (isinstance(source._format, RepositoryFormatKnit) and
3694
 
                isinstance(target._format, RepositoryFormatKnit))
3695
 
        except AttributeError:
3696
 
            return False
3697
 
        return are_knits and InterRepository._same_model(source, target)
3698
 
 
3699
 
    @needs_read_lock
3700
 
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
3701
 
        """See InterRepository.missing_revision_ids()."""
3702
 
        if revision_id is not None:
3703
 
            source_ids = self.source.get_ancestry(revision_id)
3704
 
            if source_ids[0] is not None:
3705
 
                raise AssertionError()
3706
 
            source_ids.pop(0)
3707
 
        else:
3708
 
            source_ids = self.source.all_revision_ids()
3709
 
        source_ids_set = set(source_ids)
3710
 
        # source_ids is the worst possible case we may need to pull.
3711
 
        # now we want to filter source_ids against what we actually
3712
 
        # have in target, but don't try to check for existence where we know
3713
 
        # we do not have a revision as that would be pointless.
3714
 
        target_ids = set(self.target.all_revision_ids())
3715
 
        possibly_present_revisions = target_ids.intersection(source_ids_set)
3716
 
        actually_present_revisions = set(
3717
 
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
3718
 
        required_revisions = source_ids_set.difference(actually_present_revisions)
3719
 
        if revision_id is not None:
3720
 
            # we used get_ancestry to determine source_ids then we are assured all
3721
 
            # revisions referenced are present as they are installed in topological order.
3722
 
            # and the tip revision was validated by get_ancestry.
3723
 
            result_set = required_revisions
3724
 
        else:
3725
 
            # if we just grabbed the possibly available ids, then
3726
 
            # we only have an estimate of whats available and need to validate
3727
 
            # that against the revision records.
3728
 
            result_set = set(
3729
 
                self.source._eliminate_revisions_not_present(required_revisions))
3730
 
        return self.source.revision_ids_to_search_result(result_set)
3731
 
 
3732
 
 
3733
3543
class InterDifferingSerializer(InterRepository):
3734
3544
 
3735
3545
    @classmethod
3837
3647
                basis_id, delta, current_revision_id, parents_parents)
3838
3648
            cache[current_revision_id] = parent_tree
3839
3649
 
3840
 
    def _fetch_batch(self, revision_ids, basis_id, cache, a_graph=None):
 
3650
    def _fetch_batch(self, revision_ids, basis_id, cache):
3841
3651
        """Fetch across a few revisions.
3842
3652
 
3843
3653
        :param revision_ids: The revisions to copy
3844
3654
        :param basis_id: The revision_id of a tree that must be in cache, used
3845
3655
            as a basis for delta when no other base is available
3846
3656
        :param cache: A cache of RevisionTrees that we can use.
3847
 
        :param a_graph: A Graph object to determine the heads() of the
3848
 
            rich-root data stream.
3849
3657
        :return: The revision_id of the last converted tree. The RevisionTree
3850
3658
            for it will be in cache
3851
3659
        """
3919
3727
        if root_keys_to_create:
3920
3728
            root_stream = _mod_fetch._new_root_data_stream(
3921
3729
                root_keys_to_create, self._revision_id_to_root_id, parent_map,
3922
 
                self.source, graph=a_graph)
 
3730
                self.source)
3923
3731
            to_texts.insert_record_stream(root_stream)
3924
3732
        to_texts.insert_record_stream(from_texts.get_record_stream(
3925
3733
            text_keys, self.target._format._fetch_order,
3982
3790
        cache[basis_id] = basis_tree
3983
3791
        del basis_tree # We don't want to hang on to it here
3984
3792
        hints = []
3985
 
        if self._converting_to_rich_root and len(revision_ids) > 100:
3986
 
            a_graph = _mod_fetch._get_rich_root_heads_graph(self.source,
3987
 
                                                            revision_ids)
3988
 
        else:
3989
 
            a_graph = None
 
3793
        a_graph = None
3990
3794
 
3991
3795
        for offset in range(0, len(revision_ids), batch_size):
3992
3796
            self.target.start_write_group()
3994
3798
                pb.update('Transferring revisions', offset,
3995
3799
                          len(revision_ids))
3996
3800
                batch = revision_ids[offset:offset+batch_size]
3997
 
                basis_id = self._fetch_batch(batch, basis_id, cache,
3998
 
                                             a_graph=a_graph)
 
3801
                basis_id = self._fetch_batch(batch, basis_id, cache)
3999
3802
            except:
4000
3803
                self.source._safe_to_return_from_cache = False
4001
3804
                self.target.abort_write_group()
4010
3813
                  len(revision_ids))
4011
3814
 
4012
3815
    @needs_write_lock
4013
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
3816
    def fetch(self, revision_id=None, find_ghosts=False,
4014
3817
            fetch_spec=None):
4015
3818
        """See InterRepository.fetch()."""
4016
3819
        if fetch_spec is not None:
4017
 
            raise AssertionError("Not implemented yet...")
 
3820
            revision_ids = fetch_spec.get_keys()
 
3821
        else:
 
3822
            revision_ids = None
4018
3823
        ui.ui_factory.warn_experimental_format_fetch(self)
4019
3824
        if (not self.source.supports_rich_root()
4020
3825
            and self.target.supports_rich_root()):
4027
3832
            ui.ui_factory.show_user_warning('cross_format_fetch',
4028
3833
                from_format=self.source._format,
4029
3834
                to_format=self.target._format)
4030
 
        revision_ids = self.target.search_missing_revision_ids(self.source,
4031
 
            revision_id, find_ghosts=find_ghosts).get_keys()
 
3835
        if revision_ids is None:
 
3836
            if revision_id:
 
3837
                search_revision_ids = [revision_id]
 
3838
            else:
 
3839
                search_revision_ids = None
 
3840
            revision_ids = self.target.search_missing_revision_ids(self.source,
 
3841
                revision_ids=search_revision_ids,
 
3842
                find_ghosts=find_ghosts).get_keys()
4032
3843
        if not revision_ids:
4033
3844
            return 0, 0
4034
3845
        revision_ids = tsort.topo_sort(
4038
3849
        # Walk though all revisions; get inventory deltas, copy referenced
4039
3850
        # texts that delta references, insert the delta, revision and
4040
3851
        # signature.
4041
 
        if pb is None:
4042
 
            my_pb = ui.ui_factory.nested_progress_bar()
4043
 
            pb = my_pb
4044
 
        else:
4045
 
            symbol_versioning.warn(
4046
 
                symbol_versioning.deprecated_in((1, 14, 0))
4047
 
                % "pb parameter to fetch()")
4048
 
            my_pb = None
 
3852
        pb = ui.ui_factory.nested_progress_bar()
4049
3853
        try:
4050
3854
            self._fetch_all_revisions(revision_ids, pb)
4051
3855
        finally:
4052
 
            if my_pb is not None:
4053
 
                my_pb.finished()
 
3856
            pb.finished()
4054
3857
        return len(revision_ids), 0
4055
3858
 
4056
3859
    def _get_basis(self, first_revision_id):
4067
3870
            basis_id = first_rev.parent_ids[0]
4068
3871
            # only valid as a basis if the target has it
4069
3872
            self.target.get_revision(basis_id)
4070
 
            # Try to get a basis tree - if its a ghost it will hit the
 
3873
            # Try to get a basis tree - if it's a ghost it will hit the
4071
3874
            # NoSuchRevision case.
4072
3875
            basis_tree = self.source.revision_tree(basis_id)
4073
3876
        except (IndexError, errors.NoSuchRevision):
4078
3881
 
4079
3882
InterRepository.register_optimiser(InterDifferingSerializer)
4080
3883
InterRepository.register_optimiser(InterSameDataRepository)
4081
 
InterRepository.register_optimiser(InterWeaveRepo)
4082
 
InterRepository.register_optimiser(InterKnitRepo)
4083
3884
 
4084
3885
 
4085
3886
class CopyConverter(object):
4130
3931
        pb.finished()
4131
3932
 
4132
3933
 
4133
 
_unescape_map = {
4134
 
    'apos':"'",
4135
 
    'quot':'"',
4136
 
    'amp':'&',
4137
 
    'lt':'<',
4138
 
    'gt':'>'
4139
 
}
4140
 
 
4141
 
 
4142
 
def _unescaper(match, _map=_unescape_map):
4143
 
    code = match.group(1)
4144
 
    try:
4145
 
        return _map[code]
4146
 
    except KeyError:
4147
 
        if not code.startswith('#'):
4148
 
            raise
4149
 
        return unichr(int(code[1:])).encode('utf8')
4150
 
 
4151
 
 
4152
 
_unescape_re = None
4153
 
 
4154
 
 
4155
 
def _unescape_xml(data):
4156
 
    """Unescape predefined XML entities in a string of data."""
4157
 
    global _unescape_re
4158
 
    if _unescape_re is None:
4159
 
        _unescape_re = re.compile('\&([^;]*);')
4160
 
    return _unescape_re.sub(_unescaper, data)
4161
 
 
4162
 
 
4163
3934
class _VersionedFileChecker(object):
4164
3935
 
4165
3936
    def __init__(self, repository, text_key_references=None, ancestors=None):
4224
3995
        return wrong_parents, unused_keys
4225
3996
 
4226
3997
 
4227
 
def _old_get_graph(repository, revision_id):
4228
 
    """DO NOT USE. That is all. I'm serious."""
4229
 
    graph = repository.get_graph()
4230
 
    revision_graph = dict(((key, value) for key, value in
4231
 
        graph.iter_ancestry([revision_id]) if value is not None))
4232
 
    return _strip_NULL_ghosts(revision_graph)
4233
 
 
4234
 
 
4235
3998
def _strip_NULL_ghosts(revision_graph):
4236
3999
    """Also don't use this. more compatibility code for unmigrated clients."""
4237
4000
    # Filter ghosts, and null:
4273
4036
                is_resume = False
4274
4037
            try:
4275
4038
                # locked_insert_stream performs a commit|suspend.
4276
 
                return self._locked_insert_stream(stream, src_format, is_resume)
 
4039
                missing_keys = self.insert_stream_without_locking(stream,
 
4040
                                    src_format, is_resume)
 
4041
                if missing_keys:
 
4042
                    # suspend the write group and tell the caller what we is
 
4043
                    # missing. We know we can suspend or else we would not have
 
4044
                    # entered this code path. (All repositories that can handle
 
4045
                    # missing keys can handle suspending a write group).
 
4046
                    write_group_tokens = self.target_repo.suspend_write_group()
 
4047
                    return write_group_tokens, missing_keys
 
4048
                hint = self.target_repo.commit_write_group()
 
4049
                to_serializer = self.target_repo._format._serializer
 
4050
                src_serializer = src_format._serializer
 
4051
                if (to_serializer != src_serializer and
 
4052
                    self.target_repo._format.pack_compresses):
 
4053
                    self.target_repo.pack(hint=hint)
 
4054
                return [], set()
4277
4055
            except:
4278
4056
                self.target_repo.abort_write_group(suppress_errors=True)
4279
4057
                raise
4280
4058
        finally:
4281
4059
            self.target_repo.unlock()
4282
4060
 
4283
 
    def _locked_insert_stream(self, stream, src_format, is_resume):
 
4061
    def insert_stream_without_locking(self, stream, src_format,
 
4062
                                      is_resume=False):
 
4063
        """Insert a stream's content into the target repository.
 
4064
 
 
4065
        This assumes that you already have a locked repository and an active
 
4066
        write group.
 
4067
 
 
4068
        :param src_format: a bzr repository format.
 
4069
        :param is_resume: Passed down to get_missing_parent_inventories to
 
4070
            indicate if we should be checking for missing texts at the same
 
4071
            time.
 
4072
 
 
4073
        :return: A set of keys that are missing.
 
4074
        """
 
4075
        if not self.target_repo.is_write_locked():
 
4076
            raise errors.ObjectNotLocked(self)
 
4077
        if not self.target_repo.is_in_write_group():
 
4078
            raise errors.BzrError('you must already be in a write group')
4284
4079
        to_serializer = self.target_repo._format._serializer
4285
4080
        src_serializer = src_format._serializer
4286
4081
        new_pack = None
4326
4121
                # required if the serializers are different only in terms of
4327
4122
                # the inventory.
4328
4123
                if src_serializer == to_serializer:
4329
 
                    self.target_repo.revisions.insert_record_stream(
4330
 
                        substream)
 
4124
                    self.target_repo.revisions.insert_record_stream(substream)
4331
4125
                else:
4332
4126
                    self._extract_and_insert_revisions(substream,
4333
4127
                        src_serializer)
4366
4160
            # cannot even attempt suspending, and missing would have failed
4367
4161
            # during stream insertion.
4368
4162
            missing_keys = set()
4369
 
        else:
4370
 
            if missing_keys:
4371
 
                # suspend the write group and tell the caller what we is
4372
 
                # missing. We know we can suspend or else we would not have
4373
 
                # entered this code path. (All repositories that can handle
4374
 
                # missing keys can handle suspending a write group).
4375
 
                write_group_tokens = self.target_repo.suspend_write_group()
4376
 
                return write_group_tokens, missing_keys
4377
 
        hint = self.target_repo.commit_write_group()
4378
 
        if (to_serializer != src_serializer and
4379
 
            self.target_repo._format.pack_compresses):
4380
 
            self.target_repo.pack(hint=hint)
4381
 
        return [], set()
 
4163
        return missing_keys
4382
4164
 
4383
4165
    def _extract_and_insert_inventory_deltas(self, substream, serializer):
4384
4166
        target_rich_root = self.target_repo._format.rich_root_data
4441
4223
        """Create a StreamSource streaming from from_repository."""
4442
4224
        self.from_repository = from_repository
4443
4225
        self.to_format = to_format
 
4226
        self._record_counter = RecordCounter()
4444
4227
 
4445
4228
    def delta_on_metadata(self):
4446
4229
        """Return True if delta's are permitted on metadata streams.
4731
4514
    except StopIteration:
4732
4515
        # No more history
4733
4516
        return
4734