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