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