~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

Fix lock test failures by taking lock breaking into account.

* tests/test_lockdir.py:
(TestLockDir.test_43_break): Release the lock after breaking and
acquiring it.

* tests/__init__.py:
(TestCase._check_locks): Consider lock breaks as releases.
(TestCase._track_locks, TestCase._lock_broken): Also track broken locks.

Show diffs side-by-side

added added

removed removed

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