/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5590.1.6 by John Arbash Meinel
Found another tuned_gzip use in weaverepo
1
# Copyright (C) 2007-2011 Canonical Ltd
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
16
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
17
"""Deprecated weave-based repository formats.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
18
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
19
Weave based formats scaled linearly with history size and could not represent
20
ghosts.
21
"""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
22
5590.1.6 by John Arbash Meinel
Found another tuned_gzip use in weaverepo
23
import gzip
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
24
import os
25
from cStringIO import StringIO
26
import urllib
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
27
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
28
from bzrlib.lazy_import import lazy_import
29
lazy_import(globals(), """
5852.1.8 by Jelmer Vernooij
Simplify revision limiting.
30
import itertools
31
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
32
from bzrlib import (
5582.10.44 by Jelmer Vernooij
Clean up patch.
33
    xml5,
34
    graph as _mod_graph,
35
    ui,
36
    )
37
""")
38
from bzrlib import (
5582.10.24 by Jelmer Vernooij
Fix imports.
39
    debug,
5582.10.44 by Jelmer Vernooij
Clean up patch.
40
    errors,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
41
    lockable_files,
42
    lockdir,
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
43
    osutils,
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
44
    symbol_versioning,
5184.1.1 by Vincent Ladeuil
Random cleanups to catch up with copyright updates in trunk.
45
    trace,
5590.1.6 by John Arbash Meinel
Found another tuned_gzip use in weaverepo
46
    tuned_gzip,
3834.2.2 by Martin Pool
Deprecated LockableFiles._escape
47
    urlutils,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
48
    versionedfile,
5582.10.24 by Jelmer Vernooij
Fix imports.
49
    weave,
5582.10.44 by Jelmer Vernooij
Clean up patch.
50
    weavefile,
51
    )
52
from bzrlib.decorators import needs_read_lock, needs_write_lock
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
53
from bzrlib.repository import (
5537.2.1 by Jelmer Vernooij
Move InterWeaveRepo and InterKnitRepo to related repository files.
54
    InterRepository,
6349.2.1 by Jelmer Vernooij
Add BzrDirMetaComponentFormat.
55
    RepositoryFormatMetaDir,
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
56
    )
57
from bzrlib.store.text import TextStore
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
58
from bzrlib.versionedfile import (
59
    AbsentContentFactory,
60
    FulltextContentFactory,
61
    VersionedFiles,
62
    )
5815.4.2 by Jelmer Vernooij
split out versionedfile-specific stuff from commitbuilder.
63
from bzrlib.vf_repository import (
5815.4.19 by Jelmer Vernooij
Fix test failures.
64
    InterSameDataRepository,
5815.4.2 by Jelmer Vernooij
split out versionedfile-specific stuff from commitbuilder.
65
    VersionedFileCommitBuilder,
5815.4.14 by Jelmer Vernooij
Fix imports.
66
    VersionedFileRepository,
5815.4.5 by Jelmer Vernooij
Use MetaDirVersionedFileRepositoryFormat (a Soyuz worthy name).
67
    VersionedFileRepositoryFormat,
68
    MetaDirVersionedFileRepository,
69
    MetaDirVersionedFileRepositoryFormat,
5815.4.2 by Jelmer Vernooij
split out versionedfile-specific stuff from commitbuilder.
70
    )
5582.10.23 by Jelmer Vernooij
Move bzrlib.weavefile.
71
5582.10.44 by Jelmer Vernooij
Clean up patch.
72
from bzrlib.plugins.weave_fmt import bzrdir as weave_bzrdir
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
73
5582.10.23 by Jelmer Vernooij
Move bzrlib.weavefile.
74
5815.4.14 by Jelmer Vernooij
Fix imports.
75
class AllInOneRepository(VersionedFileRepository):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
76
    """Legacy support - the repository behaviour for all-in-one branches."""
77
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
78
    @property
79
    def _serializer(self):
80
        return xml5.serializer_v5
2241.1.8 by Martin Pool
Set the repository's serializer in the places it's needed, not in the base class
81
3834.2.2 by Martin Pool
Deprecated LockableFiles._escape
82
    def _escape(self, file_or_path):
83
        if not isinstance(file_or_path, basestring):
84
            file_or_path = '/'.join(file_or_path)
85
        if file_or_path == '':
86
            return u''
87
        return urlutils.escape(osutils.safe_unicode(file_or_path))
88
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
89
    def __init__(self, _format, a_bzrdir):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
90
        # we reuse one control files instance.
3416.2.3 by Martin Pool
typo
91
        dir_mode = a_bzrdir._get_dir_mode()
92
        file_mode = a_bzrdir._get_file_mode()
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
93
94
        def get_store(name, compressed=True, prefixed=False):
95
            # FIXME: This approach of assuming stores are all entirely compressed
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
96
            # or entirely uncompressed is tidy, but breaks upgrade from
97
            # some existing branches where there's a mixture; we probably
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
98
            # still want the option to look for both.
3834.2.2 by Martin Pool
Deprecated LockableFiles._escape
99
            relpath = self._escape(name)
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
100
            store = TextStore(a_bzrdir.transport.clone(relpath),
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
101
                              prefixed=prefixed, compressed=compressed,
102
                              dir_mode=dir_mode,
103
                              file_mode=file_mode)
104
            return store
105
106
        # not broken out yet because the controlweaves|inventory_store
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
107
        # and texts bits are still different.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
108
        if isinstance(_format, RepositoryFormat4):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
109
            # cannot remove these - there is still no consistent api
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
110
            # which allows access to this old info.
111
            self.inventory_store = get_store('inventory-store')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
112
            self._text_store = get_store('text-store')
113
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
114
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
115
    @needs_read_lock
116
    def _all_possible_ids(self):
117
        """Return all the possible revisions that we could find."""
118
        if 'evil' in debug.debug_flags:
5184.1.1 by Vincent Ladeuil
Random cleanups to catch up with copyright updates in trunk.
119
            trace.mutter_callsite(
120
                3, "_all_possible_ids scales with size of history.")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
121
        return [key[-1] for key in self.inventories.keys()]
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
122
123
    @needs_read_lock
124
    def _all_revision_ids(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
125
        """Returns a list of all the revision ids in the repository.
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
126
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
127
        These are in as much topological order as the underlying store can
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
128
        present: for weaves ghosts may lead to a lack of correctness until
129
        the reweave updates the parents list.
130
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
131
        return [key[-1] for key in self.revisions.keys()]
132
133
    def _activate_new_inventory(self):
134
        """Put a replacement inventory.new into use as inventories."""
135
        # Copy the content across
136
        t = self.bzrdir._control_files._transport
137
        t.copy('inventory.new.weave', 'inventory.weave')
138
        # delete the temp inventory
139
        t.delete('inventory.new.weave')
140
        # Check we can parse the new weave properly as a sanity check
141
        self.inventories.keys()
142
143
    def _backup_inventory(self):
144
        t = self.bzrdir._control_files._transport
145
        t.copy('inventory.weave', 'inventory.backup.weave')
146
147
    def _temp_inventories(self):
148
        t = self.bzrdir._control_files._transport
149
        return self._format._get_inventories(t, self, 'inventory.new')
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
150
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
151
    def get_commit_builder(self, branch, parents, config, timestamp=None,
152
                           timezone=None, committer=None, revprops=None,
5777.6.12 by Jelmer Vernooij
Fix get_commit_builder.
153
                           revision_id=None, lossy=False):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
154
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
5815.4.2 by Jelmer Vernooij
split out versionedfile-specific stuff from commitbuilder.
155
        result = VersionedFileCommitBuilder(self, parents, config, timestamp,
156
            timezone, committer, revprops, revision_id, lossy=lossy)
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
157
        self.start_write_group()
158
        return result
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
159
160
    @needs_read_lock
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
161
    def get_revisions(self, revision_ids):
162
        revs = self._get_revisions(revision_ids)
163
        return revs
164
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
165
    def _inventory_add_lines(self, revision_id, parents, lines,
166
        check_content=True):
167
        """Store lines in inv_vf and return the sha1 of the inventory."""
168
        present_parents = self.get_graph().get_parent_map(parents)
169
        final_parents = []
170
        for parent in parents:
171
            if parent in present_parents:
172
                final_parents.append((parent,))
173
        return self.inventories.add_lines((revision_id,), final_parents, lines,
174
            check_content=check_content)[0]
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
175
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
176
    def is_shared(self):
177
        """AllInOne repositories cannot be shared."""
178
        return False
179
180
    @needs_write_lock
181
    def set_make_working_trees(self, new_value):
182
        """Set the policy flag for making working trees when creating branches.
183
184
        This only applies to branches that use this repository.
185
186
        The default is 'True'.
187
        :param new_value: True to restore the default, False to disable making
188
                          working trees.
189
        """
5158.6.10 by Martin Pool
Update more code to use user_transport when it should
190
        raise errors.RepositoryUpgradeRequired(self.user_url)
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
191
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
192
    def make_working_trees(self):
193
        """Returns the policy for making working trees on new branches."""
194
        return True
195
196
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
197
class WeaveMetaDirRepository(MetaDirVersionedFileRepository):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
198
    """A subclass of MetaDirRepository to set weave specific policy."""
199
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
200
    def __init__(self, _format, a_bzrdir, control_files):
201
        super(WeaveMetaDirRepository, self).__init__(_format, a_bzrdir, control_files)
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
202
        self._serializer = _format._serializer
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
203
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
204
    @needs_read_lock
205
    def _all_possible_ids(self):
206
        """Return all the possible revisions that we could find."""
207
        if 'evil' in debug.debug_flags:
5184.1.1 by Vincent Ladeuil
Random cleanups to catch up with copyright updates in trunk.
208
            trace.mutter_callsite(
209
                3, "_all_possible_ids scales with size of history.")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
210
        return [key[-1] for key in self.inventories.keys()]
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
211
212
    @needs_read_lock
213
    def _all_revision_ids(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
214
        """Returns a list of all the revision ids in the repository.
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
215
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
216
        These are in as much topological order as the underlying store can
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
217
        present: for weaves ghosts may lead to a lack of correctness until
218
        the reweave updates the parents list.
219
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
220
        return [key[-1] for key in self.revisions.keys()]
221
222
    def _activate_new_inventory(self):
223
        """Put a replacement inventory.new into use as inventories."""
224
        # Copy the content across
225
        t = self._transport
226
        t.copy('inventory.new.weave', 'inventory.weave')
227
        # delete the temp inventory
228
        t.delete('inventory.new.weave')
229
        # Check we can parse the new weave properly as a sanity check
230
        self.inventories.keys()
231
232
    def _backup_inventory(self):
233
        t = self._transport
234
        t.copy('inventory.weave', 'inventory.backup.weave')
235
236
    def _temp_inventories(self):
237
        t = self._transport
238
        return self._format._get_inventories(t, self, 'inventory.new')
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
239
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
240
    def get_commit_builder(self, branch, parents, config, timestamp=None,
241
                           timezone=None, committer=None, revprops=None,
5777.6.13 by Jelmer Vernooij
Fix get_commit_builder for weaves.
242
                           revision_id=None, lossy=False):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
243
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
5815.4.2 by Jelmer Vernooij
split out versionedfile-specific stuff from commitbuilder.
244
        result = VersionedFileCommitBuilder(self, parents, config, timestamp,
245
            timezone, committer, revprops, revision_id, lossy=lossy)
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
246
        self.start_write_group()
247
        return result
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
248
2850.3.1 by Robert Collins
Move various weave specific code out of the base Repository class to weaverepo.py.
249
    @needs_read_lock
250
    def get_revision(self, revision_id):
251
        """Return the Revision object for a named revision"""
252
        r = self.get_revision_reconcile(revision_id)
253
        return r
254
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
255
    def _inventory_add_lines(self, revision_id, parents, lines,
256
        check_content=True):
257
        """Store lines in inv_vf and return the sha1 of the inventory."""
258
        present_parents = self.get_graph().get_parent_map(parents)
259
        final_parents = []
260
        for parent in parents:
261
            if parent in present_parents:
262
                final_parents.append((parent,))
263
        return self.inventories.add_lines((revision_id,), final_parents, lines,
264
            check_content=check_content)[0]
3172.3.1 by Robert Collins
Repository has a new method ``has_revisions`` which signals the presence
265
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
266
5815.4.5 by Jelmer Vernooij
Use MetaDirVersionedFileRepositoryFormat (a Soyuz worthy name).
267
class PreSplitOutRepositoryFormat(VersionedFileRepositoryFormat):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
268
    """Base class for the pre split out repository formats."""
269
270
    rich_root_data = False
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
271
    supports_tree_reference = False
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
272
    supports_ghosts = False
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
273
    supports_external_lookups = False
4246.2.1 by Ian Clatworthy
supports_chks flag on repo formats & log tuning
274
    supports_chks = False
6145.2.2 by Jelmer Vernooij
Set supports_nesting_repositories.
275
    supports_nesting_repositories = True
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
276
    _fetch_order = 'topological'
277
    _fetch_reconcile = True
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
278
    fast_deltas = False
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
279
    supports_leaving_lock = False
5766.1.1 by Jelmer Vernooij
Make revision-graph-can-have-wrong-parents a repository format attribute rather than a repository method.
280
    # XXX: This is an old format that we don't support full checking on, so
281
    # just claim that checking for this inconsistency is not required.
282
    revision_graph_can_have_wrong_parents = False
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
283
284
    def initialize(self, a_bzrdir, shared=False, _internal=False):
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
285
        """Create a weave repository."""
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
286
        if shared:
287
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
288
289
        if not _internal:
290
            # always initialized when the bzrdir is.
291
            return self.open(a_bzrdir, _found=True)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
292
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
293
        # Create an empty weave
294
        sio = StringIO()
5582.10.44 by Jelmer Vernooij
Clean up patch.
295
        weavefile.write_weave_v5(weave.Weave(), sio)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
296
        empty_weave = sio.getvalue()
297
5184.1.1 by Vincent Ladeuil
Random cleanups to catch up with copyright updates in trunk.
298
        trace.mutter('creating repository in %s.', a_bzrdir.transport.base)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
299
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
300
        # FIXME: RBC 20060125 don't peek under the covers
301
        # NB: no need to escape relative paths that are url safe.
302
        control_files = lockable_files.LockableFiles(a_bzrdir.transport,
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
303
            'branch-lock', lockable_files.TransportLock)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
304
        control_files.create_lock()
305
        control_files.lock_write()
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
306
        transport = a_bzrdir.transport
3407.2.4 by Martin Pool
Small cleanups to initial creation of repository files
307
        try:
308
            transport.mkdir_multi(['revision-store', 'weaves'],
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
309
                mode=a_bzrdir._get_dir_mode())
310
            transport.put_bytes_non_atomic('inventory.weave', empty_weave,
311
                mode=a_bzrdir._get_file_mode())
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
312
        finally:
313
            control_files.unlock()
5107.3.1 by Marco Pantaleoni
Added the new hooks 'post_branch', 'post_switch' and 'post_repo_init',
314
        repository = self.open(a_bzrdir, _found=True)
315
        self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
316
        return repository
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
317
318
    def open(self, a_bzrdir, _found=False):
319
        """See RepositoryFormat.open()."""
320
        if not _found:
321
            # we are being called directly and must probe.
322
            raise NotImplementedError
323
324
        repo_transport = a_bzrdir.get_repository_transport(None)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
325
        result = AllInOneRepository(_format=self, a_bzrdir=a_bzrdir)
326
        result.revisions = self._get_revisions(repo_transport, result)
327
        result.signatures = self._get_signatures(repo_transport, result)
328
        result.inventories = self._get_inventories(repo_transport, result)
329
        result.texts = self._get_texts(repo_transport, result)
4246.2.1 by Ian Clatworthy
supports_chks flag on repo formats & log tuning
330
        result.chk_bytes = None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
331
        return result
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
332
5675.2.1 by Jelmer Vernooij
Add RepositoryFormat.is_deprecated(). This removes the need for
333
    def is_deprecated(self):
334
        return True
335
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
336
337
class RepositoryFormat4(PreSplitOutRepositoryFormat):
338
    """Bzr repository format 4.
339
340
    This repository format has:
341
     - flat stores
342
     - TextStores for texts, inventories,revisions.
343
344
    This format is deprecated: it indexes texts using a text id which is
345
    removed in format 5; initialization and write support for this format
346
    has been removed.
347
    """
348
5582.9.1 by Jelmer Vernooij
Add flag for 'supports_funky_characters'.
349
    supports_funky_characters = False
350
5582.10.44 by Jelmer Vernooij
Clean up patch.
351
    _matchingbzrdir = weave_bzrdir.BzrDirFormat4()
2241.1.11 by Martin Pool
Get rid of RepositoryFormat*_instance objects. Instead the format
352
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
353
    def get_format_description(self):
354
        """See RepositoryFormat.get_format_description()."""
355
        return "Repository format 4"
356
357
    def initialize(self, url, shared=False, _internal=False):
358
        """Format 4 branches cannot be created."""
359
        raise errors.UninitializableFormat(self)
360
361
    def is_supported(self):
362
        """Format 4 is not supported.
363
364
        It is not supported because the model changed from 4 to 5 and the
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
365
        conversion logic is expensive - so doing it on the fly was not
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
366
        feasible.
367
        """
368
        return False
369
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
370
    def _get_inventories(self, repo_transport, repo, name='inventory'):
371
        # No inventories store written so far.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
372
        return None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
373
374
    def _get_revisions(self, repo_transport, repo):
5582.10.56 by Jelmer Vernooij
move xml4 to weave plugin.
375
        from bzrlib.plugins.weave_fmt.xml4 import serializer_v4
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
376
        return RevisionTextStore(repo_transport.clone('revision-store'),
377
            serializer_v4, True, versionedfile.PrefixMapper(),
378
            repo.is_locked, repo.is_write_locked)
379
380
    def _get_signatures(self, repo_transport, repo):
381
        return SignatureTextStore(repo_transport.clone('revision-store'),
382
            False, versionedfile.PrefixMapper(),
383
            repo.is_locked, repo.is_write_locked)
384
385
    def _get_texts(self, repo_transport, repo):
386
        return None
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
387
388
389
class RepositoryFormat5(PreSplitOutRepositoryFormat):
390
    """Bzr control format 5.
391
392
    This repository format has:
393
     - weaves for file texts and inventory
394
     - flat stores
395
     - TextStores for revisions and signatures.
396
    """
397
5582.10.42 by Jelmer Vernooij
Some weave fixes.
398
    _versionedfile_class = weave.WeaveFile
5582.10.44 by Jelmer Vernooij
Clean up patch.
399
    _matchingbzrdir = weave_bzrdir.BzrDirFormat5()
5582.9.1 by Jelmer Vernooij
Add flag for 'supports_funky_characters'.
400
    supports_funky_characters = False
401
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
402
    @property
403
    def _serializer(self):
404
        return xml5.serializer_v5
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
405
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
406
    def get_format_description(self):
407
        """See RepositoryFormat.get_format_description()."""
408
        return "Weave repository format 5"
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
409
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
410
    def network_name(self):
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
411
        """The network name for this format is the control dirs disk label."""
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
412
        return self._matchingbzrdir.get_format_string()
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
413
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
414
    def _get_inventories(self, repo_transport, repo, name='inventory'):
415
        mapper = versionedfile.ConstantMapper(name)
416
        return versionedfile.ThunkedVersionedFiles(repo_transport,
5582.10.42 by Jelmer Vernooij
Some weave fixes.
417
            weave.WeaveFile, mapper, repo.is_locked)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
418
419
    def _get_revisions(self, repo_transport, repo):
420
        return RevisionTextStore(repo_transport.clone('revision-store'),
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
421
            xml5.serializer_v5, False, versionedfile.PrefixMapper(),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
422
            repo.is_locked, repo.is_write_locked)
423
424
    def _get_signatures(self, repo_transport, repo):
425
        return SignatureTextStore(repo_transport.clone('revision-store'),
426
            False, versionedfile.PrefixMapper(),
427
            repo.is_locked, repo.is_write_locked)
428
429
    def _get_texts(self, repo_transport, repo):
430
        mapper = versionedfile.PrefixMapper()
431
        base_transport = repo_transport.clone('weaves')
432
        return versionedfile.ThunkedVersionedFiles(base_transport,
5582.10.42 by Jelmer Vernooij
Some weave fixes.
433
            weave.WeaveFile, mapper, repo.is_locked)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
434
435
436
class RepositoryFormat6(PreSplitOutRepositoryFormat):
437
    """Bzr control format 6.
438
439
    This repository format has:
440
     - weaves for file texts and inventory
441
     - hash subdirectory based stores.
442
     - TextStores for revisions and signatures.
443
    """
444
5582.10.42 by Jelmer Vernooij
Some weave fixes.
445
    _versionedfile_class = weave.WeaveFile
5582.10.44 by Jelmer Vernooij
Clean up patch.
446
    _matchingbzrdir = weave_bzrdir.BzrDirFormat6()
5582.9.1 by Jelmer Vernooij
Add flag for 'supports_funky_characters'.
447
    supports_funky_characters = False
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
448
    @property
449
    def _serializer(self):
450
        return xml5.serializer_v5
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
451
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
452
    def get_format_description(self):
453
        """See RepositoryFormat.get_format_description()."""
454
        return "Weave repository format 6"
455
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
456
    def network_name(self):
3990.5.3 by Robert Collins
Docs and polish on RepositoryFormat.network_name.
457
        """The network name for this format is the control dirs disk label."""
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
458
        return self._matchingbzrdir.get_format_string()
459
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
460
    def _get_inventories(self, repo_transport, repo, name='inventory'):
461
        mapper = versionedfile.ConstantMapper(name)
462
        return versionedfile.ThunkedVersionedFiles(repo_transport,
5582.10.42 by Jelmer Vernooij
Some weave fixes.
463
            weave.WeaveFile, mapper, repo.is_locked)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
464
465
    def _get_revisions(self, repo_transport, repo):
466
        return RevisionTextStore(repo_transport.clone('revision-store'),
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
467
            xml5.serializer_v5, False, versionedfile.HashPrefixMapper(),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
468
            repo.is_locked, repo.is_write_locked)
469
470
    def _get_signatures(self, repo_transport, repo):
471
        return SignatureTextStore(repo_transport.clone('revision-store'),
472
            False, versionedfile.HashPrefixMapper(),
473
            repo.is_locked, repo.is_write_locked)
474
475
    def _get_texts(self, repo_transport, repo):
476
        mapper = versionedfile.HashPrefixMapper()
477
        base_transport = repo_transport.clone('weaves')
478
        return versionedfile.ThunkedVersionedFiles(base_transport,
5582.10.42 by Jelmer Vernooij
Some weave fixes.
479
            weave.WeaveFile, mapper, repo.is_locked)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
480
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
481
5815.4.5 by Jelmer Vernooij
Use MetaDirVersionedFileRepositoryFormat (a Soyuz worthy name).
482
class RepositoryFormat7(MetaDirVersionedFileRepositoryFormat):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
483
    """Bzr repository 7.
484
485
    This repository format has:
486
     - weaves for file texts and inventory
487
     - hash subdirectory based stores.
488
     - TextStores for revisions and signatures.
489
     - a format marker of its own
490
     - an optional 'shared-storage' flag
491
     - an optional 'no-working-trees' flag
492
    """
493
5582.10.42 by Jelmer Vernooij
Some weave fixes.
494
    _versionedfile_class = weave.WeaveFile
2949.1.2 by Robert Collins
* Fetch with pack repositories will no longer read the entire history graph.
495
    supports_ghosts = False
4246.2.1 by Ian Clatworthy
supports_chks flag on repo formats & log tuning
496
    supports_chks = False
5609.4.1 by Jelmer Vernooij
Mark RepositoryFormat7 as not supporting funky character file names. This should fix the tests on Windows.
497
    supports_funky_characters = False
5766.1.4 by Jelmer Vernooij
Set revision_graph_can_have_wrong_parents on RepositoryFormat7.
498
    revision_graph_can_have_wrong_parents = False
4246.2.1 by Ian Clatworthy
supports_chks flag on repo formats & log tuning
499
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
500
    _fetch_order = 'topological'
501
    _fetch_reconcile = True
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
502
    fast_deltas = False
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
503
    @property
504
    def _serializer(self):
505
        return xml5.serializer_v5
2241.1.10 by Martin Pool
Remove more references to weaves from the repository.py file
506
6349.2.1 by Jelmer Vernooij
Add BzrDirMetaComponentFormat.
507
    @classmethod
508
    def get_format_string(cls):
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
509
        """See RepositoryFormat.get_format_string()."""
510
        return "Bazaar-NG Repository format 7"
511
512
    def get_format_description(self):
513
        """See RepositoryFormat.get_format_description()."""
514
        return "Weave repository format 7"
515
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
516
    def _get_inventories(self, repo_transport, repo, name='inventory'):
517
        mapper = versionedfile.ConstantMapper(name)
518
        return versionedfile.ThunkedVersionedFiles(repo_transport,
5582.10.42 by Jelmer Vernooij
Some weave fixes.
519
            weave.WeaveFile, mapper, repo.is_locked)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
520
521
    def _get_revisions(self, repo_transport, repo):
522
        return RevisionTextStore(repo_transport.clone('revision-store'),
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
523
            xml5.serializer_v5, True, versionedfile.HashPrefixMapper(),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
524
            repo.is_locked, repo.is_write_locked)
525
526
    def _get_signatures(self, repo_transport, repo):
527
        return SignatureTextStore(repo_transport.clone('revision-store'),
528
            True, versionedfile.HashPrefixMapper(),
529
            repo.is_locked, repo.is_write_locked)
530
531
    def _get_texts(self, repo_transport, repo):
532
        mapper = versionedfile.HashPrefixMapper()
533
        base_transport = repo_transport.clone('weaves')
534
        return versionedfile.ThunkedVersionedFiles(base_transport,
5582.10.42 by Jelmer Vernooij
Some weave fixes.
535
            weave.WeaveFile, mapper, repo.is_locked)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
536
537
    def initialize(self, a_bzrdir, shared=False):
538
        """Create a weave repository.
539
540
        :param shared: If true the repository will be initialized as a shared
541
                       repository.
542
        """
543
        # Create an empty weave
544
        sio = StringIO()
5582.10.44 by Jelmer Vernooij
Clean up patch.
545
        weavefile.write_weave_v5(weave.Weave(), sio)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
546
        empty_weave = sio.getvalue()
547
5184.1.1 by Vincent Ladeuil
Random cleanups to catch up with copyright updates in trunk.
548
        trace.mutter('creating repository in %s.', a_bzrdir.transport.base)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
549
        dirs = ['revision-store', 'weaves']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
550
        files = [('inventory.weave', StringIO(empty_weave)),
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
551
                 ]
552
        utf8_files = [('format', self.get_format_string())]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
553
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
554
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
555
        return self.open(a_bzrdir=a_bzrdir, _found=True)
556
557
    def open(self, a_bzrdir, _found=False, _override_transport=None):
558
        """See RepositoryFormat.open().
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
559
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
560
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
561
                                    repository at a slightly different url
562
                                    than normal. I.e. during 'upgrade'.
563
        """
564
        if not _found:
6349.2.1 by Jelmer Vernooij
Add BzrDirMetaComponentFormat.
565
            format = RepositoryFormatMetaDir.find_format(a_bzrdir)
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
566
        if _override_transport is not None:
567
            repo_transport = _override_transport
568
        else:
569
            repo_transport = a_bzrdir.get_repository_transport(None)
570
        control_files = lockable_files.LockableFiles(repo_transport,
571
                                'lock', lockdir.LockDir)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
572
        result = WeaveMetaDirRepository(_format=self, a_bzrdir=a_bzrdir,
573
            control_files=control_files)
574
        result.revisions = self._get_revisions(repo_transport, result)
575
        result.signatures = self._get_signatures(repo_transport, result)
576
        result.inventories = self._get_inventories(repo_transport, result)
577
        result.texts = self._get_texts(repo_transport, result)
4246.2.1 by Ian Clatworthy
supports_chks flag on repo formats & log tuning
578
        result.chk_bytes = None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
579
        result._transport = repo_transport
580
        return result
581
5675.2.1 by Jelmer Vernooij
Add RepositoryFormat.is_deprecated(). This removes the need for
582
    def is_deprecated(self):
583
        return True
584
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
585
586
class TextVersionedFiles(VersionedFiles):
587
    """Just-a-bunch-of-files based VersionedFile stores."""
588
589
    def __init__(self, transport, compressed, mapper, is_locked, can_write):
590
        self._compressed = compressed
591
        self._transport = transport
592
        self._mapper = mapper
593
        if self._compressed:
594
            self._ext = '.gz'
595
        else:
596
            self._ext = ''
597
        self._is_locked = is_locked
598
        self._can_write = can_write
599
600
    def add_lines(self, key, parents, lines):
601
        """Add a revision to the store."""
602
        if not self._is_locked():
603
            raise errors.ObjectNotLocked(self)
604
        if not self._can_write():
605
            raise errors.ReadOnlyError(self)
606
        if '/' in key[-1]:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
607
            raise ValueError('bad idea to put / in %r' % (key,))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
608
        text = ''.join(lines)
609
        if self._compressed:
5590.1.6 by John Arbash Meinel
Found another tuned_gzip use in weaverepo
610
            text = tuned_gzip.bytes_to_gzip(text)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
611
        path = self._map(key)
612
        self._transport.put_bytes_non_atomic(path, text, create_parent_dir=True)
613
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
614
    def insert_record_stream(self, stream):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
615
        adapters = {}
616
        for record in stream:
617
            # Raise an error when a record is missing.
618
            if record.storage_kind == 'absent':
619
                raise errors.RevisionNotPresent([record.key[0]], self)
620
            # adapt to non-tuple interface
621
            if record.storage_kind == 'fulltext':
622
                self.add_lines(record.key, None,
623
                    osutils.split_lines(record.get_bytes_as('fulltext')))
624
            else:
625
                adapter_key = record.storage_kind, 'fulltext'
626
                try:
627
                    adapter = adapters[adapter_key]
628
                except KeyError:
629
                    adapter_factory = adapter_registry.get(adapter_key)
630
                    adapter = adapter_factory(self)
631
                    adapters[adapter_key] = adapter
632
                lines = osutils.split_lines(adapter.get_bytes(
633
                    record, record.get_bytes_as(record.storage_kind)))
634
                try:
635
                    self.add_lines(record.key, None, lines)
5815.4.17 by Jelmer Vernooij
Remove unused test method.
636
                except errors.RevisionAlreadyPresent:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
637
                    pass
638
639
    def _load_text(self, key):
640
        if not self._is_locked():
641
            raise errors.ObjectNotLocked(self)
642
        path = self._map(key)
643
        try:
644
            text = self._transport.get_bytes(path)
645
            compressed = self._compressed
646
        except errors.NoSuchFile:
647
            if self._compressed:
648
                # try without the .gz
649
                path = path[:-3]
650
                try:
651
                    text = self._transport.get_bytes(path)
652
                    compressed = False
653
                except errors.NoSuchFile:
654
                    return None
655
            else:
656
                return None
657
        if compressed:
5590.1.6 by John Arbash Meinel
Found another tuned_gzip use in weaverepo
658
            text = gzip.GzipFile(mode='rb', fileobj=StringIO(text)).read()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
659
        return text
660
661
    def _map(self, key):
662
        return self._mapper.map(key) + self._ext
663
664
665
class RevisionTextStore(TextVersionedFiles):
666
    """Legacy thunk for format 4 repositories."""
667
668
    def __init__(self, transport, serializer, compressed, mapper, is_locked,
669
        can_write):
670
        """Create a RevisionTextStore at transport with serializer."""
671
        TextVersionedFiles.__init__(self, transport, compressed, mapper,
672
            is_locked, can_write)
673
        self._serializer = serializer
674
675
    def _load_text_parents(self, key):
676
        text = self._load_text(key)
677
        if text is None:
678
            return None, None
679
        parents = self._serializer.read_revision_from_string(text).parent_ids
680
        return text, tuple((parent,) for parent in parents)
681
682
    def get_parent_map(self, keys):
683
        result = {}
684
        for key in keys:
685
            parents = self._load_text_parents(key)[1]
686
            if parents is None:
687
                continue
688
            result[key] = parents
689
        return result
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
690
4593.5.34 by John Arbash Meinel
Change the KnownGraph.merge_sort api.
691
    def get_known_graph_ancestry(self, keys):
692
        """Get a KnownGraph instance with the ancestry of keys."""
693
        keys = self.keys()
694
        parent_map = self.get_parent_map(keys)
695
        kg = _mod_graph.KnownGraph(parent_map)
696
        return kg
697
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
698
    def get_record_stream(self, keys, sort_order, include_delta_closure):
699
        for key in keys:
700
            text, parents = self._load_text_parents(key)
701
            if text is None:
702
                yield AbsentContentFactory(key)
703
            else:
704
                yield FulltextContentFactory(key, parents, None, text)
705
706
    def keys(self):
707
        if not self._is_locked():
708
            raise errors.ObjectNotLocked(self)
709
        relpaths = set()
710
        for quoted_relpath in self._transport.iter_files_recursive():
711
            relpath = urllib.unquote(quoted_relpath)
712
            path, ext = os.path.splitext(relpath)
713
            if ext == '.gz':
714
                relpath = path
4695.2.1 by Vincent Ladeuil
Align RevisionTextStore and SignatureTextStore keys() definitions.
715
            if not relpath.endswith('.sig'):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
716
                relpaths.add(relpath)
717
        paths = list(relpaths)
718
        return set([self._mapper.unmap(path) for path in paths])
719
720
721
class SignatureTextStore(TextVersionedFiles):
722
    """Legacy thunk for format 4-7 repositories."""
723
724
    def __init__(self, transport, compressed, mapper, is_locked, can_write):
725
        TextVersionedFiles.__init__(self, transport, compressed, mapper,
726
            is_locked, can_write)
727
        self._ext = '.sig' + self._ext
728
729
    def get_parent_map(self, keys):
730
        result = {}
731
        for key in keys:
732
            text = self._load_text(key)
733
            if text is None:
734
                continue
735
            result[key] = None
736
        return result
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
737
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
738
    def get_record_stream(self, keys, sort_order, include_delta_closure):
739
        for key in keys:
740
            text = self._load_text(key)
741
            if text is None:
742
                yield AbsentContentFactory(key)
743
            else:
744
                yield FulltextContentFactory(key, None, None, text)
745
746
    def keys(self):
747
        if not self._is_locked():
748
            raise errors.ObjectNotLocked(self)
749
        relpaths = set()
750
        for quoted_relpath in self._transport.iter_files_recursive():
751
            relpath = urllib.unquote(quoted_relpath)
752
            path, ext = os.path.splitext(relpath)
753
            if ext == '.gz':
754
                relpath = path
755
            if not relpath.endswith('.sig'):
756
                continue
757
            relpaths.add(relpath[:-4])
758
        paths = list(relpaths)
759
        return set([self._mapper.unmap(path) for path in paths])
2803.2.1 by Robert Collins
* CommitBuilder now advertises itself as requiring the root entry to be
760
5537.2.1 by Jelmer Vernooij
Move InterWeaveRepo and InterKnitRepo to related repository files.
761
762
class InterWeaveRepo(InterSameDataRepository):
763
    """Optimised code paths between Weave based repositories.
764
    """
765
766
    @classmethod
767
    def _get_repo_format_to_test(self):
768
        return RepositoryFormat7()
769
770
    @staticmethod
771
    def is_compatible(source, target):
772
        """Be compatible with known Weave formats.
773
774
        We don't test for the stores being of specific types because that
775
        could lead to confusing results, and there is no need to be
776
        overly general.
777
        """
778
        try:
779
            return (isinstance(source._format, (RepositoryFormat5,
780
                                                RepositoryFormat6,
781
                                                RepositoryFormat7)) and
782
                    isinstance(target._format, (RepositoryFormat5,
783
                                                RepositoryFormat6,
784
                                                RepositoryFormat7)))
785
        except AttributeError:
786
            return False
787
788
    @needs_write_lock
789
    def copy_content(self, revision_id=None):
790
        """See InterRepository.copy_content()."""
791
        # weave specific optimised path:
792
        try:
793
            self.target.set_make_working_trees(self.source.make_working_trees())
794
        except (errors.RepositoryUpgradeRequired, NotImplemented):
795
            pass
796
        # FIXME do not peek!
797
        if self.source._transport.listable():
798
            pb = ui.ui_factory.nested_progress_bar()
799
            try:
800
                self.target.texts.insert_record_stream(
801
                    self.source.texts.get_record_stream(
802
                        self.source.texts.keys(), 'topological', False))
803
                pb.update('Copying inventory', 0, 1)
804
                self.target.inventories.insert_record_stream(
805
                    self.source.inventories.get_record_stream(
806
                        self.source.inventories.keys(), 'topological', False))
807
                self.target.signatures.insert_record_stream(
808
                    self.source.signatures.get_record_stream(
809
                        self.source.signatures.keys(),
810
                        'unordered', True))
811
                self.target.revisions.insert_record_stream(
812
                    self.source.revisions.get_record_stream(
813
                        self.source.revisions.keys(),
814
                        'topological', True))
815
            finally:
816
                pb.finished()
817
        else:
818
            self.target.fetch(self.source, revision_id=revision_id)
819
820
    @needs_read_lock
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
821
    def search_missing_revision_ids(self,
822
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
5852.1.6 by Jelmer Vernooij
Add extra test for Repository.search_missing_revision_ids.
823
            find_ghosts=True, revision_ids=None, if_present_ids=None,
824
            limit=None):
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
825
        """See InterRepository.search_missing_revision_ids()."""
5537.2.1 by Jelmer Vernooij
Move InterWeaveRepo and InterKnitRepo to related repository files.
826
        # we want all revisions to satisfy revision_id in source.
827
        # but we don't want to stat every file here and there.
828
        # we want then, all revisions other needs to satisfy revision_id
829
        # checked, but not those that we have locally.
830
        # so the first thing is to get a subset of the revisions to
831
        # satisfy revision_id in source, and then eliminate those that
832
        # we do already have.
833
        # this is slow on high latency connection to self, but as this
834
        # disk format scales terribly for push anyway due to rewriting
835
        # inventory.weave, this is considered acceptable.
836
        # - RBC 20060209
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
837
        if symbol_versioning.deprecated_passed(revision_id):
838
            symbol_versioning.warn(
839
                'search_missing_revision_ids(revision_id=...) was '
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
840
                'deprecated in 2.4.  Use revision_ids=[...] instead.',
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
841
                DeprecationWarning, stacklevel=2)
842
            if revision_ids is not None:
843
                raise AssertionError(
844
                    'revision_ids is mutually exclusive with revision_id')
845
            if revision_id is not None:
846
                revision_ids = [revision_id]
847
        del revision_id
5535.3.32 by Andrew Bennetts
Implement if_present_ids behaviour in all implementations and code paths of searching_missing_revision_ids
848
        source_ids_set = self._present_source_revisions_for(
849
            revision_ids, if_present_ids)
5537.2.1 by Jelmer Vernooij
Move InterWeaveRepo and InterKnitRepo to related repository files.
850
        # source_ids is the worst possible case we may need to pull.
851
        # now we want to filter source_ids against what we actually
852
        # have in target, but don't try to check for existence where we know
853
        # we do not have a revision as that would be pointless.
854
        target_ids = set(self.target._all_possible_ids())
855
        possibly_present_revisions = target_ids.intersection(source_ids_set)
856
        actually_present_revisions = set(
857
            self.target._eliminate_revisions_not_present(possibly_present_revisions))
858
        required_revisions = source_ids_set.difference(actually_present_revisions)
5539.2.10 by Andrew Bennetts
s/NotInOtherForRev/NotInOtherForRevs/, and allow passing multiple revision_ids to search_missing_revision_ids.
859
        if revision_ids is not None:
5537.2.1 by Jelmer Vernooij
Move InterWeaveRepo and InterKnitRepo to related repository files.
860
            # we used get_ancestry to determine source_ids then we are assured all
861
            # revisions referenced are present as they are installed in topological order.
862
            # and the tip revision was validated by get_ancestry.
863
            result_set = required_revisions
864
        else:
865
            # if we just grabbed the possibly available ids, then
866
            # we only have an estimate of whats available and need to validate
867
            # that against the revision records.
868
            result_set = set(
869
                self.source._eliminate_revisions_not_present(required_revisions))
5852.1.6 by Jelmer Vernooij
Add extra test for Repository.search_missing_revision_ids.
870
        if limit is not None:
5852.1.8 by Jelmer Vernooij
Simplify revision limiting.
871
            topo_ordered = self.get_graph().iter_topo_order(result_set)
872
            result_set = set(itertools.islice(topo_ordered, limit))
5537.2.1 by Jelmer Vernooij
Move InterWeaveRepo and InterKnitRepo to related repository files.
873
        return self.source.revision_ids_to_search_result(result_set)
874
875
876
InterRepository.register_optimiser(InterWeaveRepo)
5676.1.9 by Jelmer Vernooij
Fix existing implementation.
877
878
879
def get_extra_interrepo_test_combinations():
880
    from bzrlib.repofmt import knitrepo
881
    return [(InterRepository, RepositoryFormat5(),
882
        knitrepo.RepositoryFormatKnit3())]