/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3376.2.12 by Martin Pool
pyflakes corrections (thanks spiv)
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
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
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
16
4002.1.5 by Andrew Bennetts
Fix possible security issue with resuming write groups: make sure the token is well-formed so that it's not possible to steal a write group from another repo.
17
import re
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
18
import sys
19
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
22
from itertools import izip
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
23
import time
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
24
25
from bzrlib import (
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
26
    chk_map,
3603.2.1 by Andrew Bennetts
Remove duplicated class definitions, remove unused imports.
27
    debug,
28
    graph,
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
29
    osutils,
3603.2.1 by Andrew Bennetts
Remove duplicated class definitions, remove unused imports.
30
    pack,
31
    transactions,
32
    ui,
3224.5.16 by Andrew Bennetts
Merge from bzr.dev.
33
    xml5,
34
    xml6,
35
    xml7,
3603.2.1 by Andrew Bennetts
Remove duplicated class definitions, remove unused imports.
36
    )
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
37
from bzrlib.index import (
2929.3.5 by Vincent Ladeuil
New files, same warnings, same fixes.
38
    CombinedGraphIndex,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
39
    GraphIndex,
40
    GraphIndexBuilder,
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
41
    GraphIndexPrefixAdapter,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
42
    InMemoryGraphIndex,
43
    )
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.
44
from bzrlib.knit import (
45
    KnitPlainFactory,
46
    KnitVersionedFiles,
47
    _KnitGraphIndex,
48
    _DirectPackAccess,
49
    )
3063.2.1 by Robert Collins
Solve reconciling erroring when multiple portions of a single delta chain are being reinserted.
50
from bzrlib import tsort
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
51
""")
52
from bzrlib import (
53
    bzrdir,
54
    errors,
55
    lockable_files,
56
    lockdir,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
57
    revision as _mod_revision,
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
58
    symbol_versioning,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
59
    )
60
3603.2.1 by Andrew Bennetts
Remove duplicated class definitions, remove unused imports.
61
from bzrlib.decorators import needs_write_lock
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
62
from bzrlib.btree_index import (
63
    BTreeGraphIndex,
64
    BTreeBuilder,
65
    )
66
from bzrlib.index import (
67
    GraphIndex,
68
    InMemoryGraphIndex,
69
    )
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
70
from bzrlib.repofmt.knitrepo import KnitRepository
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
71
from bzrlib.repository import (
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
72
    CommitBuilder,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
73
    MetaDirRepositoryFormat,
3376.2.12 by Martin Pool
pyflakes corrections (thanks spiv)
74
    RepositoryFormat,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
75
    RootCommitBuilder,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
76
    )
77
import bzrlib.revision as _mod_revision
3376.2.12 by Martin Pool
pyflakes corrections (thanks spiv)
78
from bzrlib.trace import (
79
    mutter,
80
    warning,
81
    )
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
82
83
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
84
class PackCommitBuilder(CommitBuilder):
85
    """A subclass of CommitBuilder to add texts with pack semantics.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
86
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
87
    Specifically this uses one knit object rather than one knit object per
88
    added text, reducing memory and object pressure.
89
    """
90
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
91
    def __init__(self, repository, parents, config, timestamp=None,
92
                 timezone=None, committer=None, revprops=None,
93
                 revision_id=None):
94
        CommitBuilder.__init__(self, repository, parents, config,
95
            timestamp=timestamp, timezone=timezone, committer=committer,
96
            revprops=revprops, revision_id=revision_id)
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
97
        self._file_graph = graph.Graph(
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
98
            repository._pack_collection.text_index.combined_index)
99
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
100
    def _heads(self, file_id, revision_ids):
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
101
        keys = [(file_id, revision_id) for revision_id in revision_ids]
102
        return set([key[1] for key in self._file_graph.heads(keys)])
103
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
104
105
class PackRootCommitBuilder(RootCommitBuilder):
106
    """A subclass of RootCommitBuilder to add texts with pack semantics.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
107
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
108
    Specifically this uses one knit object rather than one knit object per
109
    added text, reducing memory and object pressure.
110
    """
111
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
112
    def __init__(self, repository, parents, config, timestamp=None,
113
                 timezone=None, committer=None, revprops=None,
114
                 revision_id=None):
115
        CommitBuilder.__init__(self, repository, parents, config,
116
            timestamp=timestamp, timezone=timezone, committer=committer,
117
            revprops=revprops, revision_id=revision_id)
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
118
        self._file_graph = graph.Graph(
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
119
            repository._pack_collection.text_index.combined_index)
120
2979.2.5 by Robert Collins
Make CommitBuilder.heads be _heads as its internal to CommitBuilder only.
121
    def _heads(self, file_id, revision_ids):
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
122
        keys = [(file_id, revision_id) for revision_id in revision_ids]
123
        return set([key[1] for key in self._file_graph.heads(keys)])
124
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
125
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
126
class Pack(object):
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
127
    """An in memory proxy for a pack and its indices.
128
129
    This is a base class that is not directly used, instead the classes
130
    ExistingPack and NewPack are used.
131
    """
132
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
133
    # A map of index 'type' to the file extension and position in the
134
    # index_sizes array.
135
    index_definitions = {
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
136
        'chk': ('.cix', 4),
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
137
        'revision': ('.rix', 0),
138
        'inventory': ('.iix', 1),
139
        'text': ('.tix', 2),
140
        'signature': ('.six', 3),
141
        }
142
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
143
    def __init__(self, revision_index, inventory_index, text_index,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
144
        signature_index, chk_index=None):
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
145
        """Create a pack instance.
146
147
        :param revision_index: A GraphIndex for determining what revisions are
148
            present in the Pack and accessing the locations of their texts.
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
149
        :param inventory_index: A GraphIndex for determining what inventories are
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
150
            present in the Pack and accessing the locations of their
151
            texts/deltas.
152
        :param text_index: A GraphIndex for determining what file texts
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
153
            are present in the pack and accessing the locations of their
154
            texts/deltas (via (fileid, revisionid) tuples).
3495.3.1 by Martin Pool
doc correction from SuperMMX
155
        :param signature_index: A GraphIndex for determining what signatures are
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
156
            present in the Pack and accessing the locations of their texts.
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
157
        :param chk_index: A GraphIndex for accessing content by CHK, if the
158
            pack has one.
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
159
        """
160
        self.revision_index = revision_index
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
161
        self.inventory_index = inventory_index
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
162
        self.text_index = text_index
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
163
        self.signature_index = signature_index
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
164
        self.chk_index = chk_index
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
165
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
166
    def access_tuple(self):
167
        """Return a tuple (transport, name) for the pack content."""
168
        return self.pack_transport, self.file_name()
169
4002.1.12 by Andrew Bennetts
Add another test, fix the code so it passes, and remove some cruft.
170
    def _check_references(self):
171
        """Make sure our external references are present.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
172
4002.1.12 by Andrew Bennetts
Add another test, fix the code so it passes, and remove some cruft.
173
        Packs are allowed to have deltas whose base is not in the pack, but it
174
        must be present somewhere in this collection.  It is not allowed to
175
        have deltas based on a fallback repository.
176
        (See <https://bugs.launchpad.net/bzr/+bug/288751>)
177
        """
178
        missing_items = {}
179
        for (index_name, external_refs, index) in [
180
            ('texts',
181
                self._get_external_refs(self.text_index),
182
                self._pack_collection.text_index.combined_index),
183
            ('inventories',
184
                self._get_external_refs(self.inventory_index),
185
                self._pack_collection.inventory_index.combined_index),
186
            ]:
187
            missing = external_refs.difference(
188
                k for (idx, k, v, r) in
189
                index.iter_entries(external_refs))
190
            if missing:
191
                missing_items[index_name] = sorted(list(missing))
192
        if missing_items:
193
            from pprint import pformat
194
            raise errors.BzrCheckError(
195
                "Newly created pack file %r has delta references to "
196
                "items not in its repository:\n%s"
197
                % (self, pformat(missing_items)))
198
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
199
    def file_name(self):
200
        """Get the file name for the pack on disk."""
201
        return self.name + '.pack'
202
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
203
    def get_revision_count(self):
204
        return self.revision_index.key_count()
205
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
206
    def index_name(self, index_type, name):
207
        """Get the disk name of an index type for pack name 'name'."""
208
        return name + Pack.index_definitions[index_type][0]
209
210
    def index_offset(self, index_type):
211
        """Get the position in a index_size array for a given index type."""
212
        return Pack.index_definitions[index_type][1]
213
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
214
    def inventory_index_name(self, name):
215
        """The inv index is the name + .iix."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
216
        return self.index_name('inventory', name)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
217
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
218
    def revision_index_name(self, name):
219
        """The revision index is the name + .rix."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
220
        return self.index_name('revision', name)
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
221
222
    def signature_index_name(self, name):
223
        """The signature index is the name + .six."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
224
        return self.index_name('signature', name)
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
225
226
    def text_index_name(self, name):
227
        """The text index is the name + .tix."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
228
        return self.index_name('text', name)
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
229
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
230
    def _replace_index_with_readonly(self, index_type):
231
        setattr(self, index_type + '_index',
232
            self.index_class(self.index_transport,
233
                self.index_name(index_type, self.name),
234
                self.index_sizes[self.index_offset(index_type)]))
235
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
236
237
class ExistingPack(Pack):
2592.3.222 by Robert Collins
More review feedback.
238
    """An in memory proxy for an existing .pack and its disk indices."""
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
239
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
240
    def __init__(self, pack_transport, name, revision_index, inventory_index,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
241
        text_index, signature_index, chk_index=None):
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
242
        """Create an ExistingPack object.
243
244
        :param pack_transport: The transport where the pack file resides.
245
        :param name: The name of the pack on disk in the pack_transport.
246
        """
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
247
        Pack.__init__(self, revision_index, inventory_index, text_index,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
248
            signature_index, chk_index)
2592.3.173 by Robert Collins
Basic implementation of all_packs.
249
        self.name = name
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
250
        self.pack_transport = pack_transport
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
251
        if None in (revision_index, inventory_index, text_index,
252
                signature_index, name, pack_transport):
253
            raise AssertionError()
2592.3.173 by Robert Collins
Basic implementation of all_packs.
254
255
    def __eq__(self, other):
256
        return self.__dict__ == other.__dict__
257
258
    def __ne__(self, other):
259
        return not self.__eq__(other)
260
261
    def __repr__(self):
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
262
        return "<%s.%s object at 0x%x, %s, %s" % (
263
            self.__class__.__module__, self.__class__.__name__, id(self),
264
            self.pack_transport, self.name)
265
266
267
class ResumedPack(ExistingPack):
268
269
    def __init__(self, name, revision_index, inventory_index, text_index,
270
        signature_index, upload_transport, pack_transport, index_transport,
271
        pack_collection):
272
        """Create a ResumedPack object."""
273
        ExistingPack.__init__(self, pack_transport, name, revision_index,
274
            inventory_index, text_index, signature_index)
275
        self.upload_transport = upload_transport
276
        self.index_transport = index_transport
277
        self.index_sizes = [None, None, None, None]
278
        indices = [
279
            ('revision', revision_index),
280
            ('inventory', inventory_index),
281
            ('text', text_index),
282
            ('signature', signature_index),
283
            ]
284
        for index_type, index in indices:
285
            offset = self.index_offset(index_type)
286
            self.index_sizes[offset] = index._size
287
        self.index_class = pack_collection._index_class
4002.1.12 by Andrew Bennetts
Add another test, fix the code so it passes, and remove some cruft.
288
        self._pack_collection = pack_collection
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
289
        self._state = 'resumed'
290
        # XXX: perhaps check that the .pack file exists?
291
292
    def access_tuple(self):
293
        if self._state == 'finished':
294
            return Pack.access_tuple(self)
295
        elif self._state == 'resumed':
296
            return self.upload_transport, self.file_name()
297
        else:
298
            raise AssertionError(self._state)
299
300
    def abort(self):
301
        self.upload_transport.delete(self.file_name())
302
        indices = [self.revision_index, self.inventory_index, self.text_index,
303
            self.signature_index]
304
        for index in indices:
305
            index._transport.delete(index._name)
306
307
    def finish(self):
4002.1.12 by Andrew Bennetts
Add another test, fix the code so it passes, and remove some cruft.
308
        self._check_references()
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
309
        new_name = '../packs/' + self.file_name()
310
        self.upload_transport.rename(self.file_name(), new_name)
311
        for index_type in ['revision', 'inventory', 'text', 'signature']:
312
            old_name = self.index_name(index_type, self.name)
313
            new_name = '../indices/' + old_name
314
            self.upload_transport.rename(old_name, new_name)
315
            self._replace_index_with_readonly(index_type)
316
        self._state = 'finished'
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
317
4002.1.12 by Andrew Bennetts
Add another test, fix the code so it passes, and remove some cruft.
318
    def _get_external_refs(self, index):
319
        return index.external_references(1)
320
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
321
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
322
class NewPack(Pack):
323
    """An in memory proxy for a pack which is being created."""
324
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
325
    def __init__(self, pack_collection, upload_suffix='', file_mode=None):
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
326
        """Create a NewPack instance.
327
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
328
        :param pack_collection: A PackCollection into which this is being inserted.
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
329
        :param upload_suffix: An optional suffix to be given to any temporary
330
            files created during the pack creation. e.g '.autopack'
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
331
        :param file_mode: Unix permissions for newly created file.
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
332
        """
2592.3.228 by Martin Pool
docstrings and error messages from review
333
        # The relative locations of the packs are constrained, but all are
334
        # passed in because the caller has them, so as to avoid object churn.
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
335
        index_builder_class = pack_collection._index_builder_class
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
336
        if pack_collection.chk_index is not None:
337
            chk_index = index_builder_class(reference_lists=0)
338
        else:
339
            chk_index = None
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
340
        Pack.__init__(self,
341
            # Revisions: parents list, no text compression.
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
342
            index_builder_class(reference_lists=1),
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
343
            # Inventory: We want to map compression only, but currently the
344
            # knit code hasn't been updated enough to understand that, so we
345
            # have a regular 2-list index giving parents and compression
346
            # source.
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
347
            index_builder_class(reference_lists=2),
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
348
            # Texts: compression and per file graph, for all fileids - so two
349
            # reference lists and two elements in the key tuple.
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
350
            index_builder_class(reference_lists=2, key_elements=2),
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
351
            # Signatures: Just blobs to store, no compression, no parents
352
            # listing.
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
353
            index_builder_class(reference_lists=0),
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
354
            # CHK based storage - just blobs, no compression or parents.
355
            chk_index=chk_index
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
356
            )
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
357
        self._pack_collection = pack_collection
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
358
        # When we make readonly indices, we need this.
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
359
        self.index_class = pack_collection._index_class
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
360
        # where should the new pack be opened
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
361
        self.upload_transport = pack_collection._upload_transport
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
362
        # where are indices written out to
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
363
        self.index_transport = pack_collection._index_transport
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
364
        # where is the pack renamed to when it is finished?
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
365
        self.pack_transport = pack_collection._pack_transport
3010.1.11 by Robert Collins
Provide file modes to files created by pack repositories
366
        # What file mode to upload the pack and indices with.
367
        self._file_mode = file_mode
2592.3.193 by Robert Collins
Move hash tracking of new packs into NewPack.
368
        # tracks the content written to the .pack file.
2929.3.5 by Vincent Ladeuil
New files, same warnings, same fixes.
369
        self._hash = osutils.md5()
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
370
        # a tuple with the length in bytes of the indices, once the pack
371
        # is finalised. (rev, inv, text, sigs, chk_if_in_use)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
372
        self.index_sizes = None
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
373
        # How much data to cache when writing packs. Note that this is not
2592.3.222 by Robert Collins
More review feedback.
374
        # synchronised with reads, because it's not in the transport layer, so
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
375
        # is not safe unless the client knows it won't be reading from the pack
376
        # under creation.
377
        self._cache_limit = 0
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
378
        # the temporary pack file name.
2929.3.5 by Vincent Ladeuil
New files, same warnings, same fixes.
379
        self.random_name = osutils.rand_chars(20) + upload_suffix
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
380
        # when was this pack started ?
381
        self.start_time = time.time()
2592.3.202 by Robert Collins
Move write stream management into NewPack.
382
        # open an output stream for the data added to the pack.
383
        self.write_stream = self.upload_transport.open_write_stream(
3010.1.11 by Robert Collins
Provide file modes to files created by pack repositories
384
            self.random_name, mode=self._file_mode)
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
385
        if 'pack' in debug.debug_flags:
2592.3.202 by Robert Collins
Move write stream management into NewPack.
386
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
387
                time.ctime(), self.upload_transport.base, self.random_name,
388
                time.time() - self.start_time)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
389
        # A list of byte sequences to be written to the new pack, and the
390
        # aggregate size of them.  Stored as a list rather than separate
2592.3.233 by Martin Pool
Review cleanups
391
        # variables so that the _write_data closure below can update them.
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
392
        self._buffer = [[], 0]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
393
        # create a callable for adding data
2592.3.233 by Martin Pool
Review cleanups
394
        #
395
        # robertc says- this is a closure rather than a method on the object
396
        # so that the variables are locals, and faster than accessing object
397
        # members.
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
398
        def _write_data(bytes, flush=False, _buffer=self._buffer,
399
            _write=self.write_stream.write, _update=self._hash.update):
400
            _buffer[0].append(bytes)
401
            _buffer[1] += len(bytes)
2592.3.222 by Robert Collins
More review feedback.
402
            # buffer cap
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
403
            if _buffer[1] > self._cache_limit or flush:
404
                bytes = ''.join(_buffer[0])
405
                _write(bytes)
406
                _update(bytes)
407
                _buffer[:] = [[], 0]
2592.3.202 by Robert Collins
Move write stream management into NewPack.
408
        # expose this on self, for the occasion when clients want to add data.
409
        self._write_data = _write_data
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
410
        # a pack writer object to serialise pack records.
411
        self._writer = pack.ContainerWriter(self._write_data)
412
        self._writer.begin()
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
413
        # what state is the pack in? (open, finished, aborted)
414
        self._state = 'open'
2592.3.202 by Robert Collins
Move write stream management into NewPack.
415
416
    def abort(self):
417
        """Cancel creating this pack."""
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
418
        self._state = 'aborted'
2938.1.1 by Robert Collins
trivial fix for packs@win32: explicitly close file before deleting
419
        self.write_stream.close()
2592.3.202 by Robert Collins
Move write stream management into NewPack.
420
        # Remove the temporary pack file.
421
        self.upload_transport.delete(self.random_name)
422
        # The indices have no state on disk.
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
423
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
424
    def access_tuple(self):
425
        """Return a tuple (transport, name) for the pack content."""
426
        if self._state == 'finished':
427
            return Pack.access_tuple(self)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
428
        elif self._state == 'open':
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
429
            return self.upload_transport, self.random_name
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
430
        else:
431
            raise AssertionError(self._state)
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
432
2592.3.198 by Robert Collins
Factor out data_inserted to reduce code duplication in detecting empty packs.
433
    def data_inserted(self):
434
        """True if data has been added to this pack."""
2592.3.233 by Martin Pool
Review cleanups
435
        return bool(self.get_revision_count() or
436
            self.inventory_index.key_count() or
437
            self.text_index.key_count() or
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
438
            self.signature_index.key_count() or
439
            (self.chk_index is not None and self.chk_index.key_count()))
2592.3.198 by Robert Collins
Factor out data_inserted to reduce code duplication in detecting empty packs.
440
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
441
    def finish(self, suspend=False):
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
442
        """Finish the new pack.
443
444
        This:
445
         - finalises the content
446
         - assigns a name (the md5 of the content, currently)
447
         - writes out the associated indices
448
         - renames the pack into place.
449
         - stores the index size tuple for the pack in the index_sizes
450
           attribute.
451
        """
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
452
        self._writer.end()
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
453
        if self._buffer[1]:
454
            self._write_data('', flush=True)
2592.3.199 by Robert Collins
Store the name of a NewPack in the object upon finish().
455
        self.name = self._hash.hexdigest()
4002.1.11 by Andrew Bennetts
Fix latest test.
456
        if not suspend:
457
            self._check_references()
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
458
        # write indices
2592.3.233 by Martin Pool
Review cleanups
459
        # XXX: It'd be better to write them all to temporary names, then
460
        # rename them all into place, so that the window when only some are
461
        # visible is smaller.  On the other hand none will be seen until
462
        # they're in the names list.
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
463
        self.index_sizes = [None, None, None, None]
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
464
        self._write_index('revision', self.revision_index, 'revision', suspend)
465
        self._write_index('inventory', self.inventory_index, 'inventory',
466
            suspend)
467
        self._write_index('text', self.text_index, 'file texts', suspend)
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
468
        self._write_index('signature', self.signature_index,
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
469
            'revision signatures', suspend)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
470
        if self.chk_index is not None:
471
            self.index_sizes.append(None)
472
            self._write_index('chk', self.chk_index,
473
                'content hash bytes', suspend)
2592.3.202 by Robert Collins
Move write stream management into NewPack.
474
        self.write_stream.close()
2592.3.206 by Robert Collins
Move pack rename-into-place into NewPack.finish and document hash-collision cases somewhat better.
475
        # Note that this will clobber an existing pack with the same name,
476
        # without checking for hash collisions. While this is undesirable this
477
        # is something that can be rectified in a subsequent release. One way
478
        # to rectify it may be to leave the pack at the original name, writing
479
        # its pack-names entry as something like 'HASH: index-sizes
480
        # temporary-name'. Allocate that and check for collisions, if it is
481
        # collision free then rename it into place. If clients know this scheme
482
        # they can handle missing-file errors by:
483
        #  - try for HASH.pack
484
        #  - try for temporary-name
485
        #  - refresh the pack-list to see if the pack is now absent
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
486
        new_name = self.name + '.pack'
487
        if not suspend:
488
            new_name = '../packs/' + new_name
489
        self.upload_transport.rename(self.random_name, new_name)
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
490
        self._state = 'finished'
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
491
        if 'pack' in debug.debug_flags:
2592.3.219 by Robert Collins
Review feedback.
492
            # XXX: size might be interesting?
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
493
            mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
2592.3.219 by Robert Collins
Review feedback.
494
                time.ctime(), self.upload_transport.base, self.random_name,
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
495
                new_name, time.time() - self.start_time)
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
496
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
497
    def flush(self):
498
        """Flush any current data."""
499
        if self._buffer[1]:
500
            bytes = ''.join(self._buffer[0])
501
            self.write_stream.write(bytes)
502
            self._hash.update(bytes)
503
            self._buffer[:] = [[], 0]
504
4002.1.12 by Andrew Bennetts
Add another test, fix the code so it passes, and remove some cruft.
505
    def _get_external_refs(self, index):
506
        return index._external_references()
507
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
508
    def set_write_cache_size(self, size):
509
        self._cache_limit = size
510
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
511
    def _write_index(self, index_type, index, label, suspend=False):
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
512
        """Write out an index.
513
2592.3.222 by Robert Collins
More review feedback.
514
        :param index_type: The type of index to write - e.g. 'revision'.
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
515
        :param index: The index object to serialise.
516
        :param label: What label to give the index e.g. 'revision'.
517
        """
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
518
        index_name = self.index_name(index_type, self.name)
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
519
        if suspend:
520
            transport = self.upload_transport
521
        else:
522
            transport = self.index_transport
523
        self.index_sizes[self.index_offset(index_type)] = transport.put_file(
524
            index_name, index.finish(), mode=self._file_mode)
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
525
        if 'pack' in debug.debug_flags:
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
526
            # XXX: size might be interesting?
527
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
528
                time.ctime(), label, self.upload_transport.base,
529
                self.random_name, time.time() - self.start_time)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
530
        # Replace the writable index on this object with a readonly,
2592.3.233 by Martin Pool
Review cleanups
531
        # presently unloaded index. We should alter
532
        # the index layer to make its finish() error if add_node is
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
533
        # subsequently used. RBC
2592.3.233 by Martin Pool
Review cleanups
534
        self._replace_index_with_readonly(index_type)
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
535
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
536
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
537
class AggregateIndex(object):
538
    """An aggregated index for the RepositoryPackCollection.
539
540
    AggregateIndex is reponsible for managing the PackAccess object,
541
    Index-To-Pack mapping, and all indices list for a specific type of index
542
    such as 'revision index'.
2592.3.228 by Martin Pool
docstrings and error messages from review
543
544
    A CombinedIndex provides an index on a single key space built up
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
545
    from several on-disk indices.  The AggregateIndex builds on this
2592.3.228 by Martin Pool
docstrings and error messages from review
546
    to provide a knit access layer, and allows having up to one writable
547
    index within the collection.
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
548
    """
2592.3.235 by Martin Pool
Review cleanups
549
    # XXX: Probably 'can be written to' could/should be separated from 'acts
550
    # like a knit index' -- mbp 20071024
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
551
4187.3.3 by Andrew Bennetts
In KnitVersionedFiles.insert_record_stream, flush the access object before expanding a delta into a fulltext.
552
    def __init__(self, reload_func=None, flush_func=None):
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
553
        """Create an AggregateIndex.
554
555
        :param reload_func: A function to call if we find we are missing an
3789.1.10 by John Arbash Meinel
Review comments from Martin.
556
            index. Should have the form reload_func() => True if the list of
557
            active pack files has changed.
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
558
        """
559
        self._reload_func = reload_func
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
560
        self.index_to_pack = {}
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
561
        self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
3789.2.14 by John Arbash Meinel
Update AggregateIndex to pass the reload_func into _DirectPackAccess
562
        self.data_access = _DirectPackAccess(self.index_to_pack,
4187.3.3 by Andrew Bennetts
In KnitVersionedFiles.insert_record_stream, flush the access object before expanding a delta into a fulltext.
563
                                             reload_func=reload_func,
564
                                             flush_func=flush_func)
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.
565
        self.add_callback = None
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
566
567
    def replace_indices(self, index_to_pack, indices):
568
        """Replace the current mappings with fresh ones.
569
570
        This should probably not be used eventually, rather incremental add and
571
        removal of indices. It has been added during refactoring of existing
572
        code.
573
574
        :param index_to_pack: A mapping from index objects to
575
            (transport, name) tuples for the pack file data.
576
        :param indices: A list of indices.
577
        """
578
        # refresh the revision pack map dict without replacing the instance.
579
        self.index_to_pack.clear()
580
        self.index_to_pack.update(index_to_pack)
581
        # XXX: API break - clearly a 'replace' method would be good?
582
        self.combined_index._indices[:] = indices
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
583
        # the current add nodes callback for the current writable index if
584
        # there is one.
585
        self.add_callback = None
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
586
587
    def add_index(self, index, pack):
588
        """Add index to the aggregate, which is an index for Pack pack.
2592.3.226 by Martin Pool
formatting and docstrings
589
590
        Future searches on the aggregate index will seach this new index
591
        before all previously inserted indices.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
592
2592.3.226 by Martin Pool
formatting and docstrings
593
        :param index: An Index for the pack.
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
594
        :param pack: A Pack instance.
595
        """
596
        # expose it to the index map
597
        self.index_to_pack[index] = pack.access_tuple()
598
        # put it at the front of the linear index list
599
        self.combined_index.insert_index(0, index)
600
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
601
    def add_writable_index(self, index, pack):
602
        """Add an index which is able to have data added to it.
2592.3.235 by Martin Pool
Review cleanups
603
604
        There can be at most one writable index at any time.  Any
605
        modifications made to the knit are put into this index.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
606
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
607
        :param index: An index from the pack parameter.
608
        :param pack: A Pack instance.
609
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
610
        if self.add_callback is not None:
611
            raise AssertionError(
612
                "%s already has a writable index through %s" % \
613
                (self, self.add_callback))
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
614
        # allow writing: queue writes to a new index
615
        self.add_index(index, pack)
616
        # Updates the index to packs mapping as a side effect,
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.
617
        self.data_access.set_writer(pack._writer, index, pack.access_tuple())
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
618
        self.add_callback = index.add_nodes
619
620
    def clear(self):
621
        """Reset all the aggregate data to nothing."""
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.
622
        self.data_access.set_writer(None, None, (None, None))
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
623
        self.index_to_pack.clear()
624
        del self.combined_index._indices[:]
625
        self.add_callback = None
626
627
    def remove_index(self, index, pack):
628
        """Remove index from the indices used to answer queries.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
629
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
630
        :param index: An index from the pack parameter.
631
        :param pack: A Pack instance.
632
        """
633
        del self.index_to_pack[index]
634
        self.combined_index._indices.remove(index)
635
        if (self.add_callback is not None and
636
            getattr(index, 'add_nodes', None) == self.add_callback):
637
            self.add_callback = 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.
638
            self.data_access.set_writer(None, None, (None, None))
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
639
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
640
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
641
class Packer(object):
642
    """Create a pack from packs."""
643
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
644
    def __init__(self, pack_collection, packs, suffix, revision_ids=None,
645
                 reload_func=None):
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
646
        """Create a Packer.
647
648
        :param pack_collection: A RepositoryPackCollection object where the
649
            new pack is being written to.
650
        :param packs: The packs to combine.
651
        :param suffix: The suffix to use on the temporary files for the pack.
652
        :param revision_ids: Revision ids to limit the pack to.
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
653
        :param reload_func: A function to call if a pack file/index goes
654
            missing. The side effect of calling this function should be to
655
            update self.packs. See also AggregateIndex
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
656
        """
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
657
        self.packs = packs
658
        self.suffix = suffix
659
        self.revision_ids = revision_ids
2951.2.1 by Robert Collins
Factor out revision text copying in Packer to a single helper method.
660
        # The pack object we are creating.
661
        self.new_pack = None
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
662
        self._pack_collection = pack_collection
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
663
        self._reload_func = reload_func
2951.2.1 by Robert Collins
Factor out revision text copying in Packer to a single helper method.
664
        # The index layer keys for the revisions being copied. None for 'all
665
        # objects'.
666
        self._revision_keys = None
2951.2.2 by Robert Collins
Factor out inventory text copying in Packer to a single helper method.
667
        # What text keys to copy. None for 'all texts'. This is set by
668
        # _copy_inventory_texts
669
        self._text_filter = None
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
670
        self._extra_init()
671
672
    def _extra_init(self):
673
        """A template hook to allow extending the constructor trivially."""
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
674
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
675
    def _pack_map_and_index_list(self, index_attribute):
3824.2.1 by John Arbash Meinel
Clean up some pack object functions.
676
        """Convert a list of packs to an index pack map and index list.
677
678
        :param index_attribute: The attribute that the desired index is found
679
            on.
680
        :return: A tuple (map, list) where map contains the dict from
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
681
            index:pack_tuple, and list contains the indices in the preferred
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
682
            access order.
3824.2.1 by John Arbash Meinel
Clean up some pack object functions.
683
        """
684
        indices = []
685
        pack_map = {}
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
686
        for pack_obj in self.packs:
687
            index = getattr(pack_obj, index_attribute)
3824.2.1 by John Arbash Meinel
Clean up some pack object functions.
688
            indices.append(index)
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
689
            pack_map[index] = pack_obj
3824.2.1 by John Arbash Meinel
Clean up some pack object functions.
690
        return pack_map, indices
691
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
692
    def _index_contents(self, indices, key_filter=None):
3824.2.1 by John Arbash Meinel
Clean up some pack object functions.
693
        """Get an iterable of the index contents from a pack_map.
694
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
695
        :param indices: The list of indices to query
696
        :param key_filter: An optional filter to limit the keys returned.
3824.2.1 by John Arbash Meinel
Clean up some pack object functions.
697
        """
698
        all_index = CombinedGraphIndex(indices)
699
        if key_filter is None:
700
            return all_index.iter_all_entries()
701
        else:
702
            return all_index.iter_entries(key_filter)
703
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
704
    def pack(self, pb=None):
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
705
        """Create a new pack by reading data from other packs.
706
707
        This does little more than a bulk copy of data. One key difference
708
        is that data with the same item key across multiple packs is elided
709
        from the output. The new pack is written into the current pack store
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
710
        along with its indices, and the name added to the pack names. The
2592.3.182 by Robert Collins
Eliminate the need to use a transport,name tuple to represent a pack during fetch.
711
        source packs are not altered and are not required to be in the current
712
        pack collection.
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
713
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
714
        :param pb: An optional progress bar to use. A nested bar is created if
715
            this is None.
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
716
        :return: A Pack object, or None if nothing was copied.
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
717
        """
718
        # open a pack - using the same name as the last temporary file
719
        # - which has already been flushed, so its safe.
720
        # XXX: - duplicate code warning with start_write_group; fix before
721
        #      considering 'done'.
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
722
        if self._pack_collection._new_pack is not None:
3789.2.22 by John Arbash Meinel
We need the Packer class to cleanup if it is getting a Retry it isn't handling.
723
            raise errors.BzrError('call to %s.pack() while another pack is'
724
                                  ' being written.'
725
                                  % (self.__class__.__name__,))
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
726
        if self.revision_ids is not None:
727
            if len(self.revision_ids) == 0:
2947.1.3 by Robert Collins
Unbreak autopack. Doh.
728
                # silly fetch request.
729
                return None
730
            else:
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
731
                self.revision_ids = frozenset(self.revision_ids)
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.
732
                self.revision_keys = frozenset((revid,) for revid in
733
                    self.revision_ids)
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
734
        if pb is None:
735
            self.pb = ui.ui_factory.nested_progress_bar()
736
        else:
737
            self.pb = pb
2592.6.11 by Robert Collins
* A progress bar has been added for knitpack -> knitpack fetching.
738
        try:
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
739
            return self._create_pack_from_packs()
2592.6.11 by Robert Collins
* A progress bar has been added for knitpack -> knitpack fetching.
740
        finally:
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
741
            if pb is None:
742
                self.pb.finished()
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
743
744
    def open_pack(self):
745
        """Open a pack for the pack we are creating."""
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
746
        new_pack = self._pack_collection.pack_factory(self._pack_collection,
747
                upload_suffix=self.suffix,
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
748
                file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
4168.3.6 by John Arbash Meinel
Add 'combine_backing_indices' as a flag for GraphIndex.set_optimize().
749
        # We know that we will process all nodes in order, and don't need to
750
        # query, so don't combine any indices spilled to disk until we are done
751
        new_pack.revision_index.set_optimize(combine_backing_indices=False)
752
        new_pack.inventory_index.set_optimize(combine_backing_indices=False)
753
        new_pack.text_index.set_optimize(combine_backing_indices=False)
754
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
755
        return new_pack
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
756
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
757
    def _update_pack_order(self, entries, index_to_pack_map):
758
        """Determine how we want our packs to be ordered.
759
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
760
        This changes the sort order of the self.packs list so that packs unused
761
        by 'entries' will be at the end of the list, so that future requests
762
        can avoid probing them.  Used packs will be at the front of the
763
        self.packs list, in the order of their first use in 'entries'.
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
764
765
        :param entries: A list of (index, ...) tuples
766
        :param index_to_pack_map: A mapping from index objects to pack objects.
767
        """
768
        packs = []
769
        seen_indexes = set()
770
        for entry in entries:
771
            index = entry[0]
772
            if index not in seen_indexes:
773
                packs.append(index_to_pack_map[index])
774
                seen_indexes.add(index)
775
        if len(packs) == len(self.packs):
776
            if 'pack' in debug.debug_flags:
777
                mutter('Not changing pack list, all packs used.')
778
            return
779
        seen_packs = set(packs)
780
        for pack in self.packs:
781
            if pack not in seen_packs:
782
                packs.append(pack)
783
                seen_packs.add(pack)
784
        if 'pack' in debug.debug_flags:
785
            old_names = [p.access_tuple()[1] for p in self.packs]
786
            new_names = [p.access_tuple()[1] for p in packs]
787
            mutter('Reordering packs\nfrom: %s\n  to: %s',
788
                   old_names, new_names)
789
        self.packs = packs
790
2951.2.1 by Robert Collins
Factor out revision text copying in Packer to a single helper method.
791
    def _copy_revision_texts(self):
792
        """Copy revision data to the new pack."""
793
        # select revisions
794
        if self.revision_ids:
795
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
796
        else:
797
            revision_keys = None
798
        # select revision keys
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
799
        revision_index_map, revision_indices = self._pack_map_and_index_list(
800
            'revision_index')
801
        revision_nodes = self._index_contents(revision_indices, revision_keys)
802
        revision_nodes = list(revision_nodes)
803
        self._update_pack_order(revision_nodes, revision_index_map)
2951.2.1 by Robert Collins
Factor out revision text copying in Packer to a single helper method.
804
        # copy revision keys and adjust values
805
        self.pb.update("Copying revision texts", 1)
3070.1.2 by John Arbash Meinel
Cleanup OptimizingPacker code according to my review feedback
806
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
807
        list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
808
            self.new_pack.revision_index, readv_group_iter, total_items))
2951.2.1 by Robert Collins
Factor out revision text copying in Packer to a single helper method.
809
        if 'pack' in debug.debug_flags:
810
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
811
                time.ctime(), self._pack_collection._upload_transport.base,
812
                self.new_pack.random_name,
813
                self.new_pack.revision_index.key_count(),
814
                time.time() - self.new_pack.start_time)
815
        self._revision_keys = revision_keys
816
2951.2.2 by Robert Collins
Factor out inventory text copying in Packer to a single helper method.
817
    def _copy_inventory_texts(self):
818
        """Copy the inventory texts to the new pack.
819
820
        self._revision_keys is used to determine what inventories to copy.
821
822
        Sets self._text_filter appropriately.
823
        """
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
824
        # select inventory keys
2951.2.1 by Robert Collins
Factor out revision text copying in Packer to a single helper method.
825
        inv_keys = self._revision_keys # currently the same keyspace, and note that
2592.3.145 by Robert Collins
Fix test_fetch_missing_text_other_location_fails for pack repositories.
826
        # querying for keys here could introduce a bug where an inventory item
827
        # is missed, so do not change it to query separately without cross
828
        # checking like the text key check below.
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
829
        inventory_index_map, inventory_indices = self._pack_map_and_index_list(
830
            'inventory_index')
831
        inv_nodes = self._index_contents(inventory_indices, inv_keys)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
832
        # copy inventory keys and adjust values
2592.3.104 by Robert Collins
hackish fix, but all tests passing again.
833
        # XXX: Should be a helper function to allow different inv representation
834
        # at this point.
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
835
        self.pb.update("Copying inventory texts", 2)
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
836
        total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
3253.1.1 by John Arbash Meinel
Reduce memory consumption during autopack.
837
        # Only grab the output lines if we will be processing them
838
        output_lines = bool(self.revision_ids)
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
839
        inv_lines = self._copy_nodes_graph(inventory_index_map,
840
            self.new_pack._writer, self.new_pack.inventory_index,
3253.1.1 by John Arbash Meinel
Reduce memory consumption during autopack.
841
            readv_group_iter, total_items, output_lines=output_lines)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
842
        if self.revision_ids:
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
843
            self._process_inventory_lines(inv_lines)
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
844
        else:
2592.3.145 by Robert Collins
Fix test_fetch_missing_text_other_location_fails for pack repositories.
845
            # eat the iterator to cause it to execute.
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
846
            list(inv_lines)
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
847
            self._text_filter = None
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
848
        if 'pack' in debug.debug_flags:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
849
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
2951.2.2 by Robert Collins
Factor out inventory text copying in Packer to a single helper method.
850
                time.ctime(), self._pack_collection._upload_transport.base,
851
                self.new_pack.random_name,
852
                self.new_pack.inventory_index.key_count(),
3231.3.1 by James Westby
Make -Dpack not cause a error trying to use an unkown variable.
853
                time.time() - self.new_pack.start_time)
2951.2.2 by Robert Collins
Factor out inventory text copying in Packer to a single helper method.
854
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
855
    def _copy_text_texts(self):
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
856
        # select text keys
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
857
        text_index_map, text_nodes = self._get_text_nodes()
2951.2.2 by Robert Collins
Factor out inventory text copying in Packer to a single helper method.
858
        if self._text_filter is not None:
2592.3.149 by Robert Collins
Unbreak pack to pack fetching properly, with missing-text detection really working.
859
            # We could return the keys copied as part of the return value from
860
            # _copy_nodes_graph but this doesn't work all that well with the
861
            # need to get line output too, so we check separately, and as we're
862
            # going to buffer everything anyway, we check beforehand, which
863
            # saves reading knit data over the wire when we know there are
864
            # mising records.
865
            text_nodes = set(text_nodes)
866
            present_text_keys = set(_node[1] for _node in text_nodes)
2951.2.2 by Robert Collins
Factor out inventory text copying in Packer to a single helper method.
867
            missing_text_keys = set(self._text_filter) - present_text_keys
2592.3.149 by Robert Collins
Unbreak pack to pack fetching properly, with missing-text detection really working.
868
            if missing_text_keys:
869
                # TODO: raise a specific error that can handle many missing
870
                # keys.
4084.3.1 by Robert Collins
Log all missing keys in pack fetch operations that fail due to missing keys.
871
                mutter("missing keys during fetch: %r", missing_text_keys)
2592.3.149 by Robert Collins
Unbreak pack to pack fetching properly, with missing-text detection really working.
872
                a_missing_key = missing_text_keys.pop()
873
                raise errors.RevisionNotPresent(a_missing_key[1],
874
                    a_missing_key[0])
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
875
        # copy text keys and adjust values
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
876
        self.pb.update("Copying content texts", 3)
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
877
        total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
878
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
879
            self.new_pack.text_index, readv_group_iter, total_items))
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
880
        self._log_copied_texts()
881
882
    def _create_pack_from_packs(self):
883
        self.pb.update("Opening pack", 0, 5)
884
        self.new_pack = self.open_pack()
885
        new_pack = self.new_pack
886
        # buffer data - we won't be reading-back during the pack creation and
887
        # this makes a significant difference on sftp pushes.
888
        new_pack.set_write_cache_size(1024*1024)
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
889
        if 'pack' in debug.debug_flags:
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
890
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
891
                for a_pack in self.packs]
892
            if self.revision_ids is not None:
893
                rev_count = len(self.revision_ids)
894
            else:
895
                rev_count = 'all'
896
            mutter('%s: create_pack: creating pack from source packs: '
897
                '%s%s %s revisions wanted %s t=0',
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
898
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
899
                plain_pack_list, rev_count)
900
        self._copy_revision_texts()
901
        self._copy_inventory_texts()
902
        self._copy_text_texts()
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
903
        # select signature keys
2951.2.1 by Robert Collins
Factor out revision text copying in Packer to a single helper method.
904
        signature_filter = self._revision_keys # same keyspace
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
905
        signature_index_map, signature_indices = self._pack_map_and_index_list(
906
            'signature_index')
907
        signature_nodes = self._index_contents(signature_indices,
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
908
            signature_filter)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
909
        # copy signature keys and adjust values
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
910
        self.pb.update("Copying signature texts", 4)
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
911
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
912
            new_pack.signature_index)
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
913
        if 'pack' in debug.debug_flags:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
914
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
915
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
916
                new_pack.signature_index.key_count(),
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
917
                time.time() - new_pack.start_time)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
918
        # copy chk contents
919
        # NB XXX: how to check CHK references are present? perhaps by yielding
920
        # the items? How should that interact with stacked repos?
921
        if new_pack.chk_index is not None:
922
            self._copy_chks()
923
            if 'pack' in debug.debug_flags:
924
                mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
925
                    time.ctime(), self._pack_collection._upload_transport.base,
926
                    new_pack.random_name,
927
                    new_pack.chk_index.key_count(),
928
                    time.time() - new_pack.start_time)
3830.3.2 by Martin Pool
Check that newly created packs don't have missing delta bases.
929
        new_pack._check_references()
2951.2.8 by Robert Collins
Test that reconciling a repository can be done twice in a row.
930
        if not self._use_pack(new_pack):
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
931
            new_pack.abort()
932
            return None
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
933
        self.pb.update("Finishing pack", 5)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
934
        new_pack.finish()
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
935
        self._pack_collection.allocate(new_pack)
2592.3.206 by Robert Collins
Move pack rename-into-place into NewPack.finish and document hash-collision cases somewhat better.
936
        return new_pack
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
937
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
938
    def _copy_chks(self, refs=None):
939
        # XXX: Todo, recursive follow-pointers facility when fetching some
940
        # revisions only.
941
        chk_index_map, chk_indices = self._pack_map_and_index_list(
942
            'chk_index')
943
        chk_nodes = self._index_contents(chk_indices, refs)
944
        new_refs = set()
945
        # TODO: This isn't strictly tasteful as we are accessing some private
946
        #       variables (_serializer). Perhaps a better way would be to have
947
        #       Repository._deserialise_chk_node()
948
        search_key_func = chk_map.search_key_registry.get(
949
            self._pack_collection.repo._serializer.search_key_name)
950
        def accumlate_refs(lines):
951
            # XXX: move to a generic location
952
            # Yay mismatch:
953
            bytes = ''.join(lines)
954
            node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
955
            new_refs.update(node.refs())
956
        self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
957
            self.new_pack.chk_index, output_lines=accumlate_refs)
958
        return new_refs
959
960
    def _copy_nodes(self, nodes, index_map, writer, write_index,
961
        output_lines=None):
962
        """Copy knit nodes between packs with no graph references.
963
964
        :param output_lines: Output full texts of copied items.
965
        """
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
966
        pb = ui.ui_factory.nested_progress_bar()
967
        try:
968
            return self._do_copy_nodes(nodes, index_map, writer,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
969
                write_index, pb, output_lines=output_lines)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
970
        finally:
971
            pb.finished()
972
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
973
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
974
        output_lines=None):
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
975
        # for record verification
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.
976
        knit = KnitVersionedFiles(None, None)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
977
        # plan a readv on each source pack:
978
        # group by pack
979
        nodes = sorted(nodes)
980
        # how to map this into knit.py - or knit.py into this?
981
        # we don't want the typical knit logic, we want grouping by pack
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
982
        # at this point - perhaps a helper library for the following code
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
983
        # duplication points?
984
        request_groups = {}
985
        for index, key, value in nodes:
986
            if index not in request_groups:
987
                request_groups[index] = []
988
            request_groups[index].append((key, value))
989
        record_index = 0
990
        pb.update("Copied record", record_index, len(nodes))
991
        for index, items in request_groups.iteritems():
992
            pack_readv_requests = []
993
            for key, value in items:
994
                # ---- KnitGraphIndex.get_position
995
                bits = value[1:].split(' ')
996
                offset, length = int(bits[0]), int(bits[1])
997
                pack_readv_requests.append((offset, length, (key, value[0])))
998
            # linear scan up the pack
999
            pack_readv_requests.sort()
1000
            # copy the data
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
1001
            pack_obj = index_map[index]
1002
            transport, path = pack_obj.access_tuple()
3789.2.26 by John Arbash Meinel
Change the code so that we expect _reload_func to divert the flow by raising.
1003
            try:
1004
                reader = pack.make_readv_reader(transport, path,
1005
                    [offset[0:2] for offset in pack_readv_requests])
1006
            except errors.NoSuchFile:
1007
                if self._reload_func is not None:
1008
                    self._reload_func()
1009
                raise
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1010
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
1011
                izip(reader.iter_records(), pack_readv_requests):
1012
                raw_data = read_func(None)
1013
                # check the header only
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1014
                if output_lines is not None:
1015
                    output_lines(knit._parse_record(key[-1], raw_data)[0])
1016
                else:
1017
                    df, _ = knit._parse_record_header(key, raw_data)
1018
                    df.close()
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1019
                pos, size = writer.add_bytes_record(raw_data, names)
1020
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
1021
                pb.update("Copied record", record_index)
1022
                record_index += 1
1023
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1024
    def _copy_nodes_graph(self, index_map, writer, write_index,
3789.2.26 by John Arbash Meinel
Change the code so that we expect _reload_func to divert the flow by raising.
1025
        readv_group_iter, total_items, output_lines=False):
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1026
        """Copy knit nodes between packs.
1027
1028
        :param output_lines: Return lines present in the copied data as
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
1029
            an iterator of line,version_id.
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1030
        """
1031
        pb = ui.ui_factory.nested_progress_bar()
1032
        try:
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1033
            for result in self._do_copy_nodes_graph(index_map, writer,
3789.2.26 by John Arbash Meinel
Change the code so that we expect _reload_func to divert the flow by raising.
1034
                write_index, output_lines, pb, readv_group_iter, total_items):
3039.1.1 by Robert Collins
(robertc) Fix the text progress for pack to pack fetches. (Robert Collins).
1035
                yield result
3039.1.2 by Robert Collins
python2.4 'compatibility'.
1036
        except Exception:
3039.1.3 by Robert Collins
Document the try:except:else: rather than a finally: in pack_repo.._copy_nodes_graph.
1037
            # Python 2.4 does not permit try:finally: in a generator.
3039.1.2 by Robert Collins
python2.4 'compatibility'.
1038
            pb.finished()
1039
            raise
1040
        else:
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1041
            pb.finished()
1042
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1043
    def _do_copy_nodes_graph(self, index_map, writer, write_index,
3789.2.26 by John Arbash Meinel
Change the code so that we expect _reload_func to divert the flow by raising.
1044
        output_lines, pb, readv_group_iter, total_items):
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1045
        # for record verification
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.
1046
        knit = KnitVersionedFiles(None, None)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1047
        # for line extraction when requested (inventories only)
1048
        if output_lines:
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.
1049
            factory = KnitPlainFactory()
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1050
        record_index = 0
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1051
        pb.update("Copied record", record_index, total_items)
1052
        for index, readv_vector, node_vector in readv_group_iter:
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1053
            # copy the data
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
1054
            pack_obj = index_map[index]
1055
            transport, path = pack_obj.access_tuple()
3789.2.26 by John Arbash Meinel
Change the code so that we expect _reload_func to divert the flow by raising.
1056
            try:
1057
                reader = pack.make_readv_reader(transport, path, readv_vector)
1058
            except errors.NoSuchFile:
1059
                if self._reload_func is not None:
1060
                    self._reload_func()
1061
                raise
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1062
            for (names, read_func), (key, eol_flag, references) in \
1063
                izip(reader.iter_records(), node_vector):
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1064
                raw_data = read_func(None)
1065
                if output_lines:
1066
                    # read the entire thing
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.
1067
                    content, _ = knit._parse_record(key[-1], raw_data)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1068
                    if len(references[-1]) == 0:
1069
                        line_iterator = factory.get_fulltext_content(content)
1070
                    else:
1071
                        line_iterator = factory.get_linedelta_content(content)
1072
                    for line in line_iterator:
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.
1073
                        yield line, key
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1074
                else:
1075
                    # check the header only
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.
1076
                    df, _ = knit._parse_record_header(key, raw_data)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1077
                    df.close()
1078
                pos, size = writer.add_bytes_record(raw_data, names)
1079
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1080
                pb.update("Copied record", record_index)
1081
                record_index += 1
1082
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1083
    def _get_text_nodes(self):
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
1084
        text_index_map, text_indices = self._pack_map_and_index_list(
1085
            'text_index')
1086
        return text_index_map, self._index_contents(text_indices,
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1087
            self._text_filter)
1088
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1089
    def _least_readv_node_readv(self, nodes):
1090
        """Generate request groups for nodes using the least readv's.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1091
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1092
        :param nodes: An iterable of graph index nodes.
1093
        :return: Total node count and an iterator of the data needed to perform
1094
            readvs to obtain the data for nodes. Each item yielded by the
1095
            iterator is a tuple with:
1096
            index, readv_vector, node_vector. readv_vector is a list ready to
1097
            hand to the transport readv method, and node_vector is a list of
1098
            (key, eol_flag, references) for the the node retrieved by the
1099
            matching readv_vector.
1100
        """
1101
        # group by pack so we do one readv per pack
1102
        nodes = sorted(nodes)
1103
        total = len(nodes)
1104
        request_groups = {}
1105
        for index, key, value, references in nodes:
1106
            if index not in request_groups:
1107
                request_groups[index] = []
1108
            request_groups[index].append((key, value, references))
1109
        result = []
1110
        for index, items in request_groups.iteritems():
1111
            pack_readv_requests = []
1112
            for key, value, references in items:
1113
                # ---- KnitGraphIndex.get_position
1114
                bits = value[1:].split(' ')
1115
                offset, length = int(bits[0]), int(bits[1])
1116
                pack_readv_requests.append(
1117
                    ((offset, length), (key, value[0], references)))
1118
            # linear scan up the pack to maximum range combining.
1119
            pack_readv_requests.sort()
1120
            # split out the readv and the node data.
1121
            pack_readv = [readv for readv, node in pack_readv_requests]
1122
            node_vector = [node for readv, node in pack_readv_requests]
1123
            result.append((index, pack_readv, node_vector))
1124
        return total, result
1125
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1126
    def _log_copied_texts(self):
1127
        if 'pack' in debug.debug_flags:
1128
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
1129
                time.ctime(), self._pack_collection._upload_transport.base,
1130
                self.new_pack.random_name,
1131
                self.new_pack.text_index.key_count(),
1132
                time.time() - self.new_pack.start_time)
1133
1134
    def _process_inventory_lines(self, inv_lines):
1135
        """Use up the inv_lines generator and setup a text key filter."""
1136
        repo = self._pack_collection.repo
1137
        fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
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.
1138
            inv_lines, self.revision_keys)
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1139
        text_filter = []
1140
        for fileid, file_revids in fileid_revisions.iteritems():
1141
            text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
1142
        self._text_filter = text_filter
1143
3070.1.2 by John Arbash Meinel
Cleanup OptimizingPacker code according to my review feedback
1144
    def _revision_node_readv(self, revision_nodes):
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1145
        """Return the total revisions and the readv's to issue.
1146
1147
        :param revision_nodes: The revision index contents for the packs being
1148
            incorporated into the new pack.
1149
        :return: As per _least_readv_node_readv.
1150
        """
1151
        return self._least_readv_node_readv(revision_nodes)
1152
2951.2.8 by Robert Collins
Test that reconciling a repository can be done twice in a row.
1153
    def _use_pack(self, new_pack):
1154
        """Return True if new_pack should be used.
1155
1156
        :param new_pack: The pack that has just been created.
1157
        :return: True if the pack should be used.
1158
        """
1159
        return new_pack.data_inserted()
1160
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1161
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1162
class OptimisingPacker(Packer):
1163
    """A packer which spends more time to create better disk layouts."""
1164
3070.1.2 by John Arbash Meinel
Cleanup OptimizingPacker code according to my review feedback
1165
    def _revision_node_readv(self, revision_nodes):
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1166
        """Return the total revisions and the readv's to issue.
1167
1168
        This sort places revisions in topological order with the ancestors
1169
        after the children.
1170
1171
        :param revision_nodes: The revision index contents for the packs being
1172
            incorporated into the new pack.
1173
        :return: As per _least_readv_node_readv.
1174
        """
1175
        # build an ancestors dict
1176
        ancestors = {}
1177
        by_key = {}
1178
        for index, key, value, references in revision_nodes:
1179
            ancestors[key] = references[0]
1180
            by_key[key] = (index, value, references)
1181
        order = tsort.topo_sort(ancestors)
1182
        total = len(order)
1183
        # Single IO is pathological, but it will work as a starting point.
1184
        requests = []
1185
        for key in reversed(order):
1186
            index, value, references = by_key[key]
1187
            # ---- KnitGraphIndex.get_position
1188
            bits = value[1:].split(' ')
1189
            offset, length = int(bits[0]), int(bits[1])
1190
            requests.append(
1191
                (index, [(offset, length)], [(key, value[0], references)]))
1192
        # TODO: combine requests in the same index that are in ascending order.
1193
        return total, requests
1194
3777.5.4 by John Arbash Meinel
OptimisingPacker now sets the optimize flags for the indexes being built.
1195
    def open_pack(self):
1196
        """Open a pack for the pack we are creating."""
3777.5.5 by John Arbash Meinel
Up-call to the parent as suggested by Andrew.
1197
        new_pack = super(OptimisingPacker, self).open_pack()
1198
        # Turn on the optimization flags for all the index builders.
3777.5.4 by John Arbash Meinel
OptimisingPacker now sets the optimize flags for the indexes being built.
1199
        new_pack.revision_index.set_optimize(for_size=True)
1200
        new_pack.inventory_index.set_optimize(for_size=True)
1201
        new_pack.text_index.set_optimize(for_size=True)
1202
        new_pack.signature_index.set_optimize(for_size=True)
1203
        return new_pack
1204
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1205
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
1206
class ReconcilePacker(Packer):
1207
    """A packer which regenerates indices etc as it copies.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1208
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
1209
    This is used by ``bzr reconcile`` to cause parent text pointers to be
1210
    regenerated.
1211
    """
1212
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1213
    def _extra_init(self):
1214
        self._data_changed = False
1215
1216
    def _process_inventory_lines(self, inv_lines):
1217
        """Generate a text key reference map rather for reconciling with."""
1218
        repo = self._pack_collection.repo
1219
        refs = repo._find_text_key_references_from_xml_inventory_lines(
1220
            inv_lines)
1221
        self._text_refs = refs
1222
        # during reconcile we:
1223
        #  - convert unreferenced texts to full texts
1224
        #  - correct texts which reference a text not copied to be full texts
1225
        #  - copy all others as-is but with corrected parents.
1226
        #  - so at this point we don't know enough to decide what becomes a full
1227
        #    text.
1228
        self._text_filter = None
1229
1230
    def _copy_text_texts(self):
1231
        """generate what texts we should have and then copy."""
1232
        self.pb.update("Copying content texts", 3)
1233
        # we have three major tasks here:
1234
        # 1) generate the ideal index
1235
        repo = self._pack_collection.repo
3063.2.1 by Robert Collins
Solve reconciling erroring when multiple portions of a single delta chain are being reinserted.
1236
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1237
            _1, key, _2, refs in
3063.2.1 by Robert Collins
Solve reconciling erroring when multiple portions of a single delta chain are being reinserted.
1238
            self.new_pack.revision_index.iter_all_entries()])
1239
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1240
        # 2) generate a text_nodes list that contains all the deltas that can
1241
        #    be used as-is, with corrected parents.
1242
        ok_nodes = []
1243
        bad_texts = []
1244
        discarded_nodes = []
1245
        NULL_REVISION = _mod_revision.NULL_REVISION
1246
        text_index_map, text_nodes = self._get_text_nodes()
1247
        for node in text_nodes:
1248
            # 0 - index
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1249
            # 1 - key
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1250
            # 2 - value
1251
            # 3 - refs
1252
            try:
1253
                ideal_parents = tuple(ideal_index[node[1]])
1254
            except KeyError:
1255
                discarded_nodes.append(node)
1256
                self._data_changed = True
1257
            else:
1258
                if ideal_parents == (NULL_REVISION,):
1259
                    ideal_parents = ()
1260
                if ideal_parents == node[3][0]:
1261
                    # no change needed.
1262
                    ok_nodes.append(node)
1263
                elif ideal_parents[0:1] == node[3][0][0:1]:
1264
                    # the left most parent is the same, or there are no parents
1265
                    # today. Either way, we can preserve the representation as
1266
                    # long as we change the refs to be inserted.
1267
                    self._data_changed = True
1268
                    ok_nodes.append((node[0], node[1], node[2],
1269
                        (ideal_parents, node[3][1])))
1270
                    self._data_changed = True
1271
                else:
1272
                    # Reinsert this text completely
1273
                    bad_texts.append((node[1], ideal_parents))
1274
                    self._data_changed = True
1275
        # we're finished with some data.
1276
        del ideal_index
1277
        del text_nodes
3063.2.2 by Robert Collins
Review feedback.
1278
        # 3) bulk copy the ok data
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1279
        total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1280
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1281
            self.new_pack.text_index, readv_group_iter, total_items))
3063.2.1 by Robert Collins
Solve reconciling erroring when multiple portions of a single delta chain are being reinserted.
1282
        # 4) adhoc copy all the other texts.
1283
        # We have to topologically insert all texts otherwise we can fail to
1284
        # reconcile when parts of a single delta chain are preserved intact,
1285
        # and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1286
        # reinserted, and if d3 has incorrect parents it will also be
1287
        # reinserted. If we insert d3 first, d2 is present (as it was bulk
1288
        # copied), so we will try to delta, but d2 is not currently able to be
1289
        # extracted because it's basis d1 is not present. Topologically sorting
1290
        # addresses this. The following generates a sort for all the texts that
1291
        # are being inserted without having to reference the entire text key
1292
        # space (we only topo sort the revisions, which is smaller).
1293
        topo_order = tsort.topo_sort(ancestors)
1294
        rev_order = dict(zip(topo_order, range(len(topo_order))))
1295
        bad_texts.sort(key=lambda key:rev_order[key[0][1]])
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1296
        transaction = repo.get_transaction()
1297
        file_id_index = GraphIndexPrefixAdapter(
1298
            self.new_pack.text_index,
1299
            ('blank', ), 1,
1300
            add_nodes_callback=self.new_pack.text_index.add_nodes)
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.
1301
        data_access = _DirectPackAccess(
1302
                {self.new_pack.text_index:self.new_pack.access_tuple()})
1303
        data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1304
            self.new_pack.access_tuple())
1305
        output_texts = KnitVersionedFiles(
1306
            _KnitGraphIndex(self.new_pack.text_index,
1307
                add_callback=self.new_pack.text_index.add_nodes,
1308
                deltas=True, parents=True, is_locked=repo.is_locked),
1309
            data_access=data_access, max_delta_chain=200)
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1310
        for key, parent_keys in bad_texts:
1311
            # We refer to the new pack to delta data being output.
1312
            # A possible improvement would be to catch errors on short reads
1313
            # and only flush then.
1314
            self.new_pack.flush()
1315
            parents = []
1316
            for parent_key in parent_keys:
1317
                if parent_key[0] != key[0]:
1318
                    # Graph parents must match the fileid
1319
                    raise errors.BzrError('Mismatched key parent %r:%r' %
1320
                        (key, parent_keys))
1321
                parents.append(parent_key[1])
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
1322
            text_lines = osutils.split_lines(repo.texts.get_record_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.
1323
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
1324
            output_texts.add_lines(key, parent_keys, text_lines,
1325
                random_id=True, check_content=False)
3063.2.2 by Robert Collins
Review feedback.
1326
        # 5) check that nothing inserted has a reference outside the keyspace.
3830.3.5 by Martin Pool
GraphIndexBuilder shouldn't know references are for compression so rename
1327
        missing_text_keys = self.new_pack.text_index._external_references()
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1328
        if missing_text_keys:
3830.3.4 by Martin Pool
Move _external_compression_references onto the GraphIndexBuilder, and check them for inventories too
1329
            raise errors.BzrCheckError('Reference to missing compression parents %r'
3376.2.12 by Martin Pool
pyflakes corrections (thanks spiv)
1330
                % (missing_text_keys,))
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
1331
        self._log_copied_texts()
1332
2951.2.8 by Robert Collins
Test that reconciling a repository can be done twice in a row.
1333
    def _use_pack(self, new_pack):
1334
        """Override _use_pack to check for reconcile having changed content."""
1335
        # XXX: we might be better checking this at the copy time.
1336
        original_inventory_keys = set()
1337
        inv_index = self._pack_collection.inventory_index.combined_index
1338
        for entry in inv_index.iter_all_entries():
1339
            original_inventory_keys.add(entry[1])
1340
        new_inventory_keys = set()
1341
        for entry in new_pack.inventory_index.iter_all_entries():
1342
            new_inventory_keys.add(entry[1])
1343
        if new_inventory_keys != original_inventory_keys:
1344
            self._data_changed = True
1345
        return new_pack.data_inserted() and self._data_changed
1346
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1347
1348
class RepositoryPackCollection(object):
3517.4.4 by Martin Pool
Document RepositoryPackCollection._names
1349
    """Management of packs within a repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1350
3517.4.4 by Martin Pool
Document RepositoryPackCollection._names
1351
    :ivar _names: map of {pack_name: (index_size,)}
1352
    """
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1353
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1354
    pack_factory = NewPack
1355
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1356
    def __init__(self, repo, transport, index_transport, upload_transport,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1357
                 pack_transport, index_builder_class, index_class,
1358
                 use_chk_index):
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1359
        """Create a new RepositoryPackCollection.
1360
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1361
        :param transport: Addresses the repository base directory
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1362
            (typically .bzr/repository/).
1363
        :param index_transport: Addresses the directory containing indices.
1364
        :param upload_transport: Addresses the directory into which packs are written
1365
            while they're being created.
1366
        :param pack_transport: Addresses the directory of existing complete packs.
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1367
        :param index_builder_class: The index builder class to use.
1368
        :param index_class: The index class to use.
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1369
        :param use_chk_index: Whether to setup and manage a CHK index.
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1370
        """
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1371
        # XXX: This should call self.reset()
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1372
        self.repo = repo
1373
        self.transport = transport
1374
        self._index_transport = index_transport
1375
        self._upload_transport = upload_transport
1376
        self._pack_transport = pack_transport
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1377
        self._index_builder_class = index_builder_class
1378
        self._index_class = index_class
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1379
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
1380
            '.cix': 4}
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1381
        self.packs = []
1382
        # name:Pack mapping
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1383
        self._names = None
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1384
        self._packs_by_name = {}
1385
        # the previous pack-names content
1386
        self._packs_at_load = None
1387
        # when a pack is being created by this object, the state of that pack.
1388
        self._new_pack = None
1389
        # aggregated revision index data
4187.3.3 by Andrew Bennetts
In KnitVersionedFiles.insert_record_stream, flush the access object before expanding a delta into a fulltext.
1390
        flush = self._flush_new_pack
1391
        self.revision_index = AggregateIndex(self.reload_pack_names, flush)
1392
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
1393
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
1394
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1395
        if use_chk_index:
1396
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
1397
        else:
1398
            # used to determine if we're using a chk_index elsewhere.
1399
            self.chk_index = None
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1400
        # resumed packs
1401
        self._resumed_packs = []
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1402
1403
    def add_pack_to_memory(self, pack):
1404
        """Make a Pack object available to the repository to satisfy queries.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1405
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1406
        :param pack: A Pack object.
1407
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1408
        if pack.name in self._packs_by_name:
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1409
            raise AssertionError(
1410
                'pack %s already in _packs_by_name' % (pack.name,))
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1411
        self.packs.append(pack)
1412
        self._packs_by_name[pack.name] = pack
1413
        self.revision_index.add_index(pack.revision_index, pack)
1414
        self.inventory_index.add_index(pack.inventory_index, pack)
1415
        self.text_index.add_index(pack.text_index, pack)
1416
        self.signature_index.add_index(pack.signature_index, pack)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1417
        if self.chk_index is not None:
1418
            self.chk_index.add_index(pack.chk_index, pack)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1419
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1420
    def all_packs(self):
1421
        """Return a list of all the Pack objects this repository has.
1422
1423
        Note that an in-progress pack being created is not returned.
1424
1425
        :return: A list of Pack objects for all the packs in the repository.
1426
        """
1427
        result = []
1428
        for name in self.names():
1429
            result.append(self.get_pack_by_name(name))
1430
        return result
1431
1432
    def autopack(self):
1433
        """Pack the pack collection incrementally.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1434
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1435
        This will not attempt global reorganisation or recompression,
1436
        rather it will just ensure that the total number of packs does
1437
        not grow without bound. It uses the _max_pack_count method to
1438
        determine if autopacking is needed, and the pack_distribution
1439
        method to determine the number of revisions in each pack.
1440
1441
        If autopacking takes place then the packs name collection will have
1442
        been flushed to disk - packing requires updating the name collection
1443
        in synchronisation with certain steps. Otherwise the names collection
1444
        is not flushed.
1445
1446
        :return: True if packing took place.
1447
        """
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1448
        while True:
1449
            try:
1450
                return self._do_autopack()
1451
            except errors.RetryAutopack, e:
3789.2.22 by John Arbash Meinel
We need the Packer class to cleanup if it is getting a Retry it isn't handling.
1452
                # If we get a RetryAutopack exception, we should abort the
1453
                # current action, and retry.
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1454
                pass
1455
1456
    def _do_autopack(self):
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1457
        # XXX: Should not be needed when the management of indices is sane.
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1458
        total_revisions = self.revision_index.combined_index.key_count()
1459
        total_packs = len(self._names)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1460
        if self._max_pack_count(total_revisions) >= total_packs:
1461
            return False
1462
        # determine which packs need changing
1463
        pack_distribution = self.pack_distribution(total_revisions)
1464
        existing_packs = []
1465
        for pack in self.all_packs():
1466
            revision_count = pack.get_revision_count()
1467
            if revision_count == 0:
1468
                # revision less packs are not generated by normal operation,
1469
                # only by operations like sign-my-commits, and thus will not
1470
                # tend to grow rapdily or without bound like commit containing
1471
                # packs do - leave them alone as packing them really should
1472
                # group their data with the relevant commit, and that may
1473
                # involve rewriting ancient history - which autopack tries to
1474
                # avoid. Alternatively we could not group the data but treat
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1475
                # each of these as having a single revision, and thus add
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1476
                # one revision for each to the total revision count, to get
1477
                # a matching distribution.
1478
                continue
1479
            existing_packs.append((revision_count, pack))
1480
        pack_operations = self.plan_autopack_combinations(
1481
            existing_packs, pack_distribution)
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
1482
        num_new_packs = len(pack_operations)
1483
        num_old_packs = sum([len(po[1]) for po in pack_operations])
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
1484
        num_revs_affected = sum([po[0] for po in pack_operations])
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
1485
        mutter('Auto-packing repository %s, which has %d pack files, '
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
1486
            'containing %d revisions. Packing %d files into %d affecting %d'
3824.2.3 by John Arbash Meinel
Reorder the packs list after determining what packs
1487
            ' revisions', self, total_packs, total_revisions, num_old_packs,
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
1488
            num_new_packs, num_revs_affected)
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1489
        self._execute_pack_operations(pack_operations,
1490
                                      reload_func=self._restart_autopack)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1491
        mutter('Auto-packing repository %s completed', self)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1492
        return True
1493
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1494
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
1495
                                 reload_func=None):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1496
        """Execute a series of pack operations.
1497
1498
        :param pack_operations: A list of [revision_count, packs_to_combine].
3070.1.2 by John Arbash Meinel
Cleanup OptimizingPacker code according to my review feedback
1499
        :param _packer_class: The class of packer to use (default: Packer).
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1500
        :return: None.
1501
        """
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1502
        for revision_count, packs in pack_operations:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1503
            # we may have no-ops from the setup logic
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1504
            if len(packs) == 0:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1505
                continue
3789.2.22 by John Arbash Meinel
We need the Packer class to cleanup if it is getting a Retry it isn't handling.
1506
            packer = _packer_class(self, packs, '.autopack',
1507
                                   reload_func=reload_func)
1508
            try:
1509
                packer.pack()
1510
            except errors.RetryWithNewPacks:
1511
                # An exception is propagating out of this context, make sure
3789.2.23 by John Arbash Meinel
Clarify the comment.
1512
                # this packer has cleaned up. Packer() doesn't set its new_pack
1513
                # state into the RepositoryPackCollection object, so we only
1514
                # have access to it directly here.
3789.2.22 by John Arbash Meinel
We need the Packer class to cleanup if it is getting a Retry it isn't handling.
1515
                if packer.new_pack is not None:
1516
                    packer.new_pack.abort()
1517
                raise
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1518
            for pack in packs:
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
1519
                self._remove_pack_from_memory(pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1520
        # record the newly available packs and stop advertising the old
1521
        # packs
2948.1.1 by Robert Collins
* Obsolete packs are now cleaned up by pack and autopack operations.
1522
        self._save_pack_names(clear_obsolete_packs=True)
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1523
        # Move the old packs out of the way now they are no longer referenced.
1524
        for revision_count, packs in pack_operations:
1525
            self._obsolete_packs(packs)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1526
4187.3.3 by Andrew Bennetts
In KnitVersionedFiles.insert_record_stream, flush the access object before expanding a delta into a fulltext.
1527
    def _flush_new_pack(self):
1528
        if self._new_pack is not None:
1529
            self._new_pack.flush()
1530
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1531
    def lock_names(self):
1532
        """Acquire the mutex around the pack-names index.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1533
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1534
        This cannot be used in the middle of a read-only transaction on the
1535
        repository.
1536
        """
1537
        self.repo.control_files.lock_write()
1538
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1539
    def _already_packed(self):
1540
        """Is the collection already packed?"""
1541
        return len(self._names) < 2
1542
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1543
    def pack(self):
1544
        """Pack the pack collection totally."""
1545
        self.ensure_loaded()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1546
        total_packs = len(self._names)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1547
        if self._already_packed():
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1548
            # This is arguably wrong because we might not be optimal, but for
1549
            # now lets leave it in. (e.g. reconcile -> one pack. But not
1550
            # optimal.
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1551
            return
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1552
        total_revisions = self.revision_index.combined_index.key_count()
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1553
        # XXX: the following may want to be a class, to pack with a given
1554
        # policy.
1555
        mutter('Packing repository %s, which has %d pack files, '
1556
            'containing %d revisions into 1 packs.', self, total_packs,
1557
            total_revisions)
1558
        # determine which packs need changing
1559
        pack_distribution = [1]
1560
        pack_operations = [[0, []]]
1561
        for pack in self.all_packs():
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1562
            pack_operations[-1][0] += pack.get_revision_count()
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1563
            pack_operations[-1][1].append(pack)
3070.1.1 by Robert Collins
* ``bzr pack`` now orders revision texts in topological order, with newest
1564
        self._execute_pack_operations(pack_operations, OptimisingPacker)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1565
1566
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
2592.3.176 by Robert Collins
Various pack refactorings.
1567
        """Plan a pack operation.
1568
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1569
        :param existing_packs: The packs to pack. (A list of (revcount, Pack)
1570
            tuples).
2592.3.235 by Martin Pool
Review cleanups
1571
        :param pack_distribution: A list with the number of revisions desired
2592.3.176 by Robert Collins
Various pack refactorings.
1572
            in each pack.
1573
        """
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1574
        if len(existing_packs) <= len(pack_distribution):
1575
            return []
1576
        existing_packs.sort(reverse=True)
1577
        pack_operations = [[0, []]]
1578
        # plan out what packs to keep, and what to reorganise
1579
        while len(existing_packs):
1580
            # take the largest pack, and if its less than the head of the
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1581
            # distribution chart we will include its contents in the new pack
1582
            # for that position. If its larger, we remove its size from the
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1583
            # distribution chart
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1584
            next_pack_rev_count, next_pack = existing_packs.pop(0)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1585
            if next_pack_rev_count >= pack_distribution[0]:
1586
                # this is already packed 'better' than this, so we can
1587
                # not waste time packing it.
1588
                while next_pack_rev_count > 0:
1589
                    next_pack_rev_count -= pack_distribution[0]
1590
                    if next_pack_rev_count >= 0:
1591
                        # more to go
1592
                        del pack_distribution[0]
1593
                    else:
1594
                        # didn't use that entire bucket up
1595
                        pack_distribution[0] = -next_pack_rev_count
1596
            else:
1597
                # add the revisions we're going to add to the next output pack
1598
                pack_operations[-1][0] += next_pack_rev_count
1599
                # allocate this pack to the next pack sub operation
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1600
                pack_operations[-1][1].append(next_pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1601
                if pack_operations[-1][0] >= pack_distribution[0]:
1602
                    # this pack is used up, shift left.
1603
                    del pack_distribution[0]
1604
                    pack_operations.append([0, []])
3711.4.3 by John Arbash Meinel
Small cleanups from Robert
1605
        # Now that we know which pack files we want to move, shove them all
1606
        # into a single pack file.
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1607
        final_rev_count = 0
1608
        final_pack_list = []
1609
        for num_revs, pack_files in pack_operations:
1610
            final_rev_count += num_revs
1611
            final_pack_list.extend(pack_files)
1612
        if len(final_pack_list) == 1:
1613
            raise AssertionError('We somehow generated an autopack with a'
3711.4.3 by John Arbash Meinel
Small cleanups from Robert
1614
                ' single pack file being moved.')
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1615
            return []
1616
        return [[final_rev_count, final_pack_list]]
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1617
1618
    def ensure_loaded(self):
4145.1.4 by Robert Collins
Prevent regression to overhead of lock_read on pack repositories.
1619
        """Ensure we have read names from disk.
1620
1621
        :return: True if the disk names had not been previously read.
1622
        """
2592.3.214 by Robert Collins
Merge bzr.dev.
1623
        # NB: if you see an assertion error here, its probably access against
1624
        # an unlocked repo. Naughty.
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
1625
        if not self.repo.is_locked():
1626
            raise errors.ObjectNotLocked(self.repo)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1627
        if self._names is None:
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
1628
            self._names = {}
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1629
            self._packs_at_load = set()
1630
            for index, key, value in self._iter_disk_pack_index():
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
1631
                name = key[0]
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1632
                self._names[name] = self._parse_index_sizes(value)
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1633
                self._packs_at_load.add((key, value))
4145.1.4 by Robert Collins
Prevent regression to overhead of lock_read on pack repositories.
1634
            result = True
1635
        else:
1636
            result = False
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1637
        # populate all the metadata.
1638
        self.all_packs()
4145.1.4 by Robert Collins
Prevent regression to overhead of lock_read on pack repositories.
1639
        return result
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1640
1641
    def _parse_index_sizes(self, value):
1642
        """Parse a string of index sizes."""
1643
        return tuple([int(digits) for digits in value.split(' ')])
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
1644
2592.3.176 by Robert Collins
Various pack refactorings.
1645
    def get_pack_by_name(self, name):
1646
        """Get a Pack object by name.
1647
1648
        :param name: The name of the pack - e.g. '123456'
1649
        :return: A Pack object.
1650
        """
1651
        try:
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1652
            return self._packs_by_name[name]
2592.3.176 by Robert Collins
Various pack refactorings.
1653
        except KeyError:
1654
            rev_index = self._make_index(name, '.rix')
1655
            inv_index = self._make_index(name, '.iix')
1656
            txt_index = self._make_index(name, '.tix')
1657
            sig_index = self._make_index(name, '.six')
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1658
            if self.chk_index is not None:
1659
                chk_index = self._make_index(name, '.cix')
1660
            else:
1661
                chk_index = None
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1662
            result = ExistingPack(self._pack_transport, name, rev_index,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1663
                inv_index, txt_index, sig_index, chk_index)
2592.3.178 by Robert Collins
Add pack objects to the api for PackCollection.create_pack_from_packs.
1664
            self.add_pack_to_memory(result)
2592.3.176 by Robert Collins
Various pack refactorings.
1665
            return result
1666
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1667
    def _resume_pack(self, name):
1668
        """Get a suspended Pack object by name.
1669
1670
        :param name: The name of the pack - e.g. '123456'
1671
        :return: A Pack object.
1672
        """
4002.1.5 by Andrew Bennetts
Fix possible security issue with resuming write groups: make sure the token is well-formed so that it's not possible to steal a write group from another repo.
1673
        if not re.match('[a-f0-9]{32}', name):
1674
            # Tokens should be md5sums of the suspended pack file, i.e. 32 hex
1675
            # digits.
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
1676
            raise errors.UnresumableWriteGroup(
4002.1.5 by Andrew Bennetts
Fix possible security issue with resuming write groups: make sure the token is well-formed so that it's not possible to steal a write group from another repo.
1677
                self.repo, [name], 'Malformed write group token')
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1678
        try:
1679
            rev_index = self._make_index(name, '.rix', resume=True)
1680
            inv_index = self._make_index(name, '.iix', resume=True)
1681
            txt_index = self._make_index(name, '.tix', resume=True)
1682
            sig_index = self._make_index(name, '.six', resume=True)
1683
            result = ResumedPack(name, rev_index, inv_index, txt_index,
1684
                sig_index, self._upload_transport, self._pack_transport,
1685
                self._index_transport, self)
1686
        except errors.NoSuchFile, e:
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
1687
            raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1688
        self.add_pack_to_memory(result)
1689
        self._resumed_packs.append(result)
1690
        return result
1691
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
1692
    def allocate(self, a_new_pack):
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
1693
        """Allocate name in the list of packs.
1694
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
1695
        :param a_new_pack: A NewPack instance to be added to the collection of
1696
            packs for this repository.
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
1697
        """
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
1698
        self.ensure_loaded()
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
1699
        if a_new_pack.name in self._names:
2951.2.7 by Robert Collins
Raise an error on duplicate pack name allocation.
1700
            raise errors.BzrError(
1701
                'Pack %r already exists in %s' % (a_new_pack.name, self))
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1702
        self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
1703
        self.add_pack_to_memory(a_new_pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1704
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1705
    def _iter_disk_pack_index(self):
1706
        """Iterate over the contents of the pack-names index.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1707
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1708
        This is used when loading the list from disk, and before writing to
1709
        detect updates from others during our write operation.
1710
        :return: An iterator of the index contents.
1711
        """
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1712
        return self._index_class(self.transport, 'pack-names', None
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1713
                ).iter_all_entries()
1714
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1715
    def _make_index(self, name, suffix, resume=False):
2592.3.176 by Robert Collins
Various pack refactorings.
1716
        size_offset = self._suffix_offsets[suffix]
1717
        index_name = name + suffix
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
1718
        if resume:
1719
            transport = self._upload_transport
1720
            index_size = transport.stat(index_name).st_size
1721
        else:
1722
            transport = self._index_transport
1723
            index_size = self._names[name][size_offset]
1724
        return self._index_class(transport, index_name, index_size)
2592.5.5 by Martin Pool
Make RepositoryPackCollection remember the index transport, and responsible for getting a map of indexes
1725
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1726
    def _max_pack_count(self, total_revisions):
1727
        """Return the maximum number of packs to use for total revisions.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1728
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1729
        :param total_revisions: The total number of revisions in the
1730
            repository.
1731
        """
1732
        if not total_revisions:
1733
            return 1
1734
        digits = str(total_revisions)
1735
        result = 0
1736
        for digit in digits:
1737
            result += int(digit)
1738
        return result
1739
1740
    def names(self):
1741
        """Provide an order to the underlying names."""
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
1742
        return sorted(self._names.keys())
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1743
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1744
    def _obsolete_packs(self, packs):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1745
        """Move a number of packs which have been obsoleted out of the way.
1746
1747
        Each pack and its associated indices are moved out of the way.
1748
1749
        Note: for correctness this function should only be called after a new
1750
        pack names index has been written without these pack names, and with
1751
        the names of packs that contain the data previously available via these
1752
        packs.
1753
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1754
        :param packs: The packs to obsolete.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1755
        :param return: None.
1756
        """
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1757
        for pack in packs:
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
1758
            pack.pack_transport.rename(pack.file_name(),
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1759
                '../obsolete_packs/' + pack.file_name())
2592.3.226 by Martin Pool
formatting and docstrings
1760
            # TODO: Probably needs to know all possible indices for this pack
1761
            # - or maybe list the directory and move all indices matching this
2592.5.13 by Martin Pool
Clean up duplicate index_transport variables
1762
            # name whether we recognize it or not?
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1763
            suffixes = ['.iix', '.six', '.tix', '.rix']
1764
            if self.chk_index is not None:
1765
                suffixes.append('.cix')
1766
            for suffix in suffixes:
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1767
                self._index_transport.rename(pack.name + suffix,
1768
                    '../obsolete_packs/' + pack.name + suffix)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1769
1770
    def pack_distribution(self, total_revisions):
1771
        """Generate a list of the number of revisions to put in each pack.
1772
1773
        :param total_revisions: The total number of revisions in the
1774
            repository.
1775
        """
1776
        if total_revisions == 0:
1777
            return [0]
1778
        digits = reversed(str(total_revisions))
1779
        result = []
1780
        for exponent, count in enumerate(digits):
1781
            size = 10 ** exponent
1782
            for pos in range(int(count)):
1783
                result.append(size)
1784
        return list(reversed(result))
1785
2592.5.12 by Martin Pool
Move pack_transport and pack_name onto RepositoryPackCollection
1786
    def _pack_tuple(self, name):
1787
        """Return a tuple with the transport and file name for a pack name."""
1788
        return self._pack_transport, name + '.pack'
1789
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
1790
    def _remove_pack_from_memory(self, pack):
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1791
        """Remove pack from the packs accessed by this repository.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1792
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1793
        Only affects memory state, until self._save_pack_names() is invoked.
1794
        """
1795
        self._names.pop(pack.name)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1796
        self._packs_by_name.pop(pack.name)
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1797
        self._remove_pack_indices(pack)
3794.3.1 by John Arbash Meinel
In _remove_pack_from_memory, also remove the object from the PackCollection.packs list.
1798
        self.packs.remove(pack)
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1799
1800
    def _remove_pack_indices(self, pack):
1801
        """Remove the indices for pack from the aggregated indices."""
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1802
        self.revision_index.remove_index(pack.revision_index, pack)
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1803
        self.inventory_index.remove_index(pack.inventory_index, pack)
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1804
        self.text_index.remove_index(pack.text_index, pack)
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
1805
        self.signature_index.remove_index(pack.signature_index, pack)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1806
        if self.chk_index is not None:
1807
            self.chk_index.remove_index(pack.chk_index, pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1808
1809
    def reset(self):
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1810
        """Clear all cached data."""
1811
        # cached revision data
1812
        self.repo._revision_knit = None
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1813
        self.revision_index.clear()
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1814
        # cached signature data
1815
        self.repo._signature_knit = None
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
1816
        self.signature_index.clear()
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1817
        # cached file text data
1818
        self.text_index.clear()
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1819
        self.repo._text_knit = None
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1820
        # cached inventory data
1821
        self.inventory_index.clear()
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1822
        # cached chk data
1823
        if self.chk_index is not None:
1824
            self.chk_index.clear()
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
1825
        # remove the open pack
1826
        self._new_pack = None
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1827
        # information about packs.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1828
        self._names = None
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
1829
        self.packs = []
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1830
        self._packs_by_name = {}
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1831
        self._packs_at_load = None
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1832
2592.3.237 by Martin Pool
Rename RepositoryPackCollection.release_names to _unlock_names
1833
    def _unlock_names(self):
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1834
        """Release the mutex around the pack-names index."""
1835
        self.repo.control_files.unlock()
1836
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1837
    def _diff_pack_names(self):
1838
        """Read the pack names from disk, and compare it to the one in memory.
1839
1840
        :return: (disk_nodes, deleted_nodes, new_nodes)
1841
            disk_nodes    The final set of nodes that should be referenced
1842
            deleted_nodes Nodes which have been removed from when we started
1843
            new_nodes     Nodes that are newly introduced
1844
        """
1845
        # load the disk nodes across
1846
        disk_nodes = set()
1847
        for index, key, value in self._iter_disk_pack_index():
1848
            disk_nodes.add((key, value))
1849
1850
        # do a two-way diff against our original content
1851
        current_nodes = set()
1852
        for name, sizes in self._names.iteritems():
1853
            current_nodes.add(
1854
                ((name, ), ' '.join(str(size) for size in sizes)))
1855
1856
        # Packs no longer present in the repository, which were present when we
1857
        # locked the repository
1858
        deleted_nodes = self._packs_at_load - current_nodes
1859
        # Packs which this process is adding
1860
        new_nodes = current_nodes - self._packs_at_load
1861
1862
        # Update the disk_nodes set to include the ones we are adding, and
1863
        # remove the ones which were removed by someone else
1864
        disk_nodes.difference_update(deleted_nodes)
1865
        disk_nodes.update(new_nodes)
1866
1867
        return disk_nodes, deleted_nodes, new_nodes
1868
1869
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1870
        """Given the correct set of pack files, update our saved info.
1871
1872
        :return: (removed, added, modified)
1873
            removed     pack names removed from self._names
1874
            added       pack names added to self._names
1875
            modified    pack names that had changed value
1876
        """
1877
        removed = []
1878
        added = []
1879
        modified = []
1880
        ## self._packs_at_load = disk_nodes
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1881
        new_names = dict(disk_nodes)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1882
        # drop no longer present nodes
1883
        for pack in self.all_packs():
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1884
            if (pack.name,) not in new_names:
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1885
                removed.append(pack.name)
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
1886
                self._remove_pack_from_memory(pack)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1887
        # add new nodes/refresh existing ones
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1888
        for key, value in disk_nodes:
1889
            name = key[0]
1890
            sizes = self._parse_index_sizes(value)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1891
            if name in self._names:
1892
                # existing
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1893
                if sizes != self._names[name]:
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1894
                    # the pack for name has had its indices replaced - rare but
1895
                    # important to handle. XXX: probably can never happen today
1896
                    # because the three-way merge code above does not handle it
1897
                    # - you may end up adding the same key twice to the new
1898
                    # disk index because the set values are the same, unless
1899
                    # the only index shows up as deleted by the set difference
1900
                    # - which it may. Until there is a specific test for this,
1901
                    # assume its broken. RBC 20071017.
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
1902
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1903
                    self._names[name] = sizes
1904
                    self.get_pack_by_name(name)
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1905
                    modified.append(name)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1906
            else:
1907
                # new
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
1908
                self._names[name] = sizes
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1909
                self.get_pack_by_name(name)
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1910
                added.append(name)
1911
        return removed, added, modified
1912
1913
    def _save_pack_names(self, clear_obsolete_packs=False):
1914
        """Save the list of packs.
1915
1916
        This will take out the mutex around the pack names list for the
1917
        duration of the method call. If concurrent updates have been made, a
1918
        three-way merge between the current list and the current in memory list
1919
        is performed.
1920
1921
        :param clear_obsolete_packs: If True, clear out the contents of the
1922
            obsolete_packs directory.
1923
        """
1924
        self.lock_names()
1925
        try:
1926
            builder = self._index_builder_class()
1927
            disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1928
            # TODO: handle same-name, index-size-changes here -
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1929
            # e.g. use the value from disk, not ours, *unless* we're the one
1930
            # changing it.
1931
            for key, value in disk_nodes:
1932
                builder.add_node(key, value)
1933
            self.transport.put_file('pack-names', builder.finish(),
1934
                mode=self.repo.bzrdir._get_file_mode())
1935
            # move the baseline forward
1936
            self._packs_at_load = disk_nodes
1937
            if clear_obsolete_packs:
1938
                self._clear_obsolete_packs()
1939
        finally:
1940
            self._unlock_names()
1941
        # synchronise the memory packs list with what we just wrote:
1942
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1943
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1944
    def reload_pack_names(self):
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1945
        """Sync our pack listing with what is present in the repository.
1946
1947
        This should be called when we find out that something we thought was
1948
        present is now missing. This happens when another process re-packs the
1949
        repository, etc.
4145.1.4 by Robert Collins
Prevent regression to overhead of lock_read on pack repositories.
1950
1951
        :return: True if the in-memory list of packs has been altered at all.
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1952
        """
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
1953
        # The ensure_loaded call is to handle the case where the first call
1954
        # made involving the collection was to reload_pack_names, where we 
1955
        # don't have a view of disk contents. Its a bit of a bandaid, and
1956
        # causes two reads of pack-names, but its a rare corner case not struck
1957
        # with regular push/pull etc.
4145.1.4 by Robert Collins
Prevent regression to overhead of lock_read on pack repositories.
1958
        first_read = self.ensure_loaded()
1959
        if first_read:
1960
            return True
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1961
        # out the new value.
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1962
        disk_nodes, _, _ = self._diff_pack_names()
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1963
        self._packs_at_load = disk_nodes
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1964
        (removed, added,
1965
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1966
        if removed or added or modified:
1967
            return True
1968
        return False
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1969
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1970
    def _restart_autopack(self):
1971
        """Reload the pack names list, and restart the autopack code."""
1972
        if not self.reload_pack_names():
1973
            # Re-raise the original exception, because something went missing
1974
            # and a restart didn't find it
1975
            raise
3789.2.27 by John Arbash Meinel
Add some context information to the Retry exceptions.
1976
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1977
3446.2.1 by Martin Pool
Failure to delete an obsolete pack file should not be fatal.
1978
    def _clear_obsolete_packs(self):
1979
        """Delete everything from the obsolete-packs directory.
1980
        """
1981
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
1982
        for filename in obsolete_pack_transport.list_dir('.'):
1983
            try:
1984
                obsolete_pack_transport.delete(filename)
1985
            except (errors.PathError, errors.TransportError), e:
1986
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
1987
2592.3.202 by Robert Collins
Move write stream management into NewPack.
1988
    def _start_write_group(self):
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1989
        # Do not permit preparation for writing if we're not in a 'write lock'.
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1990
        if not self.repo.is_write_locked():
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1991
            raise errors.NotWriteLocked(self)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1992
        self._new_pack = self.pack_factory(self, upload_suffix='.pack',
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
1993
            file_mode=self.repo.bzrdir._get_file_mode())
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1994
        # allow writing: queue writes to a new index
1995
        self.revision_index.add_writable_index(self._new_pack.revision_index,
1996
            self._new_pack)
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1997
        self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1998
            self._new_pack)
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1999
        self.text_index.add_writable_index(self._new_pack.text_index,
2000
            self._new_pack)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2001
        self._new_pack.text_index.set_optimize(combine_backing_indices=False)
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
2002
        self.signature_index.add_writable_index(self._new_pack.signature_index,
2003
            self._new_pack)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2004
        if self.chk_index is not None:
2005
            self.chk_index.add_writable_index(self._new_pack.chk_index,
2006
                self._new_pack)
2007
            self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
2008
            self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2009
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.
2010
        self.repo.inventories._index._add_callback = self.inventory_index.add_callback
2011
        self.repo.revisions._index._add_callback = self.revision_index.add_callback
2012
        self.repo.signatures._index._add_callback = self.signature_index.add_callback
2013
        self.repo.texts._index._add_callback = self.text_index.add_callback
2592.5.9 by Martin Pool
Move some more bits that seem to belong in RepositoryPackCollection into there
2014
2592.5.8 by Martin Pool
Delegate abort_write_group to RepositoryPackCollection
2015
    def _abort_write_group(self):
2016
        # FIXME: just drop the transient index.
2017
        # forget what names there are
3163.1.2 by Martin Pool
RepositoryPackCollection._abort_write_group should check it actually has a new pack before aborting (#180208)
2018
        if self._new_pack is not None:
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
2019
            try:
2020
                self._new_pack.abort()
2021
            finally:
3830.3.21 by John Arbash Meinel
Merge in bzr.dev 3845 and handle the trivial conflicts.
2022
                # XXX: If we aborted while in the middle of finishing the write
2023
                # group, _remove_pack_indices can fail because the indexes are
2024
                # already gone.  If they're not there we shouldn't fail in this
2025
                # case.  -- mbp 20081113
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
2026
                self._remove_pack_indices(self._new_pack)
2027
                self._new_pack = None
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2028
        for resumed_pack in self._resumed_packs:
2029
            try:
2030
                resumed_pack.abort()
2031
            finally:
2032
                # See comment in previous finally block.
4002.1.12 by Andrew Bennetts
Add another test, fix the code so it passes, and remove some cruft.
2033
                try:
2034
                    self._remove_pack_indices(resumed_pack)
2035
                except KeyError:
2036
                    pass
2037
        del self._resumed_packs[:]
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
2038
        self.repo._text_knit = None
2592.5.6 by Martin Pool
Move pack repository start_write_group to pack collection object
2039
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2040
    def _remove_resumed_pack_indices(self):
2041
        for resumed_pack in self._resumed_packs:
2042
            self._remove_pack_indices(resumed_pack)
2043
        del self._resumed_packs[:]
2044
2592.5.7 by Martin Pool
move commit_write_group to RepositoryPackCollection
2045
    def _commit_write_group(self):
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
2046
        all_missing = set()
2047
        for prefix, versioned_file in (
2048
                ('revisions', self.repo.revisions),
2049
                ('inventories', self.repo.inventories),
2050
                ('texts', self.repo.texts),
2051
                ('signatures', self.repo.signatures),
2052
                ):
4002.1.9 by Andrew Bennetts
Merge VersionedFiles.insert-record-stream.partial from Robert.
2053
            missing = versioned_file.get_missing_compression_parent_keys()
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
2054
            all_missing.update([(prefix,) + key for key in missing])
2055
        if all_missing:
2056
            raise errors.BzrCheckError(
2057
                "Repository %s has missing compression parent(s) %r "
2058
                 % (self.repo, sorted(all_missing)))
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
2059
        self._remove_pack_indices(self._new_pack)
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2060
        should_autopack = False
2592.3.198 by Robert Collins
Factor out data_inserted to reduce code duplication in detecting empty packs.
2061
        if self._new_pack.data_inserted():
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
2062
            # get all the data to disk and read to use
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
2063
            self._new_pack.finish()
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
2064
            self.allocate(self._new_pack)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
2065
            self._new_pack = None
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2066
            should_autopack = True
2067
        else:
2068
            self._new_pack.abort()
2069
            self._new_pack = None
2070
        for resumed_pack in self._resumed_packs:
2071
            # XXX: this is a pretty ugly way to turn the resumed pack into a
2072
            # properly committed pack.
2073
            self._names[resumed_pack.name] = None
2074
            self._remove_pack_from_memory(resumed_pack)
2075
            resumed_pack.finish()
2076
            self.allocate(resumed_pack)
2077
            should_autopack = True
2078
        del self._resumed_packs[:]
2079
        if should_autopack:
2592.5.7 by Martin Pool
move commit_write_group to RepositoryPackCollection
2080
            if not self.autopack():
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
2081
                # when autopack takes no steps, the names list is still
2082
                # unsaved.
2592.5.10 by Martin Pool
Rename RepositoryPackCollection.save to _save_pack_names
2083
                self._save_pack_names()
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2084
        self.repo._text_knit = None
2085
2086
    def _suspend_write_group(self):
2087
        tokens = [pack.name for pack in self._resumed_packs]
2088
        self._remove_pack_indices(self._new_pack)
2089
        if self._new_pack.data_inserted():
2090
            # get all the data to disk and read to use
2091
            self._new_pack.finish(suspend=True)
2092
            tokens.append(self._new_pack.name)
2093
            self._new_pack = None
2592.5.7 by Martin Pool
move commit_write_group to RepositoryPackCollection
2094
        else:
2592.3.202 by Robert Collins
Move write stream management into NewPack.
2095
            self._new_pack.abort()
2951.1.1 by Robert Collins
(robertc) Fix data-refresh logic for packs not to refresh mid-transaction when a names write lock is held. (Robert Collins)
2096
            self._new_pack = None
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2097
        self._remove_resumed_pack_indices()
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
2098
        self.repo._text_knit = None
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2099
        return tokens
2100
2101
    def _resume_write_group(self, tokens):
2102
        for token in tokens:
2103
            self._resume_pack(token)
2592.5.8 by Martin Pool
Delegate abort_write_group to RepositoryPackCollection
2104
2105
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2106
class KnitPackRepository(KnitRepository):
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
2107
    """Repository with knit objects stored inside pack containers.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2108
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
2109
    The layering for a KnitPackRepository is:
2110
2111
    Graph        |  HPSS    | Repository public layer |
2112
    ===================================================
2113
    Tuple based apis below, string based, and key based apis above
2114
    ---------------------------------------------------
2115
    KnitVersionedFiles
2116
      Provides .texts, .revisions etc
2117
      This adapts the N-tuple keys to physical knit records which only have a
2118
      single string identifier (for historical reasons), which in older formats
2119
      was always the revision_id, and in the mapped code for packs is always
2120
      the last element of key tuples.
2121
    ---------------------------------------------------
2122
    GraphIndex
2123
      A separate GraphIndex is used for each of the
2124
      texts/inventories/revisions/signatures contained within each individual
2125
      pack file. The GraphIndex layer works in N-tuples and is unaware of any
2126
      semantic value.
2127
    ===================================================
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2128
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
2129
    """
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2130
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.
2131
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2132
        _serializer):
2133
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2134
            _commit_builder_class, _serializer)
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2135
        index_transport = self._transport.clone('indices')
3350.6.5 by Robert Collins
Update to bzr.dev.
2136
        self._pack_collection = RepositoryPackCollection(self, self._transport,
2592.5.11 by Martin Pool
Move upload_transport from pack repositories to the pack collection
2137
            index_transport,
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
2138
            self._transport.clone('upload'),
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2139
            self._transport.clone('packs'),
2140
            _format.index_builder_class,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2141
            _format.index_class,
2142
            use_chk_index=self._format.supports_chks,
2143
            )
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.
2144
        self.inventories = KnitVersionedFiles(
2145
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2146
                add_callback=self._pack_collection.inventory_index.add_callback,
2147
                deltas=True, parents=True, is_locked=self.is_locked),
2148
            data_access=self._pack_collection.inventory_index.data_access,
2149
            max_delta_chain=200)
2150
        self.revisions = KnitVersionedFiles(
2151
            _KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2152
                add_callback=self._pack_collection.revision_index.add_callback,
2153
                deltas=False, parents=True, is_locked=self.is_locked),
2154
            data_access=self._pack_collection.revision_index.data_access,
2155
            max_delta_chain=0)
2156
        self.signatures = KnitVersionedFiles(
2157
            _KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2158
                add_callback=self._pack_collection.signature_index.add_callback,
2159
                deltas=False, parents=False, is_locked=self.is_locked),
2160
            data_access=self._pack_collection.signature_index.data_access,
2161
            max_delta_chain=0)
2162
        self.texts = KnitVersionedFiles(
2163
            _KnitGraphIndex(self._pack_collection.text_index.combined_index,
2164
                add_callback=self._pack_collection.text_index.add_callback,
2165
                deltas=True, parents=True, is_locked=self.is_locked),
2166
            data_access=self._pack_collection.text_index.data_access,
2167
            max_delta_chain=200)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2168
        if _format.supports_chks:
2169
            # No graph, no compression:- references from chks are between
2170
            # different objects not temporal versions of the same; and without
2171
            # some sort of temporal structure knit compression will just fail.
2172
            self.chk_bytes = KnitVersionedFiles(
2173
                _KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2174
                    add_callback=self._pack_collection.chk_index.add_callback,
2175
                    deltas=False, parents=False, is_locked=self.is_locked),
2176
                data_access=self._pack_collection.chk_index.data_access,
2177
                max_delta_chain=0)
2178
        else:
2179
            self.chk_bytes = None
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2180
        # True when the repository object is 'write locked' (as opposed to the
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2181
        # physical lock only taken out around changes to the pack-names list.)
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2182
        # Another way to represent this would be a decorator around the control
2183
        # files object that presents logical locks as physical ones - if this
2184
        # gets ugly consider that alternative design. RBC 20071011
2185
        self._write_lock_count = 0
2186
        self._transaction = None
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
2187
        # for tests
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
2188
        self._reconcile_does_inventory_gc = True
2951.2.9 by Robert Collins
* ``pack-0.92`` repositories can now be reconciled.
2189
        self._reconcile_fixes_text_parents = True
2951.1.3 by Robert Collins
Partial support for native reconcile with packs.
2190
        self._reconcile_backsup_inventory = False
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2191
3575.3.1 by Andrew Bennetts
Deprecate knit repositories.
2192
    def _warn_if_deprecated(self):
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2193
        # This class isn't deprecated, but one sub-format is
2194
        if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
3606.10.3 by John Arbash Meinel
When warning give an exact upgrade request.
2195
            from bzrlib import repository
2196
            if repository._deprecation_warning_done:
2197
                return
2198
            repository._deprecation_warning_done = True
2199
            warning("Format %s for %s is deprecated - please use"
2200
                    " 'bzr upgrade --1.6.1-rich-root'"
2201
                    % (self._format, self.bzrdir.transport.base))
3575.3.1 by Andrew Bennetts
Deprecate knit repositories.
2202
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2203
    def _abort_write_group(self):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
2204
        self._pack_collection._abort_write_group()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2205
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2206
    def _find_inconsistent_revision_parents(self):
2207
        """Find revisions with incorrectly cached parents.
2208
2209
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
2210
            parents-in-revision).
2211
        """
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
2212
        if not self.is_locked():
2213
            raise errors.ObjectNotLocked(self)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2214
        pb = ui.ui_factory.nested_progress_bar()
2951.1.11 by Robert Collins
Do not try to use try:finally: around a yield for python 2.4.
2215
        result = []
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2216
        try:
2217
            revision_nodes = self._pack_collection.revision_index \
2218
                .combined_index.iter_all_entries()
2219
            index_positions = []
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2220
            # Get the cached index values for all revisions, and also the
2221
            # location in each index of the revision text so we can perform
2222
            # linear IO.
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2223
            for index, key, value, refs in revision_nodes:
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2224
                node = (index, key, value, refs)
2225
                index_memo = self.revisions._index._node_to_position(node)
2226
                if index_memo[0] != index:
2227
                    raise AssertionError('%r != %r' % (index_memo[0], index))
2228
                index_positions.append((index_memo, key[0],
2229
                                       tuple(parent[0] for parent in refs[0])))
4103.3.2 by Martin Pool
Remove trailing punctuation from progress messages
2230
                pb.update("Reading revision index", 0, 0)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2231
            index_positions.sort()
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2232
            batch_size = 1000
2233
            pb.update("Checking cached revision graph", 0,
2234
                      len(index_positions))
2235
            for offset in xrange(0, len(index_positions), 1000):
4103.3.2 by Martin Pool
Remove trailing punctuation from progress messages
2236
                pb.update("Checking cached revision graph", offset)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2237
                to_query = index_positions[offset:offset + batch_size]
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2238
                if not to_query:
2239
                    break
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2240
                rev_ids = [item[1] for item in to_query]
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2241
                revs = self.get_revisions(rev_ids)
2242
                for revision, item in zip(revs, to_query):
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2243
                    index_parents = item[2]
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2244
                    rev_parents = tuple(revision.parent_ids)
2245
                    if index_parents != rev_parents:
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2246
                        result.append((revision.revision_id, index_parents,
2247
                                       rev_parents))
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2248
        finally:
2249
            pb.finished()
2951.1.11 by Robert Collins
Do not try to use try:finally: around a yield for python 2.4.
2250
        return result
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
2251
2592.3.216 by Robert Collins
Implement get_parents and _make_parents_provider for Pack repositories.
2252
    def _make_parents_provider(self):
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
2253
        return graph.CachingParentsProvider(self)
2592.3.216 by Robert Collins
Implement get_parents and _make_parents_provider for Pack repositories.
2254
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2255
    def _refresh_data(self):
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
2256
        if not self.is_locked():
2257
            return
2258
        self._pack_collection.reload_pack_names()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2259
2260
    def _start_write_group(self):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
2261
        self._pack_collection._start_write_group()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2262
2263
    def _commit_write_group(self):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
2264
        return self._pack_collection._commit_write_group()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2265
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
2266
    def suspend_write_group(self):
2267
        # XXX check self._write_group is self.get_transaction()?
2268
        tokens = self._pack_collection._suspend_write_group()
2269
        self._write_group = None
2270
        return tokens
2271
2272
    def _resume_write_group(self, tokens):
2273
        self._start_write_group()
2274
        self._pack_collection._resume_write_group(tokens)
2275
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2276
    def get_transaction(self):
2277
        if self._write_lock_count:
2278
            return self._transaction
2279
        else:
2280
            return self.control_files.get_transaction()
2281
2282
    def is_locked(self):
2283
        return self._write_lock_count or self.control_files.is_locked()
2284
2285
    def is_write_locked(self):
2286
        return self._write_lock_count
2287
2288
    def lock_write(self, token=None):
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
2289
        locked = self.is_locked()
2290
        if not self._write_lock_count and locked:
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2291
            raise errors.ReadOnlyError(self)
2292
        self._write_lock_count += 1
2293
        if self._write_lock_count == 1:
2294
            self._transaction = transactions.WriteTransaction()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2295
            for repo in self._fallback_repositories:
2296
                # Writes don't affect fallback repos
2297
                repo.lock_read()
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
2298
        if not locked:
2299
            self._refresh_data()
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2300
2301
    def lock_read(self):
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
2302
        locked = self.is_locked()
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2303
        if self._write_lock_count:
2304
            self._write_lock_count += 1
2305
        else:
2306
            self.control_files.lock_read()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2307
            for repo in self._fallback_repositories:
2308
                # Writes don't affect fallback repos
2309
                repo.lock_read()
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
2310
        if not locked:
2311
            self._refresh_data()
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2312
2313
    def leave_lock_in_place(self):
2314
        # not supported - raise an error
2315
        raise NotImplementedError(self.leave_lock_in_place)
2316
2317
    def dont_leave_lock_in_place(self):
2318
        # not supported - raise an error
2319
        raise NotImplementedError(self.dont_leave_lock_in_place)
2320
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2321
    @needs_write_lock
2322
    def pack(self):
2323
        """Compress the data within the repository.
2324
2325
        This will pack all the data to a single pack. In future it may
2326
        recompress deltas or do other such expensive operations.
2327
        """
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
2328
        self._pack_collection.pack()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2329
2330
    @needs_write_lock
2331
    def reconcile(self, other=None, thorough=False):
2332
        """Reconcile this repository."""
2333
        from bzrlib.reconcile import PackReconciler
2334
        reconciler = PackReconciler(self, thorough=thorough)
2335
        reconciler.reconcile()
2336
        return reconciler
2337
4245.1.1 by Ian Clatworthy
minor test clean-ups & _reconcile_pack API
2338
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
2339
        packer = ReconcilePacker(collection, packs, extension, revs)
2340
        return packer.pack(pb)
2341
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2342
    def unlock(self):
2343
        if self._write_lock_count == 1 and self._write_group is not None:
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
2344
            self.abort_write_group()
2345
            self._transaction = None
2346
            self._write_lock_count = 0
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2347
            raise errors.BzrError(
2592.3.244 by Martin Pool
unlock while in a write group now aborts the write group, unlocks, and errors.
2348
                'Must end write group before releasing write lock on %s'
2349
                % self)
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2350
        if self._write_lock_count:
2351
            self._write_lock_count -= 1
2352
            if not self._write_lock_count:
2353
                transaction = self._transaction
2354
                self._transaction = None
2355
                transaction.finish()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2356
                for repo in self._fallback_repositories:
2357
                    repo.unlock()
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2358
        else:
2359
            self.control_files.unlock()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2360
            for repo in self._fallback_repositories:
2361
                repo.unlock()
2362
2363
2364
class RepositoryFormatPack(MetaDirRepositoryFormat):
2365
    """Format logic for pack structured repositories.
2366
2367
    This repository format has:
2368
     - a list of packs in pack-names
2369
     - packs in packs/NAME.pack
2370
     - indices in indices/NAME.{iix,six,tix,rix}
2371
     - knit deltas in the packs, knit indices mapped to the indices.
2372
     - thunk objects to support the knits programming API.
2373
     - a format marker of its own
2374
     - an optional 'shared-storage' flag
2375
     - an optional 'no-working-trees' flag
2376
     - a LockDir lock
2377
    """
2378
2379
    # Set this attribute in derived classes to control the repository class
2380
    # created by open and initialize.
2381
    repository_class = None
2382
    # Set this attribute in derived classes to control the
2383
    # _commit_builder_class that the repository objects will have passed to
2384
    # their constructor.
2385
    _commit_builder_class = None
2386
    # Set this attribute in derived clases to control the _serializer that the
2387
    # repository objects will have passed to their constructor.
2388
    _serializer = None
2949.1.5 by Robert Collins
Packs support ghosts.
2389
    # Packs are not confused by ghosts.
2390
    supports_ghosts = True
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2391
    # External references are not supported in pack repositories yet.
2392
    supports_external_lookups = False
4246.2.1 by Ian Clatworthy
supports_chks flag on repo formats & log tuning
2393
    # Most pack formats do not use chk lookups.
2394
    supports_chks = False
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2395
    # What index classes to use
2396
    index_builder_class = None
2397
    index_class = None
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
2398
    _fetch_uses_deltas = True
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2399
    fast_deltas = False
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2400
2401
    def initialize(self, a_bzrdir, shared=False):
2402
        """Create a pack based repository.
2403
2404
        :param a_bzrdir: bzrdir to contain the new repository; must already
2405
            be initialized.
2406
        :param shared: If true the repository will be initialized as a shared
2407
                       repository.
2408
        """
2409
        mutter('creating repository in %s.', a_bzrdir.transport.base)
2410
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2411
        builder = self.index_builder_class()
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2412
        files = [('pack-names', builder.finish())]
2413
        utf8_files = [('format', self.get_format_string())]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2414
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2415
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
2416
        return self.open(a_bzrdir=a_bzrdir, _found=True)
2417
2418
    def open(self, a_bzrdir, _found=False, _override_transport=None):
2419
        """See RepositoryFormat.open().
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2420
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2421
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
2422
                                    repository at a slightly different url
2423
                                    than normal. I.e. during 'upgrade'.
2424
        """
2425
        if not _found:
2426
            format = RepositoryFormat.find_format(a_bzrdir)
2427
        if _override_transport is not None:
2428
            repo_transport = _override_transport
2429
        else:
2430
            repo_transport = a_bzrdir.get_repository_transport(None)
2431
        control_files = lockable_files.LockableFiles(repo_transport,
2432
                                'lock', lockdir.LockDir)
2433
        return self.repository_class(_format=self,
2434
                              a_bzrdir=a_bzrdir,
2435
                              control_files=control_files,
2436
                              _commit_builder_class=self._commit_builder_class,
2437
                              _serializer=self._serializer)
2438
2439
2440
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2441
    """A no-subtrees parameterized Pack repository.
2442
2443
    This format was introduced in 0.92.
2444
    """
2445
2446
    repository_class = KnitPackRepository
2447
    _commit_builder_class = PackCommitBuilder
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.
2448
    @property
2449
    def _serializer(self):
2450
        return xml5.serializer_v5
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2451
    # What index classes to use
2452
    index_builder_class = InMemoryGraphIndex
2453
    index_class = GraphIndex
3221.12.13 by Robert Collins
Implement generic stacking rather than pack-internals based stacking.
2454
2455
    def _get_matching_bzrdir(self):
2456
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
2457
2458
    def _ignore_setting_bzrdir(self, format):
2459
        pass
2460
2461
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2462
2463
    def get_format_string(self):
2464
        """See RepositoryFormat.get_format_string()."""
2465
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2466
2467
    def get_format_description(self):
2468
        """See RepositoryFormat.get_format_description()."""
2469
        return "Packs containing knits without subtree support"
2470
2471
    def check_conversion_target(self, target_format):
2472
        pass
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
2473
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2474
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2475
class RepositoryFormatKnitPack3(RepositoryFormatPack):
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
2476
    """A subtrees parameterized Pack repository.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2477
2592.3.215 by Robert Collins
Review feedback.
2478
    This repository format uses the xml7 serializer to get:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2479
     - support for recording full info about the tree root
2480
     - support for recording tree-references
2592.3.215 by Robert Collins
Review feedback.
2481
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
2482
    This format was introduced in 0.92.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2483
    """
2484
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
2485
    repository_class = KnitPackRepository
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
2486
    _commit_builder_class = PackRootCommitBuilder
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2487
    rich_root_data = True
2488
    supports_tree_reference = True
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.
2489
    @property
2490
    def _serializer(self):
2491
        return xml7.serializer_v7
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2492
    # What index classes to use
2493
    index_builder_class = InMemoryGraphIndex
2494
    index_class = GraphIndex
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2495
2496
    def _get_matching_bzrdir(self):
2939.2.5 by Ian Clatworthy
review feedback from lifeless
2497
        return bzrdir.format_registry.make_bzrdir(
3010.3.2 by Martin Pool
Rename pack0.92 to pack-0.92
2498
            'pack-0.92-subtree')
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2499
2500
    def _ignore_setting_bzrdir(self, format):
2501
        pass
2502
2503
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2504
2505
    def check_conversion_target(self, target_format):
2506
        if not target_format.rich_root_data:
2507
            raise errors.BadConversionTarget(
2508
                'Does not support rich root data.', target_format)
2509
        if not getattr(target_format, 'supports_tree_reference', False):
2510
            raise errors.BadConversionTarget(
2511
                'Does not support nested trees', target_format)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2512
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2513
    def get_format_string(self):
2514
        """See RepositoryFormat.get_format_string()."""
2939.2.6 by Ian Clatworthy
more review feedback from lifeless and poolie
2515
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
2516
2517
    def get_format_description(self):
2518
        """See RepositoryFormat.get_format_description()."""
2939.2.1 by Ian Clatworthy
use 'knitpack' naming instead of 'experimental' for pack formats
2519
        return "Packs containing knits with subtree support\n"
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2520
2521
2522
class RepositoryFormatKnitPack4(RepositoryFormatPack):
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
2523
    """A rich-root, no subtrees parameterized Pack repository.
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2524
2996.2.12 by Aaron Bentley
Text fixes from review
2525
    This repository format uses the xml6 serializer to get:
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2526
     - support for recording full info about the tree root
2527
2996.2.12 by Aaron Bentley
Text fixes from review
2528
    This format was introduced in 1.0.
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2529
    """
2530
2531
    repository_class = KnitPackRepository
2532
    _commit_builder_class = PackRootCommitBuilder
2533
    rich_root_data = True
2534
    supports_tree_reference = False
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.
2535
    @property
2536
    def _serializer(self):
2537
        return xml6.serializer_v6
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2538
    # What index classes to use
2539
    index_builder_class = InMemoryGraphIndex
2540
    index_class = GraphIndex
2996.2.11 by Aaron Bentley
Implement rich-root-pack format ( #164639)
2541
2542
    def _get_matching_bzrdir(self):
2543
        return bzrdir.format_registry.make_bzrdir(
2544
            'rich-root-pack')
2545
2546
    def _ignore_setting_bzrdir(self, format):
2547
        pass
2548
2549
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2550
2551
    def check_conversion_target(self, target_format):
2552
        if not target_format.rich_root_data:
2553
            raise errors.BadConversionTarget(
2554
                'Does not support rich root data.', target_format)
2555
2556
    def get_format_string(self):
2557
        """See RepositoryFormat.get_format_string()."""
2558
        return ("Bazaar pack repository format 1 with rich root"
2559
                " (needs bzr 1.0)\n")
2560
2561
    def get_format_description(self):
2562
        """See RepositoryFormat.get_format_description()."""
2563
        return "Packs containing knits with rich root support\n"
3152.2.1 by Robert Collins
* A new repository format 'development' has been added. This format will
2564
2565
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2566
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2567
    """Repository that supports external references to allow stacking.
2568
2569
    New in release 1.6.
2570
2571
    Supports external lookups, which results in non-truncated ghosts after
2572
    reconcile compared to pack-0.92 formats.
2573
    """
2574
2575
    repository_class = KnitPackRepository
2576
    _commit_builder_class = PackCommitBuilder
2577
    supports_external_lookups = True
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2578
    # What index classes to use
2579
    index_builder_class = InMemoryGraphIndex
2580
    index_class = GraphIndex
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2581
3224.5.27 by Andrew Bennetts
Avoid importing bzrlib.xml* as a side-effect of importing bzrlib.repofmt.pack_repo.
2582
    @property
2583
    def _serializer(self):
2584
        return xml5.serializer_v5
2585
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2586
    def _get_matching_bzrdir(self):
3735.1.2 by Robert Collins
Remove 1.5 series dev formats and document development2 a little better.
2587
        return bzrdir.format_registry.make_bzrdir('1.6')
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2588
2589
    def _ignore_setting_bzrdir(self, format):
2590
        pass
2591
2592
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2593
2594
    def get_format_string(self):
2595
        """See RepositoryFormat.get_format_string()."""
2596
        return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2597
2598
    def get_format_description(self):
2599
        """See RepositoryFormat.get_format_description()."""
3606.3.1 by Aaron Bentley
Update repo format strings
2600
        return "Packs 5 (adds stacking support, requires bzr 1.6)"
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2601
2602
    def check_conversion_target(self, target_format):
2603
        pass
2604
2605
3549.1.6 by Martin Pool
Change stacked-subtree to stacked-rich-root
2606
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2607
    """A repository with rich roots and stacking.
2608
2609
    New in release 1.6.1.
2610
2611
    Supports stacking on other repositories, allowing data to be accessed
2612
    without being stored locally.
2613
    """
2614
2615
    repository_class = KnitPackRepository
2616
    _commit_builder_class = PackRootCommitBuilder
2617
    rich_root_data = True
2618
    supports_tree_reference = False # no subtrees
2619
    supports_external_lookups = True
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2620
    # What index classes to use
2621
    index_builder_class = InMemoryGraphIndex
2622
    index_class = GraphIndex
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2623
3224.5.27 by Andrew Bennetts
Avoid importing bzrlib.xml* as a side-effect of importing bzrlib.repofmt.pack_repo.
2624
    @property
2625
    def _serializer(self):
2626
        return xml6.serializer_v6
2627
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2628
    def _get_matching_bzrdir(self):
2629
        return bzrdir.format_registry.make_bzrdir(
3606.10.2 by John Arbash Meinel
Name the new format 1.6.1-rich-root, and NEWS for fixing bug #262333
2630
            '1.6.1-rich-root')
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2631
2632
    def _ignore_setting_bzrdir(self, format):
2633
        pass
2634
2635
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2636
2637
    def check_conversion_target(self, target_format):
2638
        if not target_format.rich_root_data:
2639
            raise errors.BadConversionTarget(
2640
                'Does not support rich root data.', target_format)
2641
2642
    def get_format_string(self):
2643
        """See RepositoryFormat.get_format_string()."""
2644
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2645
2646
    def get_format_description(self):
2647
        return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2648
2649
2650
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
3606.3.1 by Aaron Bentley
Update repo format strings
2651
    """A repository with rich roots and external references.
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2652
2653
    New in release 1.6.
2654
2655
    Supports external lookups, which results in non-truncated ghosts after
2656
    reconcile compared to pack-0.92 formats.
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2657
2658
    This format was deprecated because the serializer it uses accidentally
2659
    supported subtrees, when the format was not intended to. This meant that
2660
    someone could accidentally fetch from an incorrect repository.
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2661
    """
2662
2663
    repository_class = KnitPackRepository
2664
    _commit_builder_class = PackRootCommitBuilder
2665
    rich_root_data = True
3549.1.6 by Martin Pool
Change stacked-subtree to stacked-rich-root
2666
    supports_tree_reference = False # no subtrees
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2667
2668
    supports_external_lookups = True
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2669
    # What index classes to use
2670
    index_builder_class = InMemoryGraphIndex
2671
    index_class = GraphIndex
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2672
3224.5.27 by Andrew Bennetts
Avoid importing bzrlib.xml* as a side-effect of importing bzrlib.repofmt.pack_repo.
2673
    @property
2674
    def _serializer(self):
2675
        return xml7.serializer_v7
2676
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2677
    def _get_matching_bzrdir(self):
3845.1.1 by John Arbash Meinel
Ensure that RepositoryFormat._matchingbzrdir.repository_format matches.
2678
        matching = bzrdir.format_registry.make_bzrdir(
3735.1.2 by Robert Collins
Remove 1.5 series dev formats and document development2 a little better.
2679
            '1.6.1-rich-root')
3845.1.1 by John Arbash Meinel
Ensure that RepositoryFormat._matchingbzrdir.repository_format matches.
2680
        matching.repository_format = self
2681
        return matching
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2682
2683
    def _ignore_setting_bzrdir(self, format):
2684
        pass
2685
2686
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2687
2688
    def check_conversion_target(self, target_format):
2689
        if not target_format.rich_root_data:
2690
            raise errors.BadConversionTarget(
2691
                'Does not support rich root data.', target_format)
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2692
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2693
    def get_format_string(self):
2694
        """See RepositoryFormat.get_format_string()."""
3549.1.6 by Martin Pool
Change stacked-subtree to stacked-rich-root
2695
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2696
2697
    def get_format_description(self):
3606.10.1 by John Arbash Meinel
Create a new --1.6-rich-root, deprecate the old one.
2698
        return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2699
                " (deprecated)")
3549.1.5 by Martin Pool
Add stable format names for stacked branches
2700
2701
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2702
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2703
    """A repository with stacking and btree indexes,
2704
    without rich roots or subtrees.
2705
2706
    This is equivalent to pack-1.6 with B+Tree indices.
2707
    """
2708
2709
    repository_class = KnitPackRepository
2710
    _commit_builder_class = PackCommitBuilder
2711
    supports_external_lookups = True
2712
    # What index classes to use
2713
    index_builder_class = BTreeBuilder
2714
    index_class = BTreeGraphIndex
2715
2716
    @property
2717
    def _serializer(self):
2718
        return xml5.serializer_v5
2719
2720
    def _get_matching_bzrdir(self):
2721
        return bzrdir.format_registry.make_bzrdir('1.9')
2722
2723
    def _ignore_setting_bzrdir(self, format):
2724
        pass
2725
2726
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2727
2728
    def get_format_string(self):
2729
        """See RepositoryFormat.get_format_string()."""
2730
        return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2731
2732
    def get_format_description(self):
2733
        """See RepositoryFormat.get_format_description()."""
2734
        return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2735
2736
    def check_conversion_target(self, target_format):
2737
        pass
2738
2739
2740
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2741
    """A repository with rich roots, no subtrees, stacking and btree indexes.
2742
3805.5.1 by John Arbash Meinel
Fix a docstring.
2743
    1.6-rich-root with B+Tree indices.
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
2744
    """
2745
2746
    repository_class = KnitPackRepository
2747
    _commit_builder_class = PackRootCommitBuilder
2748
    rich_root_data = True
2749
    supports_tree_reference = False # no subtrees
2750
    supports_external_lookups = True
2751
    # What index classes to use
2752
    index_builder_class = BTreeBuilder
2753
    index_class = BTreeGraphIndex
2754
2755
    @property
2756
    def _serializer(self):
2757
        return xml6.serializer_v6
2758
2759
    def _get_matching_bzrdir(self):
2760
        return bzrdir.format_registry.make_bzrdir(
2761
            '1.9-rich-root')
2762
2763
    def _ignore_setting_bzrdir(self, format):
2764
        pass
2765
2766
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2767
2768
    def check_conversion_target(self, target_format):
2769
        if not target_format.rich_root_data:
2770
            raise errors.BadConversionTarget(
2771
                'Does not support rich root data.', target_format)
2772
2773
    def get_format_string(self):
2774
        """See RepositoryFormat.get_format_string()."""
2775
        return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2776
2777
    def get_format_description(self):
2778
        return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2779
2780
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2781
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2782
    """A subtrees development repository.
2783
2784
    This format should be retained until the second release after bzr 1.7.
2785
3735.1.2 by Robert Collins
Remove 1.5 series dev formats and document development2 a little better.
2786
    1.6.1-subtree[as it might have been] with B+Tree indices.
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2787
2788
    This is [now] retained until we have a CHK based subtree format in
2789
    development.
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2790
    """
2791
2792
    repository_class = KnitPackRepository
2793
    _commit_builder_class = PackRootCommitBuilder
2794
    rich_root_data = True
2795
    supports_tree_reference = True
2796
    supports_external_lookups = True
2797
    # What index classes to use
2798
    index_builder_class = BTreeBuilder
2799
    index_class = BTreeGraphIndex
2800
3224.5.27 by Andrew Bennetts
Avoid importing bzrlib.xml* as a side-effect of importing bzrlib.repofmt.pack_repo.
2801
    @property
2802
    def _serializer(self):
2803
        return xml7.serializer_v7
2804
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2805
    def _get_matching_bzrdir(self):
2806
        return bzrdir.format_registry.make_bzrdir(
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2807
            'development-subtree')
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2808
2809
    def _ignore_setting_bzrdir(self, format):
2810
        pass
2811
2812
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2813
2814
    def check_conversion_target(self, target_format):
2815
        if not target_format.rich_root_data:
2816
            raise errors.BadConversionTarget(
2817
                'Does not support rich root data.', target_format)
2818
        if not getattr(target_format, 'supports_tree_reference', False):
2819
            raise errors.BadConversionTarget(
2820
                'Does not support nested trees', target_format)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2821
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
2822
    def get_format_string(self):
2823
        """See RepositoryFormat.get_format_string()."""
2824
        return ("Bazaar development format 2 with subtree support "
2825
            "(needs bzr.dev from before 1.8)\n")
2826
2827
    def get_format_description(self):
2828
        """See RepositoryFormat.get_format_description()."""
2829
        return ("Development repository format, currently the same as "
3735.1.2 by Robert Collins
Remove 1.5 series dev formats and document development2 a little better.
2830
            "1.6.1-subtree with B+Tree indices.\n")
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
2831