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