~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
16
 
20
17
from bzrlib.lazy_import import lazy_import
21
18
lazy_import(globals(), """
22
19
from itertools import izip
 
20
import md5
23
21
import time
24
22
 
25
23
from bzrlib import (
26
 
    chk_map,
27
24
    debug,
28
25
    graph,
29
 
    osutils,
30
26
    pack,
31
27
    transactions,
32
28
    ui,
33
 
    xml5,
34
 
    xml6,
35
 
    xml7,
36
29
    )
37
30
from bzrlib.index import (
 
31
    GraphIndex,
 
32
    GraphIndexBuilder,
 
33
    InMemoryGraphIndex,
38
34
    CombinedGraphIndex,
39
 
    GraphIndex,
40
 
    GraphIndexBuilder,
41
35
    GraphIndexPrefixAdapter,
42
 
    InMemoryGraphIndex,
43
36
    )
44
 
from bzrlib.inventory import CHKInventory
45
37
from bzrlib.knit import (
46
38
    KnitPlainFactory,
47
39
    KnitVersionedFiles,
48
40
    _KnitGraphIndex,
49
41
    _DirectPackAccess,
50
42
    )
 
43
from bzrlib.osutils import rand_chars, split_lines
51
44
from bzrlib import tsort
52
45
""")
53
46
from bzrlib import (
54
47
    bzrdir,
55
 
    chk_serializer,
56
48
    errors,
57
49
    lockable_files,
58
50
    lockdir,
59
 
    revision as _mod_revision,
60
51
    symbol_versioning,
 
52
    xml5,
 
53
    xml6,
 
54
    xml7,
61
55
    )
62
56
 
63
57
from bzrlib.decorators import needs_write_lock
64
 
from bzrlib.btree_index import (
65
 
    BTreeGraphIndex,
66
 
    BTreeBuilder,
67
 
    )
68
 
from bzrlib.index import (
69
 
    GraphIndex,
70
 
    InMemoryGraphIndex,
71
 
    )
72
58
from bzrlib.repofmt.knitrepo import KnitRepository
73
59
from bzrlib.repository import (
74
60
    CommitBuilder,
85
71
 
86
72
class PackCommitBuilder(CommitBuilder):
87
73
    """A subclass of CommitBuilder to add texts with pack semantics.
88
 
 
 
74
    
89
75
    Specifically this uses one knit object rather than one knit object per
90
76
    added text, reducing memory and object pressure.
91
77
    """
106
92
 
107
93
class PackRootCommitBuilder(RootCommitBuilder):
108
94
    """A subclass of RootCommitBuilder to add texts with pack semantics.
109
 
 
 
95
    
110
96
    Specifically this uses one knit object rather than one knit object per
111
97
    added text, reducing memory and object pressure.
112
98
    """
132
118
    ExistingPack and NewPack are used.
133
119
    """
134
120
 
135
 
    # A map of index 'type' to the file extension and position in the
136
 
    # index_sizes array.
137
 
    index_definitions = {
138
 
        'chk': ('.cix', 4),
139
 
        'revision': ('.rix', 0),
140
 
        'inventory': ('.iix', 1),
141
 
        'text': ('.tix', 2),
142
 
        'signature': ('.six', 3),
143
 
        }
144
 
 
145
121
    def __init__(self, revision_index, inventory_index, text_index,
146
 
        signature_index, chk_index=None):
 
122
        signature_index):
147
123
        """Create a pack instance.
148
124
 
149
125
        :param revision_index: A GraphIndex for determining what revisions are
156
132
            texts/deltas (via (fileid, revisionid) tuples).
157
133
        :param signature_index: A GraphIndex for determining what signatures are
158
134
            present in the Pack and accessing the locations of their texts.
159
 
        :param chk_index: A GraphIndex for accessing content by CHK, if the
160
 
            pack has one.
161
135
        """
162
136
        self.revision_index = revision_index
163
137
        self.inventory_index = inventory_index
164
138
        self.text_index = text_index
165
139
        self.signature_index = signature_index
166
 
        self.chk_index = chk_index
167
140
 
168
141
    def access_tuple(self):
169
142
        """Return a tuple (transport, name) for the pack content."""
170
143
        return self.pack_transport, self.file_name()
171
144
 
172
 
    def _check_references(self):
173
 
        """Make sure our external references are present.
174
 
 
175
 
        Packs are allowed to have deltas whose base is not in the pack, but it
176
 
        must be present somewhere in this collection.  It is not allowed to
177
 
        have deltas based on a fallback repository.
178
 
        (See <https://bugs.launchpad.net/bzr/+bug/288751>)
179
 
        """
180
 
        missing_items = {}
181
 
        for (index_name, external_refs, index) in [
182
 
            ('texts',
183
 
                self._get_external_refs(self.text_index),
184
 
                self._pack_collection.text_index.combined_index),
185
 
            ('inventories',
186
 
                self._get_external_refs(self.inventory_index),
187
 
                self._pack_collection.inventory_index.combined_index),
188
 
            ]:
189
 
            missing = external_refs.difference(
190
 
                k for (idx, k, v, r) in
191
 
                index.iter_entries(external_refs))
192
 
            if missing:
193
 
                missing_items[index_name] = sorted(list(missing))
194
 
        if missing_items:
195
 
            from pprint import pformat
196
 
            raise errors.BzrCheckError(
197
 
                "Newly created pack file %r has delta references to "
198
 
                "items not in its repository:\n%s"
199
 
                % (self, pformat(missing_items)))
200
 
 
201
145
    def file_name(self):
202
146
        """Get the file name for the pack on disk."""
203
147
        return self.name + '.pack'
205
149
    def get_revision_count(self):
206
150
        return self.revision_index.key_count()
207
151
 
208
 
    def index_name(self, index_type, name):
209
 
        """Get the disk name of an index type for pack name 'name'."""
210
 
        return name + Pack.index_definitions[index_type][0]
211
 
 
212
 
    def index_offset(self, index_type):
213
 
        """Get the position in a index_size array for a given index type."""
214
 
        return Pack.index_definitions[index_type][1]
215
 
 
216
152
    def inventory_index_name(self, name):
217
153
        """The inv index is the name + .iix."""
218
154
        return self.index_name('inventory', name)
229
165
        """The text index is the name + .tix."""
230
166
        return self.index_name('text', name)
231
167
 
232
 
    def _replace_index_with_readonly(self, index_type):
233
 
        setattr(self, index_type + '_index',
234
 
            self.index_class(self.index_transport,
235
 
                self.index_name(index_type, self.name),
236
 
                self.index_sizes[self.index_offset(index_type)]))
 
168
    def _external_compression_parents_of_texts(self):
 
169
        keys = set()
 
170
        refs = set()
 
171
        for node in self.text_index.iter_all_entries():
 
172
            keys.add(node[1])
 
173
            refs.update(node[3][1])
 
174
        return refs - keys
237
175
 
238
176
 
239
177
class ExistingPack(Pack):
240
178
    """An in memory proxy for an existing .pack and its disk indices."""
241
179
 
242
180
    def __init__(self, pack_transport, name, revision_index, inventory_index,
243
 
        text_index, signature_index, chk_index=None):
 
181
        text_index, signature_index):
244
182
        """Create an ExistingPack object.
245
183
 
246
184
        :param pack_transport: The transport where the pack file resides.
247
185
        :param name: The name of the pack on disk in the pack_transport.
248
186
        """
249
187
        Pack.__init__(self, revision_index, inventory_index, text_index,
250
 
            signature_index, chk_index)
 
188
            signature_index)
251
189
        self.name = name
252
190
        self.pack_transport = pack_transport
253
191
        if None in (revision_index, inventory_index, text_index,
261
199
        return not self.__eq__(other)
262
200
 
263
201
    def __repr__(self):
264
 
        return "<%s.%s object at 0x%x, %s, %s" % (
265
 
            self.__class__.__module__, self.__class__.__name__, id(self),
266
 
            self.pack_transport, self.name)
267
 
 
268
 
 
269
 
class ResumedPack(ExistingPack):
270
 
 
271
 
    def __init__(self, name, revision_index, inventory_index, text_index,
272
 
        signature_index, upload_transport, pack_transport, index_transport,
273
 
        pack_collection):
274
 
        """Create a ResumedPack object."""
275
 
        ExistingPack.__init__(self, pack_transport, name, revision_index,
276
 
            inventory_index, text_index, signature_index)
277
 
        self.upload_transport = upload_transport
278
 
        self.index_transport = index_transport
279
 
        self.index_sizes = [None, None, None, None]
280
 
        indices = [
281
 
            ('revision', revision_index),
282
 
            ('inventory', inventory_index),
283
 
            ('text', text_index),
284
 
            ('signature', signature_index),
285
 
            ]
286
 
        for index_type, index in indices:
287
 
            offset = self.index_offset(index_type)
288
 
            self.index_sizes[offset] = index._size
289
 
        self.index_class = pack_collection._index_class
290
 
        self._pack_collection = pack_collection
291
 
        self._state = 'resumed'
292
 
        # XXX: perhaps check that the .pack file exists?
293
 
 
294
 
    def access_tuple(self):
295
 
        if self._state == 'finished':
296
 
            return Pack.access_tuple(self)
297
 
        elif self._state == 'resumed':
298
 
            return self.upload_transport, self.file_name()
299
 
        else:
300
 
            raise AssertionError(self._state)
301
 
 
302
 
    def abort(self):
303
 
        self.upload_transport.delete(self.file_name())
304
 
        indices = [self.revision_index, self.inventory_index, self.text_index,
305
 
            self.signature_index]
306
 
        for index in indices:
307
 
            index._transport.delete(index._name)
308
 
 
309
 
    def finish(self):
310
 
        self._check_references()
311
 
        new_name = '../packs/' + self.file_name()
312
 
        self.upload_transport.rename(self.file_name(), new_name)
313
 
        for index_type in ['revision', 'inventory', 'text', 'signature']:
314
 
            old_name = self.index_name(index_type, self.name)
315
 
            new_name = '../indices/' + old_name
316
 
            self.upload_transport.rename(old_name, new_name)
317
 
            self._replace_index_with_readonly(index_type)
318
 
        self._state = 'finished'
319
 
 
320
 
    def _get_external_refs(self, index):
321
 
        return index.external_references(1)
 
202
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
 
203
            id(self), self.pack_transport, self.name)
322
204
 
323
205
 
324
206
class NewPack(Pack):
325
207
    """An in memory proxy for a pack which is being created."""
326
208
 
327
 
    def __init__(self, pack_collection, upload_suffix='', file_mode=None):
 
209
    # A map of index 'type' to the file extension and position in the
 
210
    # index_sizes array.
 
211
    index_definitions = {
 
212
        'revision': ('.rix', 0),
 
213
        'inventory': ('.iix', 1),
 
214
        'text': ('.tix', 2),
 
215
        'signature': ('.six', 3),
 
216
        }
 
217
 
 
218
    def __init__(self, upload_transport, index_transport, pack_transport,
 
219
        upload_suffix='', file_mode=None):
328
220
        """Create a NewPack instance.
329
221
 
330
 
        :param pack_collection: A PackCollection into which this is being inserted.
 
222
        :param upload_transport: A writable transport for the pack to be
 
223
            incrementally uploaded to.
 
224
        :param index_transport: A writable transport for the pack's indices to
 
225
            be written to when the pack is finished.
 
226
        :param pack_transport: A writable transport for the pack to be renamed
 
227
            to when the upload is complete. This *must* be the same as
 
228
            upload_transport.clone('../packs').
331
229
        :param upload_suffix: An optional suffix to be given to any temporary
332
230
            files created during the pack creation. e.g '.autopack'
333
 
        :param file_mode: Unix permissions for newly created file.
 
231
        :param file_mode: An optional file mode to create the new files with.
334
232
        """
335
233
        # The relative locations of the packs are constrained, but all are
336
234
        # passed in because the caller has them, so as to avoid object churn.
337
 
        index_builder_class = pack_collection._index_builder_class
338
 
        if pack_collection.chk_index is not None:
339
 
            chk_index = index_builder_class(reference_lists=0)
340
 
        else:
341
 
            chk_index = None
342
235
        Pack.__init__(self,
343
236
            # Revisions: parents list, no text compression.
344
 
            index_builder_class(reference_lists=1),
 
237
            InMemoryGraphIndex(reference_lists=1),
345
238
            # Inventory: We want to map compression only, but currently the
346
239
            # knit code hasn't been updated enough to understand that, so we
347
240
            # have a regular 2-list index giving parents and compression
348
241
            # source.
349
 
            index_builder_class(reference_lists=2),
 
242
            InMemoryGraphIndex(reference_lists=2),
350
243
            # Texts: compression and per file graph, for all fileids - so two
351
244
            # reference lists and two elements in the key tuple.
352
 
            index_builder_class(reference_lists=2, key_elements=2),
 
245
            InMemoryGraphIndex(reference_lists=2, key_elements=2),
353
246
            # Signatures: Just blobs to store, no compression, no parents
354
247
            # listing.
355
 
            index_builder_class(reference_lists=0),
356
 
            # CHK based storage - just blobs, no compression or parents.
357
 
            chk_index=chk_index
 
248
            InMemoryGraphIndex(reference_lists=0),
358
249
            )
359
 
        self._pack_collection = pack_collection
360
 
        # When we make readonly indices, we need this.
361
 
        self.index_class = pack_collection._index_class
362
250
        # where should the new pack be opened
363
 
        self.upload_transport = pack_collection._upload_transport
 
251
        self.upload_transport = upload_transport
364
252
        # where are indices written out to
365
 
        self.index_transport = pack_collection._index_transport
 
253
        self.index_transport = index_transport
366
254
        # where is the pack renamed to when it is finished?
367
 
        self.pack_transport = pack_collection._pack_transport
 
255
        self.pack_transport = pack_transport
368
256
        # What file mode to upload the pack and indices with.
369
257
        self._file_mode = file_mode
370
258
        # tracks the content written to the .pack file.
371
 
        self._hash = osutils.md5()
372
 
        # a tuple with the length in bytes of the indices, once the pack
373
 
        # is finalised. (rev, inv, text, sigs, chk_if_in_use)
 
259
        self._hash = md5.new()
 
260
        # a four-tuple with the length in bytes of the indices, once the pack
 
261
        # is finalised. (rev, inv, text, sigs)
374
262
        self.index_sizes = None
375
263
        # How much data to cache when writing packs. Note that this is not
376
264
        # synchronised with reads, because it's not in the transport layer, so
378
266
        # under creation.
379
267
        self._cache_limit = 0
380
268
        # the temporary pack file name.
381
 
        self.random_name = osutils.rand_chars(20) + upload_suffix
 
269
        self.random_name = rand_chars(20) + upload_suffix
382
270
        # when was this pack started ?
383
271
        self.start_time = time.time()
384
272
        # open an output stream for the data added to the pack.
388
276
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
389
277
                time.ctime(), self.upload_transport.base, self.random_name,
390
278
                time.time() - self.start_time)
391
 
        # A list of byte sequences to be written to the new pack, and the
392
 
        # aggregate size of them.  Stored as a list rather than separate
 
279
        # A list of byte sequences to be written to the new pack, and the 
 
280
        # aggregate size of them.  Stored as a list rather than separate 
393
281
        # variables so that the _write_data closure below can update them.
394
282
        self._buffer = [[], 0]
395
 
        # create a callable for adding data
 
283
        # create a callable for adding data 
396
284
        #
397
285
        # robertc says- this is a closure rather than a method on the object
398
286
        # so that the variables are locals, and faster than accessing object
437
325
        return bool(self.get_revision_count() or
438
326
            self.inventory_index.key_count() or
439
327
            self.text_index.key_count() or
440
 
            self.signature_index.key_count() or
441
 
            (self.chk_index is not None and self.chk_index.key_count()))
 
328
            self.signature_index.key_count())
442
329
 
443
 
    def finish(self, suspend=False):
 
330
    def finish(self):
444
331
        """Finish the new pack.
445
332
 
446
333
        This:
455
342
        if self._buffer[1]:
456
343
            self._write_data('', flush=True)
457
344
        self.name = self._hash.hexdigest()
458
 
        if not suspend:
459
 
            self._check_references()
460
345
        # write indices
461
346
        # XXX: It'd be better to write them all to temporary names, then
462
347
        # rename them all into place, so that the window when only some are
463
348
        # visible is smaller.  On the other hand none will be seen until
464
349
        # they're in the names list.
465
350
        self.index_sizes = [None, None, None, None]
466
 
        self._write_index('revision', self.revision_index, 'revision', suspend)
467
 
        self._write_index('inventory', self.inventory_index, 'inventory',
468
 
            suspend)
469
 
        self._write_index('text', self.text_index, 'file texts', suspend)
 
351
        self._write_index('revision', self.revision_index, 'revision')
 
352
        self._write_index('inventory', self.inventory_index, 'inventory')
 
353
        self._write_index('text', self.text_index, 'file texts')
470
354
        self._write_index('signature', self.signature_index,
471
 
            'revision signatures', suspend)
472
 
        if self.chk_index is not None:
473
 
            self.index_sizes.append(None)
474
 
            self._write_index('chk', self.chk_index,
475
 
                'content hash bytes', suspend)
 
355
            'revision signatures')
476
356
        self.write_stream.close()
477
357
        # Note that this will clobber an existing pack with the same name,
478
358
        # without checking for hash collisions. While this is undesirable this
485
365
        #  - try for HASH.pack
486
366
        #  - try for temporary-name
487
367
        #  - refresh the pack-list to see if the pack is now absent
488
 
        new_name = self.name + '.pack'
489
 
        if not suspend:
490
 
            new_name = '../packs/' + new_name
491
 
        self.upload_transport.rename(self.random_name, new_name)
 
368
        self.upload_transport.rename(self.random_name,
 
369
                '../packs/' + self.name + '.pack')
492
370
        self._state = 'finished'
493
371
        if 'pack' in debug.debug_flags:
494
372
            # XXX: size might be interesting?
495
 
            mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
 
373
            mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
496
374
                time.ctime(), self.upload_transport.base, self.random_name,
497
 
                new_name, time.time() - self.start_time)
 
375
                self.pack_transport, self.name,
 
376
                time.time() - self.start_time)
498
377
 
499
378
    def flush(self):
500
379
        """Flush any current data."""
504
383
            self._hash.update(bytes)
505
384
            self._buffer[:] = [[], 0]
506
385
 
507
 
    def _get_external_refs(self, index):
508
 
        return index._external_references()
 
386
    def index_name(self, index_type, name):
 
387
        """Get the disk name of an index type for pack name 'name'."""
 
388
        return name + NewPack.index_definitions[index_type][0]
 
389
 
 
390
    def index_offset(self, index_type):
 
391
        """Get the position in a index_size array for a given index type."""
 
392
        return NewPack.index_definitions[index_type][1]
 
393
 
 
394
    def _replace_index_with_readonly(self, index_type):
 
395
        setattr(self, index_type + '_index',
 
396
            GraphIndex(self.index_transport,
 
397
                self.index_name(index_type, self.name),
 
398
                self.index_sizes[self.index_offset(index_type)]))
509
399
 
510
400
    def set_write_cache_size(self, size):
511
401
        self._cache_limit = size
512
402
 
513
 
    def _write_index(self, index_type, index, label, suspend=False):
 
403
    def _write_index(self, index_type, index, label):
514
404
        """Write out an index.
515
405
 
516
406
        :param index_type: The type of index to write - e.g. 'revision'.
518
408
        :param label: What label to give the index e.g. 'revision'.
519
409
        """
520
410
        index_name = self.index_name(index_type, self.name)
521
 
        if suspend:
522
 
            transport = self.upload_transport
523
 
        else:
524
 
            transport = self.index_transport
525
 
        self.index_sizes[self.index_offset(index_type)] = transport.put_file(
526
 
            index_name, index.finish(), mode=self._file_mode)
 
411
        self.index_sizes[self.index_offset(index_type)] = \
 
412
            self.index_transport.put_file(index_name, index.finish(),
 
413
            mode=self._file_mode)
527
414
        if 'pack' in debug.debug_flags:
528
415
            # XXX: size might be interesting?
529
416
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
530
417
                time.ctime(), label, self.upload_transport.base,
531
418
                self.random_name, time.time() - self.start_time)
532
 
        # Replace the writable index on this object with a readonly,
 
419
        # Replace the writable index on this object with a readonly, 
533
420
        # presently unloaded index. We should alter
534
421
        # the index layer to make its finish() error if add_node is
535
422
        # subsequently used. RBC
544
431
    such as 'revision index'.
545
432
 
546
433
    A CombinedIndex provides an index on a single key space built up
547
 
    from several on-disk indices.  The AggregateIndex builds on this
 
434
    from several on-disk indices.  The AggregateIndex builds on this 
548
435
    to provide a knit access layer, and allows having up to one writable
549
436
    index within the collection.
550
437
    """
551
438
    # XXX: Probably 'can be written to' could/should be separated from 'acts
552
439
    # like a knit index' -- mbp 20071024
553
440
 
554
 
    def __init__(self, reload_func=None, flush_func=None):
555
 
        """Create an AggregateIndex.
556
 
 
557
 
        :param reload_func: A function to call if we find we are missing an
558
 
            index. Should have the form reload_func() => True if the list of
559
 
            active pack files has changed.
560
 
        """
561
 
        self._reload_func = reload_func
 
441
    def __init__(self):
 
442
        """Create an AggregateIndex."""
562
443
        self.index_to_pack = {}
563
 
        self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
564
 
        self.data_access = _DirectPackAccess(self.index_to_pack,
565
 
                                             reload_func=reload_func,
566
 
                                             flush_func=flush_func)
 
444
        self.combined_index = CombinedGraphIndex([])
 
445
        self.data_access = _DirectPackAccess(self.index_to_pack)
567
446
        self.add_callback = None
568
447
 
569
448
    def replace_indices(self, index_to_pack, indices):
591
470
 
592
471
        Future searches on the aggregate index will seach this new index
593
472
        before all previously inserted indices.
594
 
 
 
473
        
595
474
        :param index: An Index for the pack.
596
475
        :param pack: A Pack instance.
597
476
        """
605
484
 
606
485
        There can be at most one writable index at any time.  Any
607
486
        modifications made to the knit are put into this index.
608
 
 
 
487
        
609
488
        :param index: An index from the pack parameter.
610
489
        :param pack: A Pack instance.
611
490
        """
628
507
 
629
508
    def remove_index(self, index, pack):
630
509
        """Remove index from the indices used to answer queries.
631
 
 
 
510
        
632
511
        :param index: An index from the pack parameter.
633
512
        :param pack: A Pack instance.
634
513
        """
643
522
class Packer(object):
644
523
    """Create a pack from packs."""
645
524
 
646
 
    def __init__(self, pack_collection, packs, suffix, revision_ids=None,
647
 
                 reload_func=None):
 
525
    def __init__(self, pack_collection, packs, suffix, revision_ids=None):
648
526
        """Create a Packer.
649
527
 
650
528
        :param pack_collection: A RepositoryPackCollection object where the
652
530
        :param packs: The packs to combine.
653
531
        :param suffix: The suffix to use on the temporary files for the pack.
654
532
        :param revision_ids: Revision ids to limit the pack to.
655
 
        :param reload_func: A function to call if a pack file/index goes
656
 
            missing. The side effect of calling this function should be to
657
 
            update self.packs. See also AggregateIndex
658
533
        """
659
534
        self.packs = packs
660
535
        self.suffix = suffix
662
537
        # The pack object we are creating.
663
538
        self.new_pack = None
664
539
        self._pack_collection = pack_collection
665
 
        self._reload_func = reload_func
666
540
        # The index layer keys for the revisions being copied. None for 'all
667
541
        # objects'.
668
542
        self._revision_keys = None
674
548
    def _extra_init(self):
675
549
        """A template hook to allow extending the constructor trivially."""
676
550
 
677
 
    def _pack_map_and_index_list(self, index_attribute):
678
 
        """Convert a list of packs to an index pack map and index list.
679
 
 
680
 
        :param index_attribute: The attribute that the desired index is found
681
 
            on.
682
 
        :return: A tuple (map, list) where map contains the dict from
683
 
            index:pack_tuple, and list contains the indices in the preferred
684
 
            access order.
685
 
        """
686
 
        indices = []
687
 
        pack_map = {}
688
 
        for pack_obj in self.packs:
689
 
            index = getattr(pack_obj, index_attribute)
690
 
            indices.append(index)
691
 
            pack_map[index] = pack_obj
692
 
        return pack_map, indices
693
 
 
694
 
    def _index_contents(self, indices, key_filter=None):
695
 
        """Get an iterable of the index contents from a pack_map.
696
 
 
697
 
        :param indices: The list of indices to query
698
 
        :param key_filter: An optional filter to limit the keys returned.
699
 
        """
700
 
        all_index = CombinedGraphIndex(indices)
701
 
        if key_filter is None:
702
 
            return all_index.iter_all_entries()
703
 
        else:
704
 
            return all_index.iter_entries(key_filter)
705
 
 
706
551
    def pack(self, pb=None):
707
552
        """Create a new pack by reading data from other packs.
708
553
 
709
554
        This does little more than a bulk copy of data. One key difference
710
555
        is that data with the same item key across multiple packs is elided
711
556
        from the output. The new pack is written into the current pack store
712
 
        along with its indices, and the name added to the pack names. The
 
557
        along with its indices, and the name added to the pack names. The 
713
558
        source packs are not altered and are not required to be in the current
714
559
        pack collection.
715
560
 
722
567
        # XXX: - duplicate code warning with start_write_group; fix before
723
568
        #      considering 'done'.
724
569
        if self._pack_collection._new_pack is not None:
725
 
            raise errors.BzrError('call to %s.pack() while another pack is'
726
 
                                  ' being written.'
727
 
                                  % (self.__class__.__name__,))
 
570
            raise errors.BzrError('call to create_pack_from_packs while '
 
571
                'another pack is being written.')
728
572
        if self.revision_ids is not None:
729
573
            if len(self.revision_ids) == 0:
730
574
                # silly fetch request.
745
589
 
746
590
    def open_pack(self):
747
591
        """Open a pack for the pack we are creating."""
748
 
        new_pack = self._pack_collection.pack_factory(self._pack_collection,
749
 
                upload_suffix=self.suffix,
750
 
                file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
751
 
        # We know that we will process all nodes in order, and don't need to
752
 
        # query, so don't combine any indices spilled to disk until we are done
753
 
        new_pack.revision_index.set_optimize(combine_backing_indices=False)
754
 
        new_pack.inventory_index.set_optimize(combine_backing_indices=False)
755
 
        new_pack.text_index.set_optimize(combine_backing_indices=False)
756
 
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
757
 
        return new_pack
758
 
 
759
 
    def _update_pack_order(self, entries, index_to_pack_map):
760
 
        """Determine how we want our packs to be ordered.
761
 
 
762
 
        This changes the sort order of the self.packs list so that packs unused
763
 
        by 'entries' will be at the end of the list, so that future requests
764
 
        can avoid probing them.  Used packs will be at the front of the
765
 
        self.packs list, in the order of their first use in 'entries'.
766
 
 
767
 
        :param entries: A list of (index, ...) tuples
768
 
        :param index_to_pack_map: A mapping from index objects to pack objects.
769
 
        """
770
 
        packs = []
771
 
        seen_indexes = set()
772
 
        for entry in entries:
773
 
            index = entry[0]
774
 
            if index not in seen_indexes:
775
 
                packs.append(index_to_pack_map[index])
776
 
                seen_indexes.add(index)
777
 
        if len(packs) == len(self.packs):
778
 
            if 'pack' in debug.debug_flags:
779
 
                mutter('Not changing pack list, all packs used.')
780
 
            return
781
 
        seen_packs = set(packs)
782
 
        for pack in self.packs:
783
 
            if pack not in seen_packs:
784
 
                packs.append(pack)
785
 
                seen_packs.add(pack)
786
 
        if 'pack' in debug.debug_flags:
787
 
            old_names = [p.access_tuple()[1] for p in self.packs]
788
 
            new_names = [p.access_tuple()[1] for p in packs]
789
 
            mutter('Reordering packs\nfrom: %s\n  to: %s',
790
 
                   old_names, new_names)
791
 
        self.packs = packs
 
592
        return NewPack(self._pack_collection._upload_transport,
 
593
            self._pack_collection._index_transport,
 
594
            self._pack_collection._pack_transport, upload_suffix=self.suffix,
 
595
            file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
792
596
 
793
597
    def _copy_revision_texts(self):
794
598
        """Copy revision data to the new pack."""
798
602
        else:
799
603
            revision_keys = None
800
604
        # select revision keys
801
 
        revision_index_map, revision_indices = self._pack_map_and_index_list(
802
 
            'revision_index')
803
 
        revision_nodes = self._index_contents(revision_indices, revision_keys)
804
 
        revision_nodes = list(revision_nodes)
805
 
        self._update_pack_order(revision_nodes, revision_index_map)
 
605
        revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
606
            self.packs, 'revision_index')[0]
 
607
        revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
806
608
        # copy revision keys and adjust values
807
609
        self.pb.update("Copying revision texts", 1)
808
610
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
828
630
        # querying for keys here could introduce a bug where an inventory item
829
631
        # is missed, so do not change it to query separately without cross
830
632
        # checking like the text key check below.
831
 
        inventory_index_map, inventory_indices = self._pack_map_and_index_list(
832
 
            'inventory_index')
833
 
        inv_nodes = self._index_contents(inventory_indices, inv_keys)
 
633
        inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
634
            self.packs, 'inventory_index')[0]
 
635
        inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
834
636
        # copy inventory keys and adjust values
835
637
        # XXX: Should be a helper function to allow different inv representation
836
638
        # at this point.
870
672
            if missing_text_keys:
871
673
                # TODO: raise a specific error that can handle many missing
872
674
                # keys.
873
 
                mutter("missing keys during fetch: %r", missing_text_keys)
874
675
                a_missing_key = missing_text_keys.pop()
875
676
                raise errors.RevisionNotPresent(a_missing_key[1],
876
677
                    a_missing_key[0])
881
682
            self.new_pack.text_index, readv_group_iter, total_items))
882
683
        self._log_copied_texts()
883
684
 
 
685
    def _check_references(self):
 
686
        """Make sure our external refereneces are present."""
 
687
        external_refs = self.new_pack._external_compression_parents_of_texts()
 
688
        if external_refs:
 
689
            index = self._pack_collection.text_index.combined_index
 
690
            found_items = list(index.iter_entries(external_refs))
 
691
            if len(found_items) != len(external_refs):
 
692
                found_keys = set(k for idx, k, refs, value in found_items)
 
693
                missing_items = external_refs - found_keys
 
694
                missing_file_id, missing_revision_id = missing_items.pop()
 
695
                raise errors.RevisionNotPresent(missing_revision_id,
 
696
                                                missing_file_id)
 
697
 
884
698
    def _create_pack_from_packs(self):
885
699
        self.pb.update("Opening pack", 0, 5)
886
700
        self.new_pack = self.open_pack()
904
718
        self._copy_text_texts()
905
719
        # select signature keys
906
720
        signature_filter = self._revision_keys # same keyspace
907
 
        signature_index_map, signature_indices = self._pack_map_and_index_list(
908
 
            'signature_index')
909
 
        signature_nodes = self._index_contents(signature_indices,
 
721
        signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
722
            self.packs, 'signature_index')[0]
 
723
        signature_nodes = self._pack_collection._index_contents(signature_index_map,
910
724
            signature_filter)
911
725
        # copy signature keys and adjust values
912
726
        self.pb.update("Copying signature texts", 4)
917
731
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
918
732
                new_pack.signature_index.key_count(),
919
733
                time.time() - new_pack.start_time)
920
 
        # copy chk contents
921
 
        # NB XXX: how to check CHK references are present? perhaps by yielding
922
 
        # the items? How should that interact with stacked repos?
923
 
        if new_pack.chk_index is not None:
924
 
            self._copy_chks()
925
 
            if 'pack' in debug.debug_flags:
926
 
                mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
927
 
                    time.ctime(), self._pack_collection._upload_transport.base,
928
 
                    new_pack.random_name,
929
 
                    new_pack.chk_index.key_count(),
930
 
                    time.time() - new_pack.start_time)
931
 
        new_pack._check_references()
 
734
        self._check_references()
932
735
        if not self._use_pack(new_pack):
933
736
            new_pack.abort()
934
737
            return None
937
740
        self._pack_collection.allocate(new_pack)
938
741
        return new_pack
939
742
 
940
 
    def _copy_chks(self, refs=None):
941
 
        # XXX: Todo, recursive follow-pointers facility when fetching some
942
 
        # revisions only.
943
 
        chk_index_map, chk_indices = self._pack_map_and_index_list(
944
 
            'chk_index')
945
 
        chk_nodes = self._index_contents(chk_indices, refs)
946
 
        new_refs = set()
947
 
        # TODO: This isn't strictly tasteful as we are accessing some private
948
 
        #       variables (_serializer). Perhaps a better way would be to have
949
 
        #       Repository._deserialise_chk_node()
950
 
        search_key_func = chk_map.search_key_registry.get(
951
 
            self._pack_collection.repo._serializer.search_key_name)
952
 
        def accumlate_refs(lines):
953
 
            # XXX: move to a generic location
954
 
            # Yay mismatch:
955
 
            bytes = ''.join(lines)
956
 
            node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
957
 
            new_refs.update(node.refs())
958
 
        self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
959
 
            self.new_pack.chk_index, output_lines=accumlate_refs)
960
 
        return new_refs
961
 
 
962
 
    def _copy_nodes(self, nodes, index_map, writer, write_index,
963
 
        output_lines=None):
964
 
        """Copy knit nodes between packs with no graph references.
965
 
 
966
 
        :param output_lines: Output full texts of copied items.
967
 
        """
 
743
    def _copy_nodes(self, nodes, index_map, writer, write_index):
 
744
        """Copy knit nodes between packs with no graph references."""
968
745
        pb = ui.ui_factory.nested_progress_bar()
969
746
        try:
970
747
            return self._do_copy_nodes(nodes, index_map, writer,
971
 
                write_index, pb, output_lines=output_lines)
 
748
                write_index, pb)
972
749
        finally:
973
750
            pb.finished()
974
751
 
975
 
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
976
 
        output_lines=None):
 
752
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
977
753
        # for record verification
978
754
        knit = KnitVersionedFiles(None, None)
979
755
        # plan a readv on each source pack:
981
757
        nodes = sorted(nodes)
982
758
        # how to map this into knit.py - or knit.py into this?
983
759
        # we don't want the typical knit logic, we want grouping by pack
984
 
        # at this point - perhaps a helper library for the following code
 
760
        # at this point - perhaps a helper library for the following code 
985
761
        # duplication points?
986
762
        request_groups = {}
987
763
        for index, key, value in nodes:
1000
776
            # linear scan up the pack
1001
777
            pack_readv_requests.sort()
1002
778
            # copy the data
1003
 
            pack_obj = index_map[index]
1004
 
            transport, path = pack_obj.access_tuple()
1005
 
            try:
1006
 
                reader = pack.make_readv_reader(transport, path,
1007
 
                    [offset[0:2] for offset in pack_readv_requests])
1008
 
            except errors.NoSuchFile:
1009
 
                if self._reload_func is not None:
1010
 
                    self._reload_func()
1011
 
                raise
 
779
            transport, path = index_map[index]
 
780
            reader = pack.make_readv_reader(transport, path,
 
781
                [offset[0:2] for offset in pack_readv_requests])
1012
782
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
1013
783
                izip(reader.iter_records(), pack_readv_requests):
1014
784
                raw_data = read_func(None)
1015
785
                # check the header only
1016
 
                if output_lines is not None:
1017
 
                    output_lines(knit._parse_record(key[-1], raw_data)[0])
1018
 
                else:
1019
 
                    df, _ = knit._parse_record_header(key, raw_data)
1020
 
                    df.close()
 
786
                df, _ = knit._parse_record_header(key, raw_data)
 
787
                df.close()
1021
788
                pos, size = writer.add_bytes_record(raw_data, names)
1022
789
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
1023
790
                pb.update("Copied record", record_index)
1053
820
        pb.update("Copied record", record_index, total_items)
1054
821
        for index, readv_vector, node_vector in readv_group_iter:
1055
822
            # copy the data
1056
 
            pack_obj = index_map[index]
1057
 
            transport, path = pack_obj.access_tuple()
1058
 
            try:
1059
 
                reader = pack.make_readv_reader(transport, path, readv_vector)
1060
 
            except errors.NoSuchFile:
1061
 
                if self._reload_func is not None:
1062
 
                    self._reload_func()
1063
 
                raise
 
823
            transport, path = index_map[index]
 
824
            reader = pack.make_readv_reader(transport, path, readv_vector)
1064
825
            for (names, read_func), (key, eol_flag, references) in \
1065
826
                izip(reader.iter_records(), node_vector):
1066
827
                raw_data = read_func(None)
1083
844
                record_index += 1
1084
845
 
1085
846
    def _get_text_nodes(self):
1086
 
        text_index_map, text_indices = self._pack_map_and_index_list(
1087
 
            'text_index')
1088
 
        return text_index_map, self._index_contents(text_indices,
 
847
        text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
848
            self.packs, 'text_index')[0]
 
849
        return text_index_map, self._pack_collection._index_contents(text_index_map,
1089
850
            self._text_filter)
1090
851
 
1091
852
    def _least_readv_node_readv(self, nodes):
1092
853
        """Generate request groups for nodes using the least readv's.
1093
 
 
 
854
        
1094
855
        :param nodes: An iterable of graph index nodes.
1095
856
        :return: Total node count and an iterator of the data needed to perform
1096
857
            readvs to obtain the data for nodes. Each item yielded by the
1194
955
        # TODO: combine requests in the same index that are in ascending order.
1195
956
        return total, requests
1196
957
 
1197
 
    def open_pack(self):
1198
 
        """Open a pack for the pack we are creating."""
1199
 
        new_pack = super(OptimisingPacker, self).open_pack()
1200
 
        # Turn on the optimization flags for all the index builders.
1201
 
        new_pack.revision_index.set_optimize(for_size=True)
1202
 
        new_pack.inventory_index.set_optimize(for_size=True)
1203
 
        new_pack.text_index.set_optimize(for_size=True)
1204
 
        new_pack.signature_index.set_optimize(for_size=True)
1205
 
        return new_pack
1206
 
 
1207
958
 
1208
959
class ReconcilePacker(Packer):
1209
960
    """A packer which regenerates indices etc as it copies.
1210
 
 
 
961
    
1211
962
    This is used by ``bzr reconcile`` to cause parent text pointers to be
1212
963
    regenerated.
1213
964
    """
1236
987
        # 1) generate the ideal index
1237
988
        repo = self._pack_collection.repo
1238
989
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1239
 
            _1, key, _2, refs in
 
990
            _1, key, _2, refs in 
1240
991
            self.new_pack.revision_index.iter_all_entries()])
1241
992
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1242
993
        # 2) generate a text_nodes list that contains all the deltas that can
1248
999
        text_index_map, text_nodes = self._get_text_nodes()
1249
1000
        for node in text_nodes:
1250
1001
            # 0 - index
1251
 
            # 1 - key
 
1002
            # 1 - key 
1252
1003
            # 2 - value
1253
1004
            # 3 - refs
1254
1005
            try:
1321
1072
                    raise errors.BzrError('Mismatched key parent %r:%r' %
1322
1073
                        (key, parent_keys))
1323
1074
                parents.append(parent_key[1])
1324
 
            text_lines = osutils.split_lines(repo.texts.get_record_stream(
 
1075
            text_lines = split_lines(repo.texts.get_record_stream(
1325
1076
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
1326
1077
            output_texts.add_lines(key, parent_keys, text_lines,
1327
1078
                random_id=True, check_content=False)
1328
1079
        # 5) check that nothing inserted has a reference outside the keyspace.
1329
 
        missing_text_keys = self.new_pack.text_index._external_references()
 
1080
        missing_text_keys = self.new_pack._external_compression_parents_of_texts()
1330
1081
        if missing_text_keys:
1331
 
            raise errors.BzrCheckError('Reference to missing compression parents %r'
 
1082
            raise errors.BzrError('Reference to missing compression parents %r'
1332
1083
                % (missing_text_keys,))
1333
1084
        self._log_copied_texts()
1334
1085
 
1349
1100
 
1350
1101
class RepositoryPackCollection(object):
1351
1102
    """Management of packs within a repository.
1352
 
 
 
1103
    
1353
1104
    :ivar _names: map of {pack_name: (index_size,)}
1354
1105
    """
1355
1106
 
1356
 
    pack_factory = NewPack
1357
 
 
1358
1107
    def __init__(self, repo, transport, index_transport, upload_transport,
1359
 
                 pack_transport, index_builder_class, index_class,
1360
 
                 use_chk_index):
 
1108
                 pack_transport):
1361
1109
        """Create a new RepositoryPackCollection.
1362
1110
 
1363
 
        :param transport: Addresses the repository base directory
 
1111
        :param transport: Addresses the repository base directory 
1364
1112
            (typically .bzr/repository/).
1365
1113
        :param index_transport: Addresses the directory containing indices.
1366
1114
        :param upload_transport: Addresses the directory into which packs are written
1367
1115
            while they're being created.
1368
1116
        :param pack_transport: Addresses the directory of existing complete packs.
1369
 
        :param index_builder_class: The index builder class to use.
1370
 
        :param index_class: The index class to use.
1371
 
        :param use_chk_index: Whether to setup and manage a CHK index.
1372
1117
        """
1373
 
        # XXX: This should call self.reset()
1374
1118
        self.repo = repo
1375
1119
        self.transport = transport
1376
1120
        self._index_transport = index_transport
1377
1121
        self._upload_transport = upload_transport
1378
1122
        self._pack_transport = pack_transport
1379
 
        self._index_builder_class = index_builder_class
1380
 
        self._index_class = index_class
1381
 
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
1382
 
            '.cix': 4}
 
1123
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
1383
1124
        self.packs = []
1384
1125
        # name:Pack mapping
1385
 
        self._names = None
1386
1126
        self._packs_by_name = {}
1387
1127
        # the previous pack-names content
1388
1128
        self._packs_at_load = None
1389
1129
        # when a pack is being created by this object, the state of that pack.
1390
1130
        self._new_pack = None
1391
1131
        # aggregated revision index data
1392
 
        flush = self._flush_new_pack
1393
 
        self.revision_index = AggregateIndex(self.reload_pack_names, flush)
1394
 
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
1395
 
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
1396
 
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
1397
 
        if use_chk_index:
1398
 
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
1399
 
        else:
1400
 
            # used to determine if we're using a chk_index elsewhere.
1401
 
            self.chk_index = None
1402
 
        # resumed packs
1403
 
        self._resumed_packs = []
 
1132
        self.revision_index = AggregateIndex()
 
1133
        self.inventory_index = AggregateIndex()
 
1134
        self.text_index = AggregateIndex()
 
1135
        self.signature_index = AggregateIndex()
1404
1136
 
1405
1137
    def add_pack_to_memory(self, pack):
1406
1138
        """Make a Pack object available to the repository to satisfy queries.
1407
 
 
 
1139
        
1408
1140
        :param pack: A Pack object.
1409
1141
        """
1410
1142
        if pack.name in self._packs_by_name:
1411
 
            raise AssertionError(
1412
 
                'pack %s already in _packs_by_name' % (pack.name,))
 
1143
            raise AssertionError()
1413
1144
        self.packs.append(pack)
1414
1145
        self._packs_by_name[pack.name] = pack
1415
1146
        self.revision_index.add_index(pack.revision_index, pack)
1416
1147
        self.inventory_index.add_index(pack.inventory_index, pack)
1417
1148
        self.text_index.add_index(pack.text_index, pack)
1418
1149
        self.signature_index.add_index(pack.signature_index, pack)
1419
 
        if self.chk_index is not None:
1420
 
            self.chk_index.add_index(pack.chk_index, pack)
1421
 
 
 
1150
        
1422
1151
    def all_packs(self):
1423
1152
        """Return a list of all the Pack objects this repository has.
1424
1153
 
1433
1162
 
1434
1163
    def autopack(self):
1435
1164
        """Pack the pack collection incrementally.
1436
 
 
 
1165
        
1437
1166
        This will not attempt global reorganisation or recompression,
1438
1167
        rather it will just ensure that the total number of packs does
1439
1168
        not grow without bound. It uses the _max_pack_count method to
1447
1176
 
1448
1177
        :return: True if packing took place.
1449
1178
        """
1450
 
        while True:
1451
 
            try:
1452
 
                return self._do_autopack()
1453
 
            except errors.RetryAutopack, e:
1454
 
                # If we get a RetryAutopack exception, we should abort the
1455
 
                # current action, and retry.
1456
 
                pass
1457
 
 
1458
 
    def _do_autopack(self):
1459
1179
        # XXX: Should not be needed when the management of indices is sane.
1460
1180
        total_revisions = self.revision_index.combined_index.key_count()
1461
1181
        total_packs = len(self._names)
1462
1182
        if self._max_pack_count(total_revisions) >= total_packs:
1463
1183
            return False
 
1184
        # XXX: the following may want to be a class, to pack with a given
 
1185
        # policy.
 
1186
        mutter('Auto-packing repository %s, which has %d pack files, '
 
1187
            'containing %d revisions into %d packs.', self, total_packs,
 
1188
            total_revisions, self._max_pack_count(total_revisions))
1464
1189
        # determine which packs need changing
1465
1190
        pack_distribution = self.pack_distribution(total_revisions)
1466
1191
        existing_packs = []
1474
1199
                # group their data with the relevant commit, and that may
1475
1200
                # involve rewriting ancient history - which autopack tries to
1476
1201
                # avoid. Alternatively we could not group the data but treat
1477
 
                # each of these as having a single revision, and thus add
 
1202
                # each of these as having a single revision, and thus add 
1478
1203
                # one revision for each to the total revision count, to get
1479
1204
                # a matching distribution.
1480
1205
                continue
1481
1206
            existing_packs.append((revision_count, pack))
1482
1207
        pack_operations = self.plan_autopack_combinations(
1483
1208
            existing_packs, pack_distribution)
1484
 
        num_new_packs = len(pack_operations)
1485
 
        num_old_packs = sum([len(po[1]) for po in pack_operations])
1486
 
        num_revs_affected = sum([po[0] for po in pack_operations])
1487
 
        mutter('Auto-packing repository %s, which has %d pack files, '
1488
 
            'containing %d revisions. Packing %d files into %d affecting %d'
1489
 
            ' revisions', self, total_packs, total_revisions, num_old_packs,
1490
 
            num_new_packs, num_revs_affected)
1491
 
        self._execute_pack_operations(pack_operations,
1492
 
                                      reload_func=self._restart_autopack)
1493
 
        mutter('Auto-packing repository %s completed', self)
 
1209
        self._execute_pack_operations(pack_operations)
1494
1210
        return True
1495
1211
 
1496
 
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
1497
 
                                 reload_func=None):
 
1212
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer):
1498
1213
        """Execute a series of pack operations.
1499
1214
 
1500
1215
        :param pack_operations: A list of [revision_count, packs_to_combine].
1505
1220
            # we may have no-ops from the setup logic
1506
1221
            if len(packs) == 0:
1507
1222
                continue
1508
 
            packer = _packer_class(self, packs, '.autopack',
1509
 
                                   reload_func=reload_func)
1510
 
            try:
1511
 
                packer.pack()
1512
 
            except errors.RetryWithNewPacks:
1513
 
                # An exception is propagating out of this context, make sure
1514
 
                # this packer has cleaned up. Packer() doesn't set its new_pack
1515
 
                # state into the RepositoryPackCollection object, so we only
1516
 
                # have access to it directly here.
1517
 
                if packer.new_pack is not None:
1518
 
                    packer.new_pack.abort()
1519
 
                raise
 
1223
            _packer_class(self, packs, '.autopack').pack()
1520
1224
            for pack in packs:
1521
1225
                self._remove_pack_from_memory(pack)
1522
1226
        # record the newly available packs and stop advertising the old
1526
1230
        for revision_count, packs in pack_operations:
1527
1231
            self._obsolete_packs(packs)
1528
1232
 
1529
 
    def _flush_new_pack(self):
1530
 
        if self._new_pack is not None:
1531
 
            self._new_pack.flush()
1532
 
 
1533
1233
    def lock_names(self):
1534
1234
        """Acquire the mutex around the pack-names index.
1535
 
 
 
1235
        
1536
1236
        This cannot be used in the middle of a read-only transaction on the
1537
1237
        repository.
1538
1238
        """
1539
1239
        self.repo.control_files.lock_write()
1540
1240
 
1541
 
    def _already_packed(self):
1542
 
        """Is the collection already packed?"""
1543
 
        return len(self._names) < 2
1544
 
 
1545
1241
    def pack(self):
1546
1242
        """Pack the pack collection totally."""
1547
1243
        self.ensure_loaded()
1548
1244
        total_packs = len(self._names)
1549
 
        if self._already_packed():
 
1245
        if total_packs < 2:
1550
1246
            # This is arguably wrong because we might not be optimal, but for
1551
1247
            # now lets leave it in. (e.g. reconcile -> one pack. But not
1552
1248
            # optimal.
1580
1276
        # plan out what packs to keep, and what to reorganise
1581
1277
        while len(existing_packs):
1582
1278
            # take the largest pack, and if its less than the head of the
1583
 
            # distribution chart we will include its contents in the new pack
1584
 
            # for that position. If its larger, we remove its size from the
 
1279
            # distribution chart we will include its contents in the new pack for
 
1280
            # that position. If its larger, we remove its size from the
1585
1281
            # distribution chart
1586
1282
            next_pack_rev_count, next_pack = existing_packs.pop(0)
1587
1283
            if next_pack_rev_count >= pack_distribution[0]:
1604
1300
                    # this pack is used up, shift left.
1605
1301
                    del pack_distribution[0]
1606
1302
                    pack_operations.append([0, []])
1607
 
        # Now that we know which pack files we want to move, shove them all
1608
 
        # into a single pack file.
1609
 
        final_rev_count = 0
1610
 
        final_pack_list = []
1611
 
        for num_revs, pack_files in pack_operations:
1612
 
            final_rev_count += num_revs
1613
 
            final_pack_list.extend(pack_files)
1614
 
        if len(final_pack_list) == 1:
1615
 
            raise AssertionError('We somehow generated an autopack with a'
1616
 
                ' single pack file being moved.')
1617
 
            return []
1618
 
        return [[final_rev_count, final_pack_list]]
 
1303
        
 
1304
        return pack_operations
1619
1305
 
1620
1306
    def ensure_loaded(self):
1621
 
        """Ensure we have read names from disk.
1622
 
 
1623
 
        :return: True if the disk names had not been previously read.
1624
 
        """
1625
1307
        # NB: if you see an assertion error here, its probably access against
1626
1308
        # an unlocked repo. Naughty.
1627
1309
        if not self.repo.is_locked():
1633
1315
                name = key[0]
1634
1316
                self._names[name] = self._parse_index_sizes(value)
1635
1317
                self._packs_at_load.add((key, value))
1636
 
            result = True
1637
 
        else:
1638
 
            result = False
1639
1318
        # populate all the metadata.
1640
1319
        self.all_packs()
1641
 
        return result
1642
1320
 
1643
1321
    def _parse_index_sizes(self, value):
1644
1322
        """Parse a string of index sizes."""
1657
1335
            inv_index = self._make_index(name, '.iix')
1658
1336
            txt_index = self._make_index(name, '.tix')
1659
1337
            sig_index = self._make_index(name, '.six')
1660
 
            if self.chk_index is not None:
1661
 
                chk_index = self._make_index(name, '.cix')
1662
 
            else:
1663
 
                chk_index = None
1664
1338
            result = ExistingPack(self._pack_transport, name, rev_index,
1665
 
                inv_index, txt_index, sig_index, chk_index)
 
1339
                inv_index, txt_index, sig_index)
1666
1340
            self.add_pack_to_memory(result)
1667
1341
            return result
1668
1342
 
1669
 
    def _resume_pack(self, name):
1670
 
        """Get a suspended Pack object by name.
1671
 
 
1672
 
        :param name: The name of the pack - e.g. '123456'
1673
 
        :return: A Pack object.
1674
 
        """
1675
 
        if not re.match('[a-f0-9]{32}', name):
1676
 
            # Tokens should be md5sums of the suspended pack file, i.e. 32 hex
1677
 
            # digits.
1678
 
            raise errors.UnresumableWriteGroup(
1679
 
                self.repo, [name], 'Malformed write group token')
1680
 
        try:
1681
 
            rev_index = self._make_index(name, '.rix', resume=True)
1682
 
            inv_index = self._make_index(name, '.iix', resume=True)
1683
 
            txt_index = self._make_index(name, '.tix', resume=True)
1684
 
            sig_index = self._make_index(name, '.six', resume=True)
1685
 
            result = ResumedPack(name, rev_index, inv_index, txt_index,
1686
 
                sig_index, self._upload_transport, self._pack_transport,
1687
 
                self._index_transport, self)
1688
 
        except errors.NoSuchFile, e:
1689
 
            raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
1690
 
        self.add_pack_to_memory(result)
1691
 
        self._resumed_packs.append(result)
1692
 
        return result
1693
 
 
1694
1343
    def allocate(self, a_new_pack):
1695
1344
        """Allocate name in the list of packs.
1696
1345
 
1706
1355
 
1707
1356
    def _iter_disk_pack_index(self):
1708
1357
        """Iterate over the contents of the pack-names index.
1709
 
 
 
1358
        
1710
1359
        This is used when loading the list from disk, and before writing to
1711
1360
        detect updates from others during our write operation.
1712
1361
        :return: An iterator of the index contents.
1713
1362
        """
1714
 
        return self._index_class(self.transport, 'pack-names', None
 
1363
        return GraphIndex(self.transport, 'pack-names', None
1715
1364
                ).iter_all_entries()
1716
1365
 
1717
 
    def _make_index(self, name, suffix, resume=False):
 
1366
    def _make_index(self, name, suffix):
1718
1367
        size_offset = self._suffix_offsets[suffix]
1719
1368
        index_name = name + suffix
1720
 
        if resume:
1721
 
            transport = self._upload_transport
1722
 
            index_size = transport.stat(index_name).st_size
1723
 
        else:
1724
 
            transport = self._index_transport
1725
 
            index_size = self._names[name][size_offset]
1726
 
        return self._index_class(transport, index_name, index_size)
 
1369
        index_size = self._names[name][size_offset]
 
1370
        return GraphIndex(
 
1371
            self._index_transport, index_name, index_size)
1727
1372
 
1728
1373
    def _max_pack_count(self, total_revisions):
1729
1374
        """Return the maximum number of packs to use for total revisions.
1730
 
 
 
1375
        
1731
1376
        :param total_revisions: The total number of revisions in the
1732
1377
            repository.
1733
1378
        """
1762
1407
            # TODO: Probably needs to know all possible indices for this pack
1763
1408
            # - or maybe list the directory and move all indices matching this
1764
1409
            # name whether we recognize it or not?
1765
 
            suffixes = ['.iix', '.six', '.tix', '.rix']
1766
 
            if self.chk_index is not None:
1767
 
                suffixes.append('.cix')
1768
 
            for suffix in suffixes:
 
1410
            for suffix in ('.iix', '.six', '.tix', '.rix'):
1769
1411
                self._index_transport.rename(pack.name + suffix,
1770
1412
                    '../obsolete_packs/' + pack.name + suffix)
1771
1413
 
1791
1433
 
1792
1434
    def _remove_pack_from_memory(self, pack):
1793
1435
        """Remove pack from the packs accessed by this repository.
1794
 
 
 
1436
        
1795
1437
        Only affects memory state, until self._save_pack_names() is invoked.
1796
1438
        """
1797
1439
        self._names.pop(pack.name)
1798
1440
        self._packs_by_name.pop(pack.name)
1799
1441
        self._remove_pack_indices(pack)
1800
 
        self.packs.remove(pack)
1801
1442
 
1802
1443
    def _remove_pack_indices(self, pack):
1803
1444
        """Remove the indices for pack from the aggregated indices."""
1805
1446
        self.inventory_index.remove_index(pack.inventory_index, pack)
1806
1447
        self.text_index.remove_index(pack.text_index, pack)
1807
1448
        self.signature_index.remove_index(pack.signature_index, pack)
1808
 
        if self.chk_index is not None:
1809
 
            self.chk_index.remove_index(pack.chk_index, pack)
1810
1449
 
1811
1450
    def reset(self):
1812
1451
        """Clear all cached data."""
1821
1460
        self.repo._text_knit = None
1822
1461
        # cached inventory data
1823
1462
        self.inventory_index.clear()
1824
 
        # cached chk data
1825
 
        if self.chk_index is not None:
1826
 
            self.chk_index.clear()
1827
1463
        # remove the open pack
1828
1464
        self._new_pack = None
1829
1465
        # information about packs.
1832
1468
        self._packs_by_name = {}
1833
1469
        self._packs_at_load = None
1834
1470
 
 
1471
    def _make_index_map(self, index_suffix):
 
1472
        """Return information on existing indices.
 
1473
 
 
1474
        :param suffix: Index suffix added to pack name.
 
1475
 
 
1476
        :returns: (pack_map, indices) where indices is a list of GraphIndex 
 
1477
        objects, and pack_map is a mapping from those objects to the 
 
1478
        pack tuple they describe.
 
1479
        """
 
1480
        # TODO: stop using this; it creates new indices unnecessarily.
 
1481
        self.ensure_loaded()
 
1482
        suffix_map = {'.rix': 'revision_index',
 
1483
            '.six': 'signature_index',
 
1484
            '.iix': 'inventory_index',
 
1485
            '.tix': 'text_index',
 
1486
        }
 
1487
        return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
 
1488
            suffix_map[index_suffix])
 
1489
 
 
1490
    def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
 
1491
        """Convert a list of packs to an index pack map and index list.
 
1492
 
 
1493
        :param packs: The packs list to process.
 
1494
        :param index_attribute: The attribute that the desired index is found
 
1495
            on.
 
1496
        :return: A tuple (map, list) where map contains the dict from
 
1497
            index:pack_tuple, and lsit contains the indices in the same order
 
1498
            as the packs list.
 
1499
        """
 
1500
        indices = []
 
1501
        pack_map = {}
 
1502
        for pack in packs:
 
1503
            index = getattr(pack, index_attribute)
 
1504
            indices.append(index)
 
1505
            pack_map[index] = (pack.pack_transport, pack.file_name())
 
1506
        return pack_map, indices
 
1507
 
 
1508
    def _index_contents(self, pack_map, key_filter=None):
 
1509
        """Get an iterable of the index contents from a pack_map.
 
1510
 
 
1511
        :param pack_map: A map from indices to pack details.
 
1512
        :param key_filter: An optional filter to limit the
 
1513
            keys returned.
 
1514
        """
 
1515
        indices = [index for index in pack_map.iterkeys()]
 
1516
        all_index = CombinedGraphIndex(indices)
 
1517
        if key_filter is None:
 
1518
            return all_index.iter_all_entries()
 
1519
        else:
 
1520
            return all_index.iter_entries(key_filter)
 
1521
 
1835
1522
    def _unlock_names(self):
1836
1523
        """Release the mutex around the pack-names index."""
1837
1524
        self.repo.control_files.unlock()
1838
1525
 
1839
 
    def _diff_pack_names(self):
1840
 
        """Read the pack names from disk, and compare it to the one in memory.
1841
 
 
1842
 
        :return: (disk_nodes, deleted_nodes, new_nodes)
1843
 
            disk_nodes    The final set of nodes that should be referenced
1844
 
            deleted_nodes Nodes which have been removed from when we started
1845
 
            new_nodes     Nodes that are newly introduced
1846
 
        """
1847
 
        # load the disk nodes across
1848
 
        disk_nodes = set()
1849
 
        for index, key, value in self._iter_disk_pack_index():
1850
 
            disk_nodes.add((key, value))
1851
 
 
1852
 
        # do a two-way diff against our original content
1853
 
        current_nodes = set()
1854
 
        for name, sizes in self._names.iteritems():
1855
 
            current_nodes.add(
1856
 
                ((name, ), ' '.join(str(size) for size in sizes)))
1857
 
 
1858
 
        # Packs no longer present in the repository, which were present when we
1859
 
        # locked the repository
1860
 
        deleted_nodes = self._packs_at_load - current_nodes
1861
 
        # Packs which this process is adding
1862
 
        new_nodes = current_nodes - self._packs_at_load
1863
 
 
1864
 
        # Update the disk_nodes set to include the ones we are adding, and
1865
 
        # remove the ones which were removed by someone else
1866
 
        disk_nodes.difference_update(deleted_nodes)
1867
 
        disk_nodes.update(new_nodes)
1868
 
 
1869
 
        return disk_nodes, deleted_nodes, new_nodes
1870
 
 
1871
 
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1872
 
        """Given the correct set of pack files, update our saved info.
1873
 
 
1874
 
        :return: (removed, added, modified)
1875
 
            removed     pack names removed from self._names
1876
 
            added       pack names added to self._names
1877
 
            modified    pack names that had changed value
1878
 
        """
1879
 
        removed = []
1880
 
        added = []
1881
 
        modified = []
1882
 
        ## self._packs_at_load = disk_nodes
 
1526
    def _save_pack_names(self, clear_obsolete_packs=False):
 
1527
        """Save the list of packs.
 
1528
 
 
1529
        This will take out the mutex around the pack names list for the
 
1530
        duration of the method call. If concurrent updates have been made, a
 
1531
        three-way merge between the current list and the current in memory list
 
1532
        is performed.
 
1533
 
 
1534
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1535
            obsolete_packs directory.
 
1536
        """
 
1537
        self.lock_names()
 
1538
        try:
 
1539
            builder = GraphIndexBuilder()
 
1540
            # load the disk nodes across
 
1541
            disk_nodes = set()
 
1542
            for index, key, value in self._iter_disk_pack_index():
 
1543
                disk_nodes.add((key, value))
 
1544
            # do a two-way diff against our original content
 
1545
            current_nodes = set()
 
1546
            for name, sizes in self._names.iteritems():
 
1547
                current_nodes.add(
 
1548
                    ((name, ), ' '.join(str(size) for size in sizes)))
 
1549
            deleted_nodes = self._packs_at_load - current_nodes
 
1550
            new_nodes = current_nodes - self._packs_at_load
 
1551
            disk_nodes.difference_update(deleted_nodes)
 
1552
            disk_nodes.update(new_nodes)
 
1553
            # TODO: handle same-name, index-size-changes here - 
 
1554
            # e.g. use the value from disk, not ours, *unless* we're the one
 
1555
            # changing it.
 
1556
            for key, value in disk_nodes:
 
1557
                builder.add_node(key, value)
 
1558
            self.transport.put_file('pack-names', builder.finish(),
 
1559
                mode=self.repo.bzrdir._get_file_mode())
 
1560
            # move the baseline forward
 
1561
            self._packs_at_load = disk_nodes
 
1562
            if clear_obsolete_packs:
 
1563
                self._clear_obsolete_packs()
 
1564
        finally:
 
1565
            self._unlock_names()
 
1566
        # synchronise the memory packs list with what we just wrote:
1883
1567
        new_names = dict(disk_nodes)
1884
1568
        # drop no longer present nodes
1885
1569
        for pack in self.all_packs():
1886
1570
            if (pack.name,) not in new_names:
1887
 
                removed.append(pack.name)
1888
1571
                self._remove_pack_from_memory(pack)
1889
1572
        # add new nodes/refresh existing ones
1890
1573
        for key, value in disk_nodes:
1904
1587
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
1905
1588
                    self._names[name] = sizes
1906
1589
                    self.get_pack_by_name(name)
1907
 
                    modified.append(name)
1908
1590
            else:
1909
1591
                # new
1910
1592
                self._names[name] = sizes
1911
1593
                self.get_pack_by_name(name)
1912
 
                added.append(name)
1913
 
        return removed, added, modified
1914
 
 
1915
 
    def _save_pack_names(self, clear_obsolete_packs=False):
1916
 
        """Save the list of packs.
1917
 
 
1918
 
        This will take out the mutex around the pack names list for the
1919
 
        duration of the method call. If concurrent updates have been made, a
1920
 
        three-way merge between the current list and the current in memory list
1921
 
        is performed.
1922
 
 
1923
 
        :param clear_obsolete_packs: If True, clear out the contents of the
1924
 
            obsolete_packs directory.
1925
 
        """
1926
 
        self.lock_names()
1927
 
        try:
1928
 
            builder = self._index_builder_class()
1929
 
            disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
1930
 
            # TODO: handle same-name, index-size-changes here -
1931
 
            # e.g. use the value from disk, not ours, *unless* we're the one
1932
 
            # changing it.
1933
 
            for key, value in disk_nodes:
1934
 
                builder.add_node(key, value)
1935
 
            self.transport.put_file('pack-names', builder.finish(),
1936
 
                mode=self.repo.bzrdir._get_file_mode())
1937
 
            # move the baseline forward
1938
 
            self._packs_at_load = disk_nodes
1939
 
            if clear_obsolete_packs:
1940
 
                self._clear_obsolete_packs()
1941
 
        finally:
1942
 
            self._unlock_names()
1943
 
        # synchronise the memory packs list with what we just wrote:
1944
 
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1945
 
 
1946
 
    def reload_pack_names(self):
1947
 
        """Sync our pack listing with what is present in the repository.
1948
 
 
1949
 
        This should be called when we find out that something we thought was
1950
 
        present is now missing. This happens when another process re-packs the
1951
 
        repository, etc.
1952
 
 
1953
 
        :return: True if the in-memory list of packs has been altered at all.
1954
 
        """
1955
 
        # The ensure_loaded call is to handle the case where the first call
1956
 
        # made involving the collection was to reload_pack_names, where we 
1957
 
        # don't have a view of disk contents. Its a bit of a bandaid, and
1958
 
        # causes two reads of pack-names, but its a rare corner case not struck
1959
 
        # with regular push/pull etc.
1960
 
        first_read = self.ensure_loaded()
1961
 
        if first_read:
1962
 
            return True
1963
 
        # out the new value.
1964
 
        disk_nodes, _, _ = self._diff_pack_names()
1965
 
        self._packs_at_load = disk_nodes
1966
 
        (removed, added,
1967
 
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1968
 
        if removed or added or modified:
1969
 
            return True
1970
 
        return False
1971
 
 
1972
 
    def _restart_autopack(self):
1973
 
        """Reload the pack names list, and restart the autopack code."""
1974
 
        if not self.reload_pack_names():
1975
 
            # Re-raise the original exception, because something went missing
1976
 
            # and a restart didn't find it
1977
 
            raise
1978
 
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1979
1594
 
1980
1595
    def _clear_obsolete_packs(self):
1981
1596
        """Delete everything from the obsolete-packs directory.
1991
1606
        # Do not permit preparation for writing if we're not in a 'write lock'.
1992
1607
        if not self.repo.is_write_locked():
1993
1608
            raise errors.NotWriteLocked(self)
1994
 
        self._new_pack = self.pack_factory(self, upload_suffix='.pack',
 
1609
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
 
1610
            self._pack_transport, upload_suffix='.pack',
1995
1611
            file_mode=self.repo.bzrdir._get_file_mode())
1996
1612
        # allow writing: queue writes to a new index
1997
1613
        self.revision_index.add_writable_index(self._new_pack.revision_index,
2002
1618
            self._new_pack)
2003
1619
        self.signature_index.add_writable_index(self._new_pack.signature_index,
2004
1620
            self._new_pack)
2005
 
        if self.chk_index is not None:
2006
 
            self.chk_index.add_writable_index(self._new_pack.chk_index,
2007
 
                self._new_pack)
2008
 
            self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
2009
1621
 
2010
1622
        self.repo.inventories._index._add_callback = self.inventory_index.add_callback
2011
1623
        self.repo.revisions._index._add_callback = self.revision_index.add_callback
2016
1628
        # FIXME: just drop the transient index.
2017
1629
        # forget what names there are
2018
1630
        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[:]
 
1631
            self._new_pack.abort()
 
1632
            self._remove_pack_indices(self._new_pack)
 
1633
            self._new_pack = None
2038
1634
        self.repo._text_knit = None
2039
1635
 
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
1636
    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
1637
        self._remove_pack_indices(self._new_pack)
2060
 
        should_autopack = False
2061
1638
        if self._new_pack.data_inserted():
2062
1639
            # get all the data to disk and read to use
2063
1640
            self._new_pack.finish()
2064
1641
            self.allocate(self._new_pack)
2065
1642
            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
1643
            if not self.autopack():
2081
1644
                # when autopack takes no steps, the names list is still
2082
1645
                # unsaved.
2083
1646
                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
1647
        else:
2095
1648
            self._new_pack.abort()
2096
1649
            self._new_pack = None
2097
 
        self._remove_resumed_pack_indices()
2098
1650
        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
1651
 
2105
1652
 
2106
1653
class KnitPackRepository(KnitRepository):
2107
1654
    """Repository with knit objects stored inside pack containers.
2108
 
 
 
1655
    
2109
1656
    The layering for a KnitPackRepository is:
2110
1657
 
2111
1658
    Graph        |  HPSS    | Repository public layer |
2125
1672
      pack file. The GraphIndex layer works in N-tuples and is unaware of any
2126
1673
      semantic value.
2127
1674
    ===================================================
2128
 
 
 
1675
    
2129
1676
    """
2130
1677
 
2131
1678
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2136
1683
        self._pack_collection = RepositoryPackCollection(self, self._transport,
2137
1684
            index_transport,
2138
1685
            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
 
            )
 
1686
            self._transport.clone('packs'))
2144
1687
        self.inventories = KnitVersionedFiles(
2145
1688
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2146
1689
                add_callback=self._pack_collection.inventory_index.add_callback,
2165
1708
                deltas=True, parents=True, is_locked=self.is_locked),
2166
1709
            data_access=self._pack_collection.text_index.data_access,
2167
1710
            max_delta_chain=200)
2168
 
        if _format.supports_chks:
2169
 
            # No graph, no compression:- references from chks are between
2170
 
            # different objects not temporal versions of the same; and without
2171
 
            # some sort of temporal structure knit compression will just fail.
2172
 
            self.chk_bytes = KnitVersionedFiles(
2173
 
                _KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2174
 
                    add_callback=self._pack_collection.chk_index.add_callback,
2175
 
                    deltas=False, parents=False, is_locked=self.is_locked),
2176
 
                data_access=self._pack_collection.chk_index.data_access,
2177
 
                max_delta_chain=0)
2178
 
        else:
2179
 
            self.chk_bytes = None
2180
1711
        # True when the repository object is 'write locked' (as opposed to the
2181
 
        # physical lock only taken out around changes to the pack-names list.)
 
1712
        # physical lock only taken out around changes to the pack-names list.) 
2182
1713
        # Another way to represent this would be a decorator around the control
2183
1714
        # files object that presents logical locks as physical ones - if this
2184
1715
        # gets ugly consider that alternative design. RBC 20071011
2188
1719
        self._reconcile_does_inventory_gc = True
2189
1720
        self._reconcile_fixes_text_parents = True
2190
1721
        self._reconcile_backsup_inventory = False
 
1722
        self._fetch_order = 'unordered'
2191
1723
 
2192
1724
    def _warn_if_deprecated(self):
2193
1725
        # This class isn't deprecated, but one sub-format is
2217
1749
            revision_nodes = self._pack_collection.revision_index \
2218
1750
                .combined_index.iter_all_entries()
2219
1751
            index_positions = []
2220
 
            # Get the cached index values for all revisions, and also the
2221
 
            # location in each index of the revision text so we can perform
2222
 
            # linear IO.
 
1752
            # Get the cached index values for all revisions, and also the location
 
1753
            # in each index of the revision text so we can perform linear IO.
2223
1754
            for index, key, value, refs in revision_nodes:
2224
 
                node = (index, key, value, refs)
2225
 
                index_memo = self.revisions._index._node_to_position(node)
2226
 
                assert index_memo[0] == index
2227
 
                index_positions.append((index_memo, key[0],
2228
 
                                       tuple(parent[0] for parent in refs[0])))
2229
 
                pb.update("Reading revision index", 0, 0)
 
1755
                pos, length = value[1:].split(' ')
 
1756
                index_positions.append((index, int(pos), key[0],
 
1757
                    tuple(parent[0] for parent in refs[0])))
 
1758
                pb.update("Reading revision index.", 0, 0)
2230
1759
            index_positions.sort()
2231
 
            batch_size = 1000
2232
 
            pb.update("Checking cached revision graph", 0,
2233
 
                      len(index_positions))
2234
 
            for offset in xrange(0, len(index_positions), 1000):
2235
 
                pb.update("Checking cached revision graph", offset)
2236
 
                to_query = index_positions[offset:offset + batch_size]
 
1760
            batch_count = len(index_positions) / 1000 + 1
 
1761
            pb.update("Checking cached revision graph.", 0, batch_count)
 
1762
            for offset in xrange(batch_count):
 
1763
                pb.update("Checking cached revision graph.", offset)
 
1764
                to_query = index_positions[offset * 1000:(offset + 1) * 1000]
2237
1765
                if not to_query:
2238
1766
                    break
2239
 
                rev_ids = [item[1] for item in to_query]
 
1767
                rev_ids = [item[2] for item in to_query]
2240
1768
                revs = self.get_revisions(rev_ids)
2241
1769
                for revision, item in zip(revs, to_query):
2242
 
                    index_parents = item[2]
 
1770
                    index_parents = item[3]
2243
1771
                    rev_parents = tuple(revision.parent_ids)
2244
1772
                    if index_parents != rev_parents:
2245
 
                        result.append((revision.revision_id, index_parents,
2246
 
                                       rev_parents))
 
1773
                        result.append((revision.revision_id, index_parents, rev_parents))
2247
1774
        finally:
2248
1775
            pb.finished()
2249
1776
        return result
2250
1777
 
 
1778
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
 
1779
    def get_parents(self, revision_ids):
 
1780
        """See graph._StackedParentsProvider.get_parents."""
 
1781
        parent_map = self.get_parent_map(revision_ids)
 
1782
        return [parent_map.get(r, None) for r in revision_ids]
 
1783
 
2251
1784
    def _make_parents_provider(self):
2252
1785
        return graph.CachingParentsProvider(self)
2253
1786
 
2254
1787
    def _refresh_data(self):
2255
 
        if not self.is_locked():
2256
 
            return
2257
 
        self._pack_collection.reload_pack_names()
 
1788
        if self._write_lock_count == 1 or (
 
1789
            self.control_files._lock_count == 1 and
 
1790
            self.control_files._lock_mode == 'r'):
 
1791
            # forget what names there are
 
1792
            self._pack_collection.reset()
 
1793
            # XXX: Better to do an in-memory merge when acquiring a new lock -
 
1794
            # factor out code from _save_pack_names.
 
1795
            self._pack_collection.ensure_loaded()
2258
1796
 
2259
1797
    def _start_write_group(self):
2260
1798
        self._pack_collection._start_write_group()
2262
1800
    def _commit_write_group(self):
2263
1801
        return self._pack_collection._commit_write_group()
2264
1802
 
2265
 
    def suspend_write_group(self):
2266
 
        # XXX check self._write_group is self.get_transaction()?
2267
 
        tokens = self._pack_collection._suspend_write_group()
2268
 
        self._write_group = None
2269
 
        return tokens
2270
 
 
2271
 
    def _resume_write_group(self, tokens):
2272
 
        self._start_write_group()
2273
 
        self._pack_collection._resume_write_group(tokens)
2274
 
 
2275
1803
    def get_transaction(self):
2276
1804
        if self._write_lock_count:
2277
1805
            return self._transaction
2285
1813
        return self._write_lock_count
2286
1814
 
2287
1815
    def lock_write(self, token=None):
2288
 
        locked = self.is_locked()
2289
 
        if not self._write_lock_count and locked:
 
1816
        if not self._write_lock_count and self.is_locked():
2290
1817
            raise errors.ReadOnlyError(self)
2291
1818
        self._write_lock_count += 1
2292
1819
        if self._write_lock_count == 1:
2294
1821
            for repo in self._fallback_repositories:
2295
1822
                # Writes don't affect fallback repos
2296
1823
                repo.lock_read()
2297
 
        if not locked:
2298
 
            self._refresh_data()
 
1824
        self._refresh_data()
2299
1825
 
2300
1826
    def lock_read(self):
2301
 
        locked = self.is_locked()
2302
1827
        if self._write_lock_count:
2303
1828
            self._write_lock_count += 1
2304
1829
        else:
2306
1831
            for repo in self._fallback_repositories:
2307
1832
                # Writes don't affect fallback repos
2308
1833
                repo.lock_read()
2309
 
        if not locked:
2310
 
            self._refresh_data()
 
1834
        self._refresh_data()
2311
1835
 
2312
1836
    def leave_lock_in_place(self):
2313
1837
        # not supported - raise an error
2334
1858
        reconciler.reconcile()
2335
1859
        return reconciler
2336
1860
 
2337
 
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
2338
 
        packer = ReconcilePacker(collection, packs, extension, revs)
2339
 
        return packer.pack(pb)
2340
 
 
2341
1861
    def unlock(self):
2342
1862
        if self._write_lock_count == 1 and self._write_group is not None:
2343
1863
            self.abort_write_group()
2360
1880
                repo.unlock()
2361
1881
 
2362
1882
 
2363
 
class CHKInventoryRepository(KnitPackRepository):
2364
 
    """subclass of KnitPackRepository that uses CHK based inventories."""
2365
 
 
2366
 
    def _add_inventory_checked(self, revision_id, inv, parents):
2367
 
        """Add inv to the repository after checking the inputs.
2368
 
 
2369
 
        This function can be overridden to allow different inventory styles.
2370
 
 
2371
 
        :seealso: add_inventory, for the contract.
2372
 
        """
2373
 
        # make inventory
2374
 
        serializer = self._format._serializer
2375
 
        result = CHKInventory.from_inventory(self.chk_bytes, inv,
2376
 
            maximum_size=serializer.maximum_size,
2377
 
            search_key_name=serializer.search_key_name)
2378
 
        inv_lines = result.to_lines()
2379
 
        return self._inventory_add_lines(revision_id, parents,
2380
 
            inv_lines, check_content=False)
2381
 
 
2382
 
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
2383
 
                               parents, basis_inv=None, propagate_caches=False):
2384
 
        """Add a new inventory expressed as a delta against another revision.
2385
 
 
2386
 
        :param basis_revision_id: The inventory id the delta was created
2387
 
            against.
2388
 
        :param delta: The inventory delta (see Inventory.apply_delta for
2389
 
            details).
2390
 
        :param new_revision_id: The revision id that the inventory is being
2391
 
            added for.
2392
 
        :param parents: The revision ids of the parents that revision_id is
2393
 
            known to have and are in the repository already. These are supplied
2394
 
            for repositories that depend on the inventory graph for revision
2395
 
            graph access, as well as for those that pun ancestry with delta
2396
 
            compression.
2397
 
        :param basis_inv: The basis inventory if it is already known,
2398
 
            otherwise None.
2399
 
        :param propagate_caches: If True, the caches for this inventory are
2400
 
          copied to and updated for the result if possible.
2401
 
 
2402
 
        :returns: (validator, new_inv)
2403
 
            The validator(which is a sha1 digest, though what is sha'd is
2404
 
            repository format specific) of the serialized inventory, and the
2405
 
            resulting inventory.
2406
 
        """
2407
 
        if basis_revision_id == _mod_revision.NULL_REVISION:
2408
 
            return KnitPackRepository.add_inventory_by_delta(self,
2409
 
                basis_revision_id, delta, new_revision_id, parents)
2410
 
        if not self.is_in_write_group():
2411
 
            raise AssertionError("%r not in write group" % (self,))
2412
 
        _mod_revision.check_not_reserved_id(new_revision_id)
2413
 
        basis_tree = self.revision_tree(basis_revision_id)
2414
 
        basis_tree.lock_read()
2415
 
        try:
2416
 
            if basis_inv is None:
2417
 
                basis_inv = basis_tree.inventory
2418
 
            result = basis_inv.create_by_apply_delta(delta, new_revision_id,
2419
 
                propagate_caches=propagate_caches)
2420
 
            inv_lines = result.to_lines()
2421
 
            return self._inventory_add_lines(new_revision_id, parents,
2422
 
                inv_lines, check_content=False), result
2423
 
        finally:
2424
 
            basis_tree.unlock()
2425
 
 
2426
 
    def _iter_inventories(self, revision_ids):
2427
 
        """Iterate over many inventory objects."""
2428
 
        keys = [(revision_id,) for revision_id in revision_ids]
2429
 
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
2430
 
        texts = {}
2431
 
        for record in stream:
2432
 
            if record.storage_kind != 'absent':
2433
 
                texts[record.key] = record.get_bytes_as('fulltext')
2434
 
            else:
2435
 
                raise errors.NoSuchRevision(self, record.key)
2436
 
        for key in keys:
2437
 
            yield CHKInventory.deserialise(self.chk_bytes, texts[key], key)
2438
 
 
2439
 
    def _iter_inventory_xmls(self, revision_ids):
2440
 
        # Without a native 'xml' inventory, this method doesn't make sense, so
2441
 
        # make it raise to trap naughty direct users.
2442
 
        raise NotImplementedError(self._iter_inventory_xmls)
2443
 
 
2444
 
    def _find_revision_outside_set(self, revision_ids):
2445
 
        revision_set = frozenset(revision_ids)
2446
 
        for revid in revision_ids:
2447
 
            parent_ids = self.get_parent_map([revid]).get(revid, ())
2448
 
            for parent in parent_ids:
2449
 
                if parent in revision_set:
2450
 
                    # Parent is not outside the set
2451
 
                    continue
2452
 
                if parent not in self.get_parent_map([parent]):
2453
 
                    # Parent is a ghost
2454
 
                    continue
2455
 
                return parent
2456
 
        return _mod_revision.NULL_REVISION
2457
 
 
2458
 
    def _find_file_keys_to_fetch(self, revision_ids, pb):
2459
 
        rich_root = self.supports_rich_root()
2460
 
        revision_outside_set = self._find_revision_outside_set(revision_ids)
2461
 
        if revision_outside_set == _mod_revision.NULL_REVISION:
2462
 
            uninteresting_root_keys = set()
2463
 
        else:
2464
 
            uninteresting_inv = self.get_inventory(revision_outside_set)
2465
 
            uninteresting_root_keys = set([uninteresting_inv.id_to_entry.key()])
2466
 
        interesting_root_keys = set()
2467
 
        for idx, inv in enumerate(self.iter_inventories(revision_ids)):
2468
 
            interesting_root_keys.add(inv.id_to_entry.key())
2469
 
        revision_ids = frozenset(revision_ids)
2470
 
        file_id_revisions = {}
2471
 
        bytes_to_info = CHKInventory._bytes_to_utf8name_key
2472
 
        for records, items in chk_map.iter_interesting_nodes(self.chk_bytes,
2473
 
                    interesting_root_keys, uninteresting_root_keys,
2474
 
                    pb=pb):
2475
 
            # This is cheating a bit to use the last grabbed 'inv', but it
2476
 
            # works
2477
 
            for name, bytes in items:
2478
 
                (name_utf8, file_id, revision_id) = bytes_to_info(bytes)
2479
 
                if not rich_root and name_utf8 == '':
2480
 
                    continue
2481
 
                if revision_id in revision_ids:
2482
 
                    # Would we rather build this up into file_id => revision
2483
 
                    # maps?
2484
 
                    try:
2485
 
                        file_id_revisions[file_id].add(revision_id)
2486
 
                    except KeyError:
2487
 
                        file_id_revisions[file_id] = set([revision_id])
2488
 
        for file_id, revisions in file_id_revisions.iteritems():
2489
 
            yield ('file', file_id, revisions)
2490
 
 
2491
 
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
2492
 
        """Find the file ids and versions affected by revisions.
2493
 
 
2494
 
        :param revisions: an iterable containing revision ids.
2495
 
        :param _inv_weave: The inventory weave from this repository or None.
2496
 
            If None, the inventory weave will be opened automatically.
2497
 
        :return: a dictionary mapping altered file-ids to an iterable of
2498
 
            revision_ids. Each altered file-ids has the exact revision_ids that
2499
 
            altered it listed explicitly.
2500
 
        """
2501
 
        rich_roots = self.supports_rich_root()
2502
 
        result = {}
2503
 
        pb = ui.ui_factory.nested_progress_bar()
2504
 
        try:
2505
 
            total = len(revision_ids)
2506
 
            for pos, inv in enumerate(self.iter_inventories(revision_ids)):
2507
 
                pb.update("Finding text references", pos, total)
2508
 
                for entry in inv.iter_just_entries():
2509
 
                    if entry.revision != inv.revision_id:
2510
 
                        continue
2511
 
                    if not rich_roots and entry.file_id == inv.root_id:
2512
 
                        continue
2513
 
                    alterations = result.setdefault(entry.file_id, set([]))
2514
 
                    alterations.add(entry.revision)
2515
 
            return result
2516
 
        finally:
2517
 
            pb.finished()
2518
 
 
2519
 
    def find_text_key_references(self):
2520
 
        """Find the text key references within the repository.
2521
 
 
2522
 
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
2523
 
            to whether they were referred to by the inventory of the
2524
 
            revision_id that they contain. The inventory texts from all present
2525
 
            revision ids are assessed to generate this report.
2526
 
        """
2527
 
        # XXX: Slow version but correct: rewrite as a series of delta
2528
 
        # examinations/direct tree traversal. Note that that will require care
2529
 
        # as a common node is reachable both from the inventory that added it,
2530
 
        # and others afterwards.
2531
 
        revision_keys = self.revisions.keys()
2532
 
        result = {}
2533
 
        rich_roots = self.supports_rich_root()
2534
 
        pb = ui.ui_factory.nested_progress_bar()
2535
 
        try:
2536
 
            all_revs = self.all_revision_ids()
2537
 
            total = len(all_revs)
2538
 
            for pos, inv in enumerate(self.iter_inventories(all_revs)):
2539
 
                pb.update("Finding text references", pos, total)
2540
 
                for _, entry in inv.iter_entries():
2541
 
                    if not rich_roots and entry.file_id == inv.root_id:
2542
 
                        continue
2543
 
                    key = (entry.file_id, entry.revision)
2544
 
                    result.setdefault(key, False)
2545
 
                    if entry.revision == inv.revision_id:
2546
 
                        result[key] = True
2547
 
            return result
2548
 
        finally:
2549
 
            pb.finished()
2550
 
 
2551
 
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
2552
 
        packer = CHKReconcilePacker(collection, packs, extension, revs)
2553
 
        return packer.pack(pb)
2554
 
 
2555
 
 
2556
 
class CHKReconcilePacker(ReconcilePacker):
2557
 
    """Subclass of ReconcilePacker for handling chk inventories."""
2558
 
 
2559
 
    def _process_inventory_lines(self, inv_lines):
2560
 
        """Generate a text key reference map rather for reconciling with."""
2561
 
        repo = self._pack_collection.repo
2562
 
        # XXX: This double-reads the inventories; but it works.
2563
 
        refs = repo.find_text_key_references()
2564
 
        self._text_refs = refs
2565
 
        # during reconcile we:
2566
 
        #  - convert unreferenced texts to full texts
2567
 
        #  - correct texts which reference a text not copied to be full texts
2568
 
        #  - copy all others as-is but with corrected parents.
2569
 
        #  - so at this point we don't know enough to decide what becomes a full
2570
 
        #    text.
2571
 
        self._text_filter = None
2572
 
        # Copy the selected inventory roots, extracting the CHK references
2573
 
        # needed.
2574
 
        pending_refs = set()
2575
 
        for line, revid in inv_lines:
2576
 
            if line.startswith('id_to_entry: '):
2577
 
                pending_refs.add((line[13:],))
2578
 
        while pending_refs:
2579
 
            pending_refs = self._copy_chks(pending_refs)
2580
 
 
2581
 
 
2582
1883
class RepositoryFormatPack(MetaDirRepositoryFormat):
2583
1884
    """Format logic for pack structured repositories.
2584
1885
 
2604
1905
    # Set this attribute in derived clases to control the _serializer that the
2605
1906
    # repository objects will have passed to their constructor.
2606
1907
    _serializer = None
2607
 
    # Packs are not confused by ghosts.
2608
 
    supports_ghosts = True
2609
1908
    # External references are not supported in pack repositories yet.
2610
1909
    supports_external_lookups = False
2611
 
    # Most pack formats do not use chk lookups.
2612
 
    supports_chks = False
2613
 
    # What index classes to use
2614
 
    index_builder_class = None
2615
 
    index_class = None
2616
 
    _fetch_uses_deltas = True
2617
 
    fast_deltas = False
2618
1910
 
2619
1911
    def initialize(self, a_bzrdir, shared=False):
2620
1912
        """Create a pack based repository.
2626
1918
        """
2627
1919
        mutter('creating repository in %s.', a_bzrdir.transport.base)
2628
1920
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
2629
 
        builder = self.index_builder_class()
 
1921
        builder = GraphIndexBuilder()
2630
1922
        files = [('pack-names', builder.finish())]
2631
1923
        utf8_files = [('format', self.get_format_string())]
2632
 
 
 
1924
        
2633
1925
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
2634
1926
        return self.open(a_bzrdir=a_bzrdir, _found=True)
2635
1927
 
2636
1928
    def open(self, a_bzrdir, _found=False, _override_transport=None):
2637
1929
        """See RepositoryFormat.open().
2638
 
 
 
1930
        
2639
1931
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
2640
1932
                                    repository at a slightly different url
2641
1933
                                    than normal. I.e. during 'upgrade'.
2663
1955
 
2664
1956
    repository_class = KnitPackRepository
2665
1957
    _commit_builder_class = PackCommitBuilder
2666
 
    @property
2667
 
    def _serializer(self):
2668
 
        return xml5.serializer_v5
2669
 
    # What index classes to use
2670
 
    index_builder_class = InMemoryGraphIndex
2671
 
    index_class = GraphIndex
 
1958
    _serializer = xml5.serializer_v5
2672
1959
 
2673
1960
    def _get_matching_bzrdir(self):
2674
1961
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
2704
1991
    _commit_builder_class = PackRootCommitBuilder
2705
1992
    rich_root_data = True
2706
1993
    supports_tree_reference = True
2707
 
    @property
2708
 
    def _serializer(self):
2709
 
        return xml7.serializer_v7
2710
 
    # What index classes to use
2711
 
    index_builder_class = InMemoryGraphIndex
2712
 
    index_class = GraphIndex
 
1994
    _serializer = xml7.serializer_v7
2713
1995
 
2714
1996
    def _get_matching_bzrdir(self):
2715
1997
        return bzrdir.format_registry.make_bzrdir(
2727
2009
        if not getattr(target_format, 'supports_tree_reference', False):
2728
2010
            raise errors.BadConversionTarget(
2729
2011
                'Does not support nested trees', target_format)
2730
 
 
 
2012
            
2731
2013
    def get_format_string(self):
2732
2014
        """See RepositoryFormat.get_format_string()."""
2733
2015
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2750
2032
    _commit_builder_class = PackRootCommitBuilder
2751
2033
    rich_root_data = True
2752
2034
    supports_tree_reference = False
2753
 
    @property
2754
 
    def _serializer(self):
2755
 
        return xml6.serializer_v6
2756
 
    # What index classes to use
2757
 
    index_builder_class = InMemoryGraphIndex
2758
 
    index_class = GraphIndex
 
2035
    _serializer = xml6.serializer_v6
2759
2036
 
2760
2037
    def _get_matching_bzrdir(self):
2761
2038
        return bzrdir.format_registry.make_bzrdir(
2792
2069
 
2793
2070
    repository_class = KnitPackRepository
2794
2071
    _commit_builder_class = PackCommitBuilder
 
2072
    _serializer = xml5.serializer_v5
2795
2073
    supports_external_lookups = True
2796
 
    # What index classes to use
2797
 
    index_builder_class = InMemoryGraphIndex
2798
 
    index_class = GraphIndex
2799
 
 
2800
 
    @property
2801
 
    def _serializer(self):
2802
 
        return xml5.serializer_v5
2803
2074
 
2804
2075
    def _get_matching_bzrdir(self):
2805
 
        return bzrdir.format_registry.make_bzrdir('1.6')
 
2076
        return bzrdir.format_registry.make_bzrdir('development1')
2806
2077
 
2807
2078
    def _ignore_setting_bzrdir(self, format):
2808
2079
        pass
2834
2105
    _commit_builder_class = PackRootCommitBuilder
2835
2106
    rich_root_data = True
2836
2107
    supports_tree_reference = False # no subtrees
 
2108
    _serializer = xml6.serializer_v6
2837
2109
    supports_external_lookups = True
2838
 
    # What index classes to use
2839
 
    index_builder_class = InMemoryGraphIndex
2840
 
    index_class = GraphIndex
2841
 
 
2842
 
    @property
2843
 
    def _serializer(self):
2844
 
        return xml6.serializer_v6
2845
2110
 
2846
2111
    def _get_matching_bzrdir(self):
2847
2112
        return bzrdir.format_registry.make_bzrdir(
2882
2147
    _commit_builder_class = PackRootCommitBuilder
2883
2148
    rich_root_data = True
2884
2149
    supports_tree_reference = False # no subtrees
 
2150
    _serializer = xml7.serializer_v7
2885
2151
 
2886
2152
    supports_external_lookups = True
2887
 
    # What index classes to use
2888
 
    index_builder_class = InMemoryGraphIndex
2889
 
    index_class = GraphIndex
2890
 
 
2891
 
    @property
2892
 
    def _serializer(self):
2893
 
        return xml7.serializer_v7
2894
2153
 
2895
2154
    def _get_matching_bzrdir(self):
2896
 
        matching = bzrdir.format_registry.make_bzrdir(
2897
 
            '1.6.1-rich-root')
2898
 
        matching.repository_format = self
2899
 
        return matching
 
2155
        return bzrdir.format_registry.make_bzrdir(
 
2156
            'development1-subtree')
2900
2157
 
2901
2158
    def _ignore_setting_bzrdir(self, format):
2902
2159
        pass
2917
2174
                " (deprecated)")
2918
2175
 
2919
2176
 
2920
 
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2921
 
    """A repository with stacking and btree indexes,
2922
 
    without rich roots or subtrees.
2923
 
 
2924
 
    This is equivalent to pack-1.6 with B+Tree indices.
2925
 
    """
2926
 
 
2927
 
    repository_class = KnitPackRepository
2928
 
    _commit_builder_class = PackCommitBuilder
2929
 
    supports_external_lookups = True
2930
 
    # What index classes to use
2931
 
    index_builder_class = BTreeBuilder
2932
 
    index_class = BTreeGraphIndex
2933
 
 
2934
 
    @property
2935
 
    def _serializer(self):
2936
 
        return xml5.serializer_v5
2937
 
 
2938
 
    def _get_matching_bzrdir(self):
2939
 
        return bzrdir.format_registry.make_bzrdir('1.9')
2940
 
 
2941
 
    def _ignore_setting_bzrdir(self, format):
2942
 
        pass
2943
 
 
2944
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2945
 
 
2946
 
    def get_format_string(self):
2947
 
        """See RepositoryFormat.get_format_string()."""
2948
 
        return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2949
 
 
2950
 
    def get_format_description(self):
2951
 
        """See RepositoryFormat.get_format_description()."""
2952
 
        return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2953
 
 
2954
 
    def check_conversion_target(self, target_format):
2955
 
        pass
2956
 
 
2957
 
 
2958
 
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2959
 
    """A repository with rich roots, no subtrees, stacking and btree indexes.
2960
 
 
2961
 
    1.6-rich-root with B+Tree indices.
2962
 
    """
2963
 
 
2964
 
    repository_class = KnitPackRepository
2965
 
    _commit_builder_class = PackRootCommitBuilder
2966
 
    rich_root_data = True
2967
 
    supports_tree_reference = False # no subtrees
2968
 
    supports_external_lookups = True
2969
 
    # What index classes to use
2970
 
    index_builder_class = BTreeBuilder
2971
 
    index_class = BTreeGraphIndex
2972
 
 
2973
 
    @property
2974
 
    def _serializer(self):
2975
 
        return xml6.serializer_v6
2976
 
 
2977
 
    def _get_matching_bzrdir(self):
2978
 
        return bzrdir.format_registry.make_bzrdir(
2979
 
            '1.9-rich-root')
2980
 
 
2981
 
    def _ignore_setting_bzrdir(self, format):
2982
 
        pass
2983
 
 
2984
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2985
 
 
2986
 
    def check_conversion_target(self, target_format):
2987
 
        if not target_format.rich_root_data:
2988
 
            raise errors.BadConversionTarget(
2989
 
                'Does not support rich root data.', target_format)
2990
 
 
2991
 
    def get_format_string(self):
2992
 
        """See RepositoryFormat.get_format_string()."""
2993
 
        return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2994
 
 
2995
 
    def get_format_description(self):
2996
 
        return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2997
 
 
2998
 
 
2999
 
class RepositoryFormatPackDevelopment2(RepositoryFormatPack):
3000
 
    """A no-subtrees development repository.
3001
 
 
3002
 
    This format should be retained until the second release after bzr 1.7.
3003
 
 
3004
 
    This is pack-1.6.1 with B+Tree indices.
3005
 
    """
3006
 
 
3007
 
    repository_class = KnitPackRepository
3008
 
    _commit_builder_class = PackCommitBuilder
3009
 
    supports_external_lookups = True
3010
 
    # What index classes to use
3011
 
    index_builder_class = BTreeBuilder
3012
 
    index_class = BTreeGraphIndex
3013
 
    # Set to true to get the fast-commit code path tested until a really fast
3014
 
    # format lands in trunk. Not actually fast in this format.
3015
 
    fast_deltas = True
3016
 
 
3017
 
    @property
3018
 
    def _serializer(self):
3019
 
        return xml5.serializer_v5
3020
 
 
3021
 
    def _get_matching_bzrdir(self):
3022
 
        return bzrdir.format_registry.make_bzrdir('development2')
3023
 
 
3024
 
    def _ignore_setting_bzrdir(self, format):
3025
 
        pass
3026
 
 
3027
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
3028
 
 
3029
 
    def get_format_string(self):
3030
 
        """See RepositoryFormat.get_format_string()."""
3031
 
        return "Bazaar development format 2 (needs bzr.dev from before 1.8)\n"
3032
 
 
3033
 
    def get_format_description(self):
3034
 
        """See RepositoryFormat.get_format_description()."""
3035
 
        return ("Development repository format, currently the same as "
3036
 
            "1.6.1 with B+Trees.\n")
3037
 
 
3038
 
    def check_conversion_target(self, target_format):
3039
 
        pass
3040
 
 
3041
 
 
3042
 
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
3043
 
    """A subtrees development repository.
3044
 
 
3045
 
    This format should be retained until the second release after bzr 1.7.
3046
 
 
3047
 
    1.6.1-subtree[as it might have been] with B+Tree indices.
3048
 
    """
3049
 
 
3050
 
    repository_class = KnitPackRepository
3051
 
    _commit_builder_class = PackRootCommitBuilder
3052
 
    rich_root_data = True
3053
 
    supports_tree_reference = True
3054
 
    supports_external_lookups = True
3055
 
    # What index classes to use
3056
 
    index_builder_class = BTreeBuilder
3057
 
    index_class = BTreeGraphIndex
3058
 
 
3059
 
    @property
3060
 
    def _serializer(self):
3061
 
        return xml7.serializer_v7
3062
 
 
3063
 
    def _get_matching_bzrdir(self):
3064
 
        return bzrdir.format_registry.make_bzrdir(
3065
 
            'development2-subtree')
3066
 
 
3067
 
    def _ignore_setting_bzrdir(self, format):
3068
 
        pass
3069
 
 
3070
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
3071
 
 
3072
 
    def check_conversion_target(self, target_format):
3073
 
        if not target_format.rich_root_data:
3074
 
            raise errors.BadConversionTarget(
3075
 
                'Does not support rich root data.', target_format)
3076
 
        if not getattr(target_format, 'supports_tree_reference', False):
3077
 
            raise errors.BadConversionTarget(
3078
 
                'Does not support nested trees', target_format)
3079
 
 
3080
 
    def get_format_string(self):
3081
 
        """See RepositoryFormat.get_format_string()."""
3082
 
        return ("Bazaar development format 2 with subtree support "
3083
 
            "(needs bzr.dev from before 1.8)\n")
3084
 
 
3085
 
    def get_format_description(self):
3086
 
        """See RepositoryFormat.get_format_description()."""
3087
 
        return ("Development repository format, currently the same as "
3088
 
            "1.6.1-subtree with B+Tree indices.\n")
3089
 
 
3090
 
 
3091
 
class RepositoryFormatPackDevelopment5(RepositoryFormatPack):
3092
 
    """A no-subtrees development repository.
3093
 
 
3094
 
    This format should be retained until the second release after bzr 1.13.
3095
 
 
3096
 
    This is pack-1.9 with CHKMap based inventories.
3097
 
    """
3098
 
 
3099
 
    repository_class = CHKInventoryRepository
3100
 
    _commit_builder_class = PackCommitBuilder
3101
 
    _serializer = chk_serializer.chk_serializer_parent_id
3102
 
    supports_external_lookups = True
3103
 
    # What index classes to use
3104
 
    index_builder_class = BTreeBuilder
3105
 
    index_class = BTreeGraphIndex
3106
 
    supports_chks = True
3107
 
    _commit_inv_deltas = True
3108
 
 
3109
 
    def _get_matching_bzrdir(self):
3110
 
        return bzrdir.format_registry.make_bzrdir('development5')
3111
 
 
3112
 
    def _ignore_setting_bzrdir(self, format):
3113
 
        pass
3114
 
 
3115
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
3116
 
 
3117
 
    def get_format_string(self):
3118
 
        """See RepositoryFormat.get_format_string()."""
3119
 
        # This will need to be updated (at least replacing 1.13 with the target
3120
 
        # bzr release) once we merge brisbane-core into bzr.dev, I've used
3121
 
        # 'merge-bbc-dev4-to-bzr.dev' into comments at relevant places to make
3122
 
        # them easily greppable.  -- vila 2009016
3123
 
        return "Bazaar development format 5 (needs bzr.dev from before 1.13)\n"
3124
 
 
3125
 
    def get_format_description(self):
3126
 
        """See RepositoryFormat.get_format_description()."""
3127
 
        return ("Development repository format, currently the same as"
3128
 
                " 1.9 with B+Trees and chk support.\n")
3129
 
 
3130
 
    def check_conversion_target(self, target_format):
3131
 
        pass
3132
 
 
3133
 
 
3134
 
class RepositoryFormatPackDevelopment5Subtree(RepositoryFormatPack):
3135
 
    # merge-bbc-dev4-to-bzr.dev
3136
 
    """A subtrees development repository.
3137
 
 
3138
 
    This format should be retained until the second release after bzr 1.13.
3139
 
 
3140
 
    1.9-subtree[as it might have been] with CHKMap based inventories.
3141
 
    """
3142
 
 
3143
 
    repository_class = CHKInventoryRepository
3144
 
    _commit_builder_class = PackRootCommitBuilder
3145
 
    rich_root_data = True
3146
 
    supports_tree_reference = True
3147
 
    _serializer = chk_serializer.chk_serializer_subtree_parent_id
3148
 
    supports_external_lookups = True
3149
 
    # What index classes to use
3150
 
    index_builder_class = BTreeBuilder
3151
 
    index_class = BTreeGraphIndex
3152
 
    supports_chks = True
3153
 
    _commit_inv_deltas = True
3154
 
 
3155
 
    def _get_matching_bzrdir(self):
3156
 
        return bzrdir.format_registry.make_bzrdir(
3157
 
            'development5-subtree')
3158
 
 
3159
 
    def _ignore_setting_bzrdir(self, format):
3160
 
        pass
3161
 
 
3162
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
3163
 
 
3164
 
    def check_conversion_target(self, target_format):
3165
 
        if not target_format.rich_root_data:
3166
 
            raise errors.BadConversionTarget(
3167
 
                'Does not support rich root data.', target_format)
3168
 
        if not getattr(target_format, 'supports_tree_reference', False):
3169
 
            raise errors.BadConversionTarget(
3170
 
                'Does not support nested trees', target_format)
3171
 
 
3172
 
    def get_format_string(self):
3173
 
        """See RepositoryFormat.get_format_string()."""
3174
 
        # merge-bbc-dev4-to-bzr.dev
3175
 
        return ("Bazaar development format 5 with subtree support"
3176
 
                " (needs bzr.dev from before 1.13)\n")
3177
 
 
3178
 
    def get_format_description(self):
3179
 
        """See RepositoryFormat.get_format_description()."""
3180
 
        return ("Development repository format, currently the same as"
3181
 
                " 1.9-subtree with B+Tree and chk support.\n")
3182
 
 
3183
 
 
3184
 
class RepositoryFormatPackDevelopment5Hash16(RepositoryFormatPack):
3185
 
    """A no-subtrees development repository.
3186
 
 
3187
 
    This format should be retained until the second release after bzr 1.13.
3188
 
 
3189
 
    This is pack-1.9 with CHKMap based inventories with 16-way hash tries.
3190
 
    """
3191
 
 
3192
 
    repository_class = CHKInventoryRepository
3193
 
    _commit_builder_class = PackCommitBuilder
3194
 
    _serializer = chk_serializer.chk_serializer_16_parent_id
3195
 
    supports_external_lookups = True
3196
 
    # What index classes to use
3197
 
    index_builder_class = BTreeBuilder
3198
 
    index_class = BTreeGraphIndex
3199
 
    supports_chks = True
3200
 
    _commit_inv_deltas = True
3201
 
 
3202
 
    def _get_matching_bzrdir(self):
3203
 
        return bzrdir.format_registry.make_bzrdir('development5-hash16')
3204
 
 
3205
 
    def _ignore_setting_bzrdir(self, format):
3206
 
        pass
3207
 
 
3208
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
3209
 
 
3210
 
    def get_format_string(self):
3211
 
        """See RepositoryFormat.get_format_string()."""
3212
 
        return ("Bazaar development format 5 hash 16"
3213
 
                " (needs bzr.dev from before 1.13)\n")
3214
 
 
3215
 
    def get_format_description(self):
3216
 
        """See RepositoryFormat.get_format_description()."""
3217
 
        return ("Development repository format, currently the same as"
3218
 
                " 1.9 with B+Trees and chk support and 16-way hash tries\n")
3219
 
 
3220
 
    def check_conversion_target(self, target_format):
3221
 
        pass
3222
 
 
3223
 
 
3224
 
class RepositoryFormatPackDevelopment5Hash255(RepositoryFormatPack):
3225
 
    """A no-subtrees development repository.
3226
 
 
3227
 
    This format should be retained until the second release after bzr 1.13.
3228
 
 
3229
 
    This is pack-1.9 with CHKMap based inventories with 255-way hash tries.
3230
 
    """
3231
 
 
3232
 
    repository_class = CHKInventoryRepository
3233
 
    _commit_builder_class = PackCommitBuilder
3234
 
    _serializer = chk_serializer.chk_serializer_255_parent_id
3235
 
    supports_external_lookups = True
3236
 
    # What index classes to use
3237
 
    index_builder_class = BTreeBuilder
3238
 
    index_class = BTreeGraphIndex
3239
 
    supports_chks = True
3240
 
    _commit_inv_deltas = True
3241
 
 
3242
 
    def _get_matching_bzrdir(self):
3243
 
        return bzrdir.format_registry.make_bzrdir('development5-hash255')
3244
 
 
3245
 
    def _ignore_setting_bzrdir(self, format):
3246
 
        pass
3247
 
 
3248
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
3249
 
 
3250
 
    def get_format_string(self):
3251
 
        """See RepositoryFormat.get_format_string()."""
3252
 
        return ("Bazaar development format 5 hash 255"
3253
 
                " (needs bzr.dev from before 1.13)\n")
3254
 
 
3255
 
    def get_format_description(self):
3256
 
        """See RepositoryFormat.get_format_description()."""
3257
 
        return ("Development repository format, currently the same as"
3258
 
                " 1.9 with B+Trees and chk support and 255-way hash tries\n")
3259
 
 
3260
 
    def check_conversion_target(self, target_format):
3261
 
        pass
 
2177
class RepositoryFormatPackDevelopment1(RepositoryFormatPack):
 
2178
    """A no-subtrees development repository.
 
2179
 
 
2180
    This format should be retained until the second release after bzr 1.5.
 
2181
 
 
2182
    Supports external lookups, which results in non-truncated ghosts after
 
2183
    reconcile compared to pack-0.92 formats.
 
2184
    """
 
2185
 
 
2186
    repository_class = KnitPackRepository
 
2187
    _commit_builder_class = PackCommitBuilder
 
2188
    _serializer = xml5.serializer_v5
 
2189
    supports_external_lookups = True
 
2190
 
 
2191
    def _get_matching_bzrdir(self):
 
2192
        return bzrdir.format_registry.make_bzrdir('development1')
 
2193
 
 
2194
    def _ignore_setting_bzrdir(self, format):
 
2195
        pass
 
2196
 
 
2197
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2198
 
 
2199
    def get_format_string(self):
 
2200
        """See RepositoryFormat.get_format_string()."""
 
2201
        return "Bazaar development format 1 (needs bzr.dev from before 1.6)\n"
 
2202
 
 
2203
    def get_format_description(self):
 
2204
        """See RepositoryFormat.get_format_description()."""
 
2205
        return ("Development repository format, currently the same as "
 
2206
            "pack-0.92 with external reference support.\n")
 
2207
 
 
2208
    def check_conversion_target(self, target_format):
 
2209
        pass
 
2210
 
 
2211
 
 
2212
class RepositoryFormatPackDevelopment1Subtree(RepositoryFormatPack):
 
2213
    """A subtrees development repository.
 
2214
 
 
2215
    This format should be retained until the second release after bzr 1.5.
 
2216
 
 
2217
    Supports external lookups, which results in non-truncated ghosts after
 
2218
    reconcile compared to pack-0.92 formats.
 
2219
    """
 
2220
 
 
2221
    repository_class = KnitPackRepository
 
2222
    _commit_builder_class = PackRootCommitBuilder
 
2223
    rich_root_data = True
 
2224
    supports_tree_reference = True
 
2225
    _serializer = xml7.serializer_v7
 
2226
    supports_external_lookups = True
 
2227
 
 
2228
    def _get_matching_bzrdir(self):
 
2229
        return bzrdir.format_registry.make_bzrdir(
 
2230
            'development1-subtree')
 
2231
 
 
2232
    def _ignore_setting_bzrdir(self, format):
 
2233
        pass
 
2234
 
 
2235
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2236
 
 
2237
    def check_conversion_target(self, target_format):
 
2238
        if not target_format.rich_root_data:
 
2239
            raise errors.BadConversionTarget(
 
2240
                'Does not support rich root data.', target_format)
 
2241
        if not getattr(target_format, 'supports_tree_reference', False):
 
2242
            raise errors.BadConversionTarget(
 
2243
                'Does not support nested trees', target_format)
 
2244
            
 
2245
    def get_format_string(self):
 
2246
        """See RepositoryFormat.get_format_string()."""
 
2247
        return ("Bazaar development format 1 with subtree support "
 
2248
            "(needs bzr.dev from before 1.6)\n")
 
2249
 
 
2250
    def get_format_description(self):
 
2251
        """See RepositoryFormat.get_format_description()."""
 
2252
        return ("Development repository format, currently the same as "
 
2253
            "pack-0.92-subtree with external reference support.\n")