/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-07-18 03:07:07 UTC
  • mfrom: (3535.5.1 lean_imports)
  • Revision ID: pqm@pqm.ubuntu.com-20080718030707-qimx9fv1d4xhlk1m
(jam) Some small import cleanups, to reduce unused dependencies.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from bzrlib.lazy_import import lazy_import
 
18
lazy_import(globals(), """
 
19
from itertools import izip
 
20
import math
 
21
import md5
 
22
import time
 
23
 
 
24
from bzrlib import (
 
25
        debug,
 
26
        graph,
 
27
        pack,
 
28
        ui,
 
29
        )
 
30
from bzrlib.index import (
 
31
    GraphIndex,
 
32
    GraphIndexBuilder,
 
33
    InMemoryGraphIndex,
 
34
    CombinedGraphIndex,
 
35
    GraphIndexPrefixAdapter,
 
36
    )
 
37
from bzrlib.knit import (
 
38
    KnitPlainFactory,
 
39
    KnitVersionedFiles,
 
40
    _KnitGraphIndex,
 
41
    _DirectPackAccess,
 
42
    )
 
43
from bzrlib.osutils import rand_chars, split_lines
 
44
from bzrlib.pack import ContainerWriter
 
45
from bzrlib.store import revision
 
46
from bzrlib import tsort
 
47
""")
 
48
from bzrlib import (
 
49
    bzrdir,
 
50
    errors,
 
51
    lockable_files,
 
52
    lockdir,
 
53
    osutils,
 
54
    symbol_versioning,
 
55
    transactions,
 
56
    xml5,
 
57
    xml6,
 
58
    xml7,
 
59
    )
 
60
 
 
61
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
62
from bzrlib.repofmt.knitrepo import KnitRepository
 
63
from bzrlib.repository import (
 
64
    CommitBuilder,
 
65
    InterRepository,
 
66
    MetaDirRepository,
 
67
    MetaDirRepositoryFormat,
 
68
    RepositoryFormat,
 
69
    RootCommitBuilder,
 
70
    )
 
71
import bzrlib.revision as _mod_revision
 
72
from bzrlib.store.versioned import VersionedFileStore
 
73
from bzrlib.trace import (
 
74
    mutter,
 
75
    mutter_callsite,
 
76
    note,
 
77
    warning,
 
78
    )
 
79
 
 
80
 
 
81
class PackCommitBuilder(CommitBuilder):
 
82
    """A subclass of CommitBuilder to add texts with pack semantics.
 
83
    
 
84
    Specifically this uses one knit object rather than one knit object per
 
85
    added text, reducing memory and object pressure.
 
86
    """
 
87
 
 
88
    def __init__(self, repository, parents, config, timestamp=None,
 
89
                 timezone=None, committer=None, revprops=None,
 
90
                 revision_id=None):
 
91
        CommitBuilder.__init__(self, repository, parents, config,
 
92
            timestamp=timestamp, timezone=timezone, committer=committer,
 
93
            revprops=revprops, revision_id=revision_id)
 
94
        self._file_graph = graph.Graph(
 
95
            repository._pack_collection.text_index.combined_index)
 
96
 
 
97
    def _heads(self, file_id, revision_ids):
 
98
        keys = [(file_id, revision_id) for revision_id in revision_ids]
 
99
        return set([key[1] for key in self._file_graph.heads(keys)])
 
100
 
 
101
 
 
102
class PackRootCommitBuilder(RootCommitBuilder):
 
103
    """A subclass of RootCommitBuilder to add texts with pack semantics.
 
104
    
 
105
    Specifically this uses one knit object rather than one knit object per
 
106
    added text, reducing memory and object pressure.
 
107
    """
 
108
 
 
109
    def __init__(self, repository, parents, config, timestamp=None,
 
110
                 timezone=None, committer=None, revprops=None,
 
111
                 revision_id=None):
 
112
        CommitBuilder.__init__(self, repository, parents, config,
 
113
            timestamp=timestamp, timezone=timezone, committer=committer,
 
114
            revprops=revprops, revision_id=revision_id)
 
115
        self._file_graph = graph.Graph(
 
116
            repository._pack_collection.text_index.combined_index)
 
117
 
 
118
    def _heads(self, file_id, revision_ids):
 
119
        keys = [(file_id, revision_id) for revision_id in revision_ids]
 
120
        return set([key[1] for key in self._file_graph.heads(keys)])
 
121
 
 
122
 
 
123
class Pack(object):
 
124
    """An in memory proxy for a pack and its indices.
 
125
 
 
126
    This is a base class that is not directly used, instead the classes
 
127
    ExistingPack and NewPack are used.
 
128
    """
 
129
 
 
130
    def __init__(self, revision_index, inventory_index, text_index,
 
131
        signature_index):
 
132
        """Create a pack instance.
 
133
 
 
134
        :param revision_index: A GraphIndex for determining what revisions are
 
135
            present in the Pack and accessing the locations of their texts.
 
136
        :param inventory_index: A GraphIndex for determining what inventories are
 
137
            present in the Pack and accessing the locations of their
 
138
            texts/deltas.
 
139
        :param text_index: A GraphIndex for determining what file texts
 
140
            are present in the pack and accessing the locations of their
 
141
            texts/deltas (via (fileid, revisionid) tuples).
 
142
        :param signature_index: A GraphIndex for determining what signatures are
 
143
            present in the Pack and accessing the locations of their texts.
 
144
        """
 
145
        self.revision_index = revision_index
 
146
        self.inventory_index = inventory_index
 
147
        self.text_index = text_index
 
148
        self.signature_index = signature_index
 
149
 
 
150
    def access_tuple(self):
 
151
        """Return a tuple (transport, name) for the pack content."""
 
152
        return self.pack_transport, self.file_name()
 
153
 
 
154
    def file_name(self):
 
155
        """Get the file name for the pack on disk."""
 
156
        return self.name + '.pack'
 
157
 
 
158
    def get_revision_count(self):
 
159
        return self.revision_index.key_count()
 
160
 
 
161
    def inventory_index_name(self, name):
 
162
        """The inv index is the name + .iix."""
 
163
        return self.index_name('inventory', name)
 
164
 
 
165
    def revision_index_name(self, name):
 
166
        """The revision index is the name + .rix."""
 
167
        return self.index_name('revision', name)
 
168
 
 
169
    def signature_index_name(self, name):
 
170
        """The signature index is the name + .six."""
 
171
        return self.index_name('signature', name)
 
172
 
 
173
    def text_index_name(self, name):
 
174
        """The text index is the name + .tix."""
 
175
        return self.index_name('text', name)
 
176
 
 
177
    def _external_compression_parents_of_texts(self):
 
178
        keys = set()
 
179
        refs = set()
 
180
        for node in self.text_index.iter_all_entries():
 
181
            keys.add(node[1])
 
182
            refs.update(node[3][1])
 
183
        return refs - keys
 
184
 
 
185
 
 
186
class ExistingPack(Pack):
 
187
    """An in memory proxy for an existing .pack and its disk indices."""
 
188
 
 
189
    def __init__(self, pack_transport, name, revision_index, inventory_index,
 
190
        text_index, signature_index):
 
191
        """Create an ExistingPack object.
 
192
 
 
193
        :param pack_transport: The transport where the pack file resides.
 
194
        :param name: The name of the pack on disk in the pack_transport.
 
195
        """
 
196
        Pack.__init__(self, revision_index, inventory_index, text_index,
 
197
            signature_index)
 
198
        self.name = name
 
199
        self.pack_transport = pack_transport
 
200
        if None in (revision_index, inventory_index, text_index,
 
201
                signature_index, name, pack_transport):
 
202
            raise AssertionError()
 
203
 
 
204
    def __eq__(self, other):
 
205
        return self.__dict__ == other.__dict__
 
206
 
 
207
    def __ne__(self, other):
 
208
        return not self.__eq__(other)
 
209
 
 
210
    def __repr__(self):
 
211
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
 
212
            id(self), self.pack_transport, self.name)
 
213
 
 
214
 
 
215
class NewPack(Pack):
 
216
    """An in memory proxy for a pack which is being created."""
 
217
 
 
218
    # A map of index 'type' to the file extension and position in the
 
219
    # index_sizes array.
 
220
    index_definitions = {
 
221
        'revision': ('.rix', 0),
 
222
        'inventory': ('.iix', 1),
 
223
        'text': ('.tix', 2),
 
224
        'signature': ('.six', 3),
 
225
        }
 
226
 
 
227
    def __init__(self, upload_transport, index_transport, pack_transport,
 
228
        upload_suffix='', file_mode=None):
 
229
        """Create a NewPack instance.
 
230
 
 
231
        :param upload_transport: A writable transport for the pack to be
 
232
            incrementally uploaded to.
 
233
        :param index_transport: A writable transport for the pack's indices to
 
234
            be written to when the pack is finished.
 
235
        :param pack_transport: A writable transport for the pack to be renamed
 
236
            to when the upload is complete. This *must* be the same as
 
237
            upload_transport.clone('../packs').
 
238
        :param upload_suffix: An optional suffix to be given to any temporary
 
239
            files created during the pack creation. e.g '.autopack'
 
240
        :param file_mode: An optional file mode to create the new files with.
 
241
        """
 
242
        # The relative locations of the packs are constrained, but all are
 
243
        # passed in because the caller has them, so as to avoid object churn.
 
244
        Pack.__init__(self,
 
245
            # Revisions: parents list, no text compression.
 
246
            InMemoryGraphIndex(reference_lists=1),
 
247
            # Inventory: We want to map compression only, but currently the
 
248
            # knit code hasn't been updated enough to understand that, so we
 
249
            # have a regular 2-list index giving parents and compression
 
250
            # source.
 
251
            InMemoryGraphIndex(reference_lists=2),
 
252
            # Texts: compression and per file graph, for all fileids - so two
 
253
            # reference lists and two elements in the key tuple.
 
254
            InMemoryGraphIndex(reference_lists=2, key_elements=2),
 
255
            # Signatures: Just blobs to store, no compression, no parents
 
256
            # listing.
 
257
            InMemoryGraphIndex(reference_lists=0),
 
258
            )
 
259
        # where should the new pack be opened
 
260
        self.upload_transport = upload_transport
 
261
        # where are indices written out to
 
262
        self.index_transport = index_transport
 
263
        # where is the pack renamed to when it is finished?
 
264
        self.pack_transport = pack_transport
 
265
        # What file mode to upload the pack and indices with.
 
266
        self._file_mode = file_mode
 
267
        # tracks the content written to the .pack file.
 
268
        self._hash = md5.new()
 
269
        # a four-tuple with the length in bytes of the indices, once the pack
 
270
        # is finalised. (rev, inv, text, sigs)
 
271
        self.index_sizes = None
 
272
        # How much data to cache when writing packs. Note that this is not
 
273
        # synchronised with reads, because it's not in the transport layer, so
 
274
        # is not safe unless the client knows it won't be reading from the pack
 
275
        # under creation.
 
276
        self._cache_limit = 0
 
277
        # the temporary pack file name.
 
278
        self.random_name = rand_chars(20) + upload_suffix
 
279
        # when was this pack started ?
 
280
        self.start_time = time.time()
 
281
        # open an output stream for the data added to the pack.
 
282
        self.write_stream = self.upload_transport.open_write_stream(
 
283
            self.random_name, mode=self._file_mode)
 
284
        if 'pack' in debug.debug_flags:
 
285
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
 
286
                time.ctime(), self.upload_transport.base, self.random_name,
 
287
                time.time() - self.start_time)
 
288
        # A list of byte sequences to be written to the new pack, and the 
 
289
        # aggregate size of them.  Stored as a list rather than separate 
 
290
        # variables so that the _write_data closure below can update them.
 
291
        self._buffer = [[], 0]
 
292
        # create a callable for adding data 
 
293
        #
 
294
        # robertc says- this is a closure rather than a method on the object
 
295
        # so that the variables are locals, and faster than accessing object
 
296
        # members.
 
297
        def _write_data(bytes, flush=False, _buffer=self._buffer,
 
298
            _write=self.write_stream.write, _update=self._hash.update):
 
299
            _buffer[0].append(bytes)
 
300
            _buffer[1] += len(bytes)
 
301
            # buffer cap
 
302
            if _buffer[1] > self._cache_limit or flush:
 
303
                bytes = ''.join(_buffer[0])
 
304
                _write(bytes)
 
305
                _update(bytes)
 
306
                _buffer[:] = [[], 0]
 
307
        # expose this on self, for the occasion when clients want to add data.
 
308
        self._write_data = _write_data
 
309
        # a pack writer object to serialise pack records.
 
310
        self._writer = pack.ContainerWriter(self._write_data)
 
311
        self._writer.begin()
 
312
        # what state is the pack in? (open, finished, aborted)
 
313
        self._state = 'open'
 
314
 
 
315
    def abort(self):
 
316
        """Cancel creating this pack."""
 
317
        self._state = 'aborted'
 
318
        self.write_stream.close()
 
319
        # Remove the temporary pack file.
 
320
        self.upload_transport.delete(self.random_name)
 
321
        # The indices have no state on disk.
 
322
 
 
323
    def access_tuple(self):
 
324
        """Return a tuple (transport, name) for the pack content."""
 
325
        if self._state == 'finished':
 
326
            return Pack.access_tuple(self)
 
327
        elif self._state == 'open':
 
328
            return self.upload_transport, self.random_name
 
329
        else:
 
330
            raise AssertionError(self._state)
 
331
 
 
332
    def data_inserted(self):
 
333
        """True if data has been added to this pack."""
 
334
        return bool(self.get_revision_count() or
 
335
            self.inventory_index.key_count() or
 
336
            self.text_index.key_count() or
 
337
            self.signature_index.key_count())
 
338
 
 
339
    def finish(self):
 
340
        """Finish the new pack.
 
341
 
 
342
        This:
 
343
         - finalises the content
 
344
         - assigns a name (the md5 of the content, currently)
 
345
         - writes out the associated indices
 
346
         - renames the pack into place.
 
347
         - stores the index size tuple for the pack in the index_sizes
 
348
           attribute.
 
349
        """
 
350
        self._writer.end()
 
351
        if self._buffer[1]:
 
352
            self._write_data('', flush=True)
 
353
        self.name = self._hash.hexdigest()
 
354
        # write indices
 
355
        # XXX: It'd be better to write them all to temporary names, then
 
356
        # rename them all into place, so that the window when only some are
 
357
        # visible is smaller.  On the other hand none will be seen until
 
358
        # they're in the names list.
 
359
        self.index_sizes = [None, None, None, None]
 
360
        self._write_index('revision', self.revision_index, 'revision')
 
361
        self._write_index('inventory', self.inventory_index, 'inventory')
 
362
        self._write_index('text', self.text_index, 'file texts')
 
363
        self._write_index('signature', self.signature_index,
 
364
            'revision signatures')
 
365
        self.write_stream.close()
 
366
        # Note that this will clobber an existing pack with the same name,
 
367
        # without checking for hash collisions. While this is undesirable this
 
368
        # is something that can be rectified in a subsequent release. One way
 
369
        # to rectify it may be to leave the pack at the original name, writing
 
370
        # its pack-names entry as something like 'HASH: index-sizes
 
371
        # temporary-name'. Allocate that and check for collisions, if it is
 
372
        # collision free then rename it into place. If clients know this scheme
 
373
        # they can handle missing-file errors by:
 
374
        #  - try for HASH.pack
 
375
        #  - try for temporary-name
 
376
        #  - refresh the pack-list to see if the pack is now absent
 
377
        self.upload_transport.rename(self.random_name,
 
378
                '../packs/' + self.name + '.pack')
 
379
        self._state = 'finished'
 
380
        if 'pack' in debug.debug_flags:
 
381
            # XXX: size might be interesting?
 
382
            mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
 
383
                time.ctime(), self.upload_transport.base, self.random_name,
 
384
                self.pack_transport, self.name,
 
385
                time.time() - self.start_time)
 
386
 
 
387
    def flush(self):
 
388
        """Flush any current data."""
 
389
        if self._buffer[1]:
 
390
            bytes = ''.join(self._buffer[0])
 
391
            self.write_stream.write(bytes)
 
392
            self._hash.update(bytes)
 
393
            self._buffer[:] = [[], 0]
 
394
 
 
395
    def index_name(self, index_type, name):
 
396
        """Get the disk name of an index type for pack name 'name'."""
 
397
        return name + NewPack.index_definitions[index_type][0]
 
398
 
 
399
    def index_offset(self, index_type):
 
400
        """Get the position in a index_size array for a given index type."""
 
401
        return NewPack.index_definitions[index_type][1]
 
402
 
 
403
    def _replace_index_with_readonly(self, index_type):
 
404
        setattr(self, index_type + '_index',
 
405
            GraphIndex(self.index_transport,
 
406
                self.index_name(index_type, self.name),
 
407
                self.index_sizes[self.index_offset(index_type)]))
 
408
 
 
409
    def set_write_cache_size(self, size):
 
410
        self._cache_limit = size
 
411
 
 
412
    def _write_index(self, index_type, index, label):
 
413
        """Write out an index.
 
414
 
 
415
        :param index_type: The type of index to write - e.g. 'revision'.
 
416
        :param index: The index object to serialise.
 
417
        :param label: What label to give the index e.g. 'revision'.
 
418
        """
 
419
        index_name = self.index_name(index_type, self.name)
 
420
        self.index_sizes[self.index_offset(index_type)] = \
 
421
            self.index_transport.put_file(index_name, index.finish(),
 
422
            mode=self._file_mode)
 
423
        if 'pack' in debug.debug_flags:
 
424
            # XXX: size might be interesting?
 
425
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
 
426
                time.ctime(), label, self.upload_transport.base,
 
427
                self.random_name, time.time() - self.start_time)
 
428
        # Replace the writable index on this object with a readonly, 
 
429
        # presently unloaded index. We should alter
 
430
        # the index layer to make its finish() error if add_node is
 
431
        # subsequently used. RBC
 
432
        self._replace_index_with_readonly(index_type)
 
433
 
 
434
 
 
435
class AggregateIndex(object):
 
436
    """An aggregated index for the RepositoryPackCollection.
 
437
 
 
438
    AggregateIndex is reponsible for managing the PackAccess object,
 
439
    Index-To-Pack mapping, and all indices list for a specific type of index
 
440
    such as 'revision index'.
 
441
 
 
442
    A CombinedIndex provides an index on a single key space built up
 
443
    from several on-disk indices.  The AggregateIndex builds on this 
 
444
    to provide a knit access layer, and allows having up to one writable
 
445
    index within the collection.
 
446
    """
 
447
    # XXX: Probably 'can be written to' could/should be separated from 'acts
 
448
    # like a knit index' -- mbp 20071024
 
449
 
 
450
    def __init__(self):
 
451
        """Create an AggregateIndex."""
 
452
        self.index_to_pack = {}
 
453
        self.combined_index = CombinedGraphIndex([])
 
454
        self.data_access = _DirectPackAccess(self.index_to_pack)
 
455
        self.add_callback = None
 
456
 
 
457
    def replace_indices(self, index_to_pack, indices):
 
458
        """Replace the current mappings with fresh ones.
 
459
 
 
460
        This should probably not be used eventually, rather incremental add and
 
461
        removal of indices. It has been added during refactoring of existing
 
462
        code.
 
463
 
 
464
        :param index_to_pack: A mapping from index objects to
 
465
            (transport, name) tuples for the pack file data.
 
466
        :param indices: A list of indices.
 
467
        """
 
468
        # refresh the revision pack map dict without replacing the instance.
 
469
        self.index_to_pack.clear()
 
470
        self.index_to_pack.update(index_to_pack)
 
471
        # XXX: API break - clearly a 'replace' method would be good?
 
472
        self.combined_index._indices[:] = indices
 
473
        # the current add nodes callback for the current writable index if
 
474
        # there is one.
 
475
        self.add_callback = None
 
476
 
 
477
    def add_index(self, index, pack):
 
478
        """Add index to the aggregate, which is an index for Pack pack.
 
479
 
 
480
        Future searches on the aggregate index will seach this new index
 
481
        before all previously inserted indices.
 
482
        
 
483
        :param index: An Index for the pack.
 
484
        :param pack: A Pack instance.
 
485
        """
 
486
        # expose it to the index map
 
487
        self.index_to_pack[index] = pack.access_tuple()
 
488
        # put it at the front of the linear index list
 
489
        self.combined_index.insert_index(0, index)
 
490
 
 
491
    def add_writable_index(self, index, pack):
 
492
        """Add an index which is able to have data added to it.
 
493
 
 
494
        There can be at most one writable index at any time.  Any
 
495
        modifications made to the knit are put into this index.
 
496
        
 
497
        :param index: An index from the pack parameter.
 
498
        :param pack: A Pack instance.
 
499
        """
 
500
        if self.add_callback is not None:
 
501
            raise AssertionError(
 
502
                "%s already has a writable index through %s" % \
 
503
                (self, self.add_callback))
 
504
        # allow writing: queue writes to a new index
 
505
        self.add_index(index, pack)
 
506
        # Updates the index to packs mapping as a side effect,
 
507
        self.data_access.set_writer(pack._writer, index, pack.access_tuple())
 
508
        self.add_callback = index.add_nodes
 
509
 
 
510
    def clear(self):
 
511
        """Reset all the aggregate data to nothing."""
 
512
        self.data_access.set_writer(None, None, (None, None))
 
513
        self.index_to_pack.clear()
 
514
        del self.combined_index._indices[:]
 
515
        self.add_callback = None
 
516
 
 
517
    def remove_index(self, index, pack):
 
518
        """Remove index from the indices used to answer queries.
 
519
        
 
520
        :param index: An index from the pack parameter.
 
521
        :param pack: A Pack instance.
 
522
        """
 
523
        del self.index_to_pack[index]
 
524
        self.combined_index._indices.remove(index)
 
525
        if (self.add_callback is not None and
 
526
            getattr(index, 'add_nodes', None) == self.add_callback):
 
527
            self.add_callback = None
 
528
            self.data_access.set_writer(None, None, (None, None))
 
529
 
 
530
 
 
531
class Packer(object):
 
532
    """Create a pack from packs."""
 
533
 
 
534
    def __init__(self, pack_collection, packs, suffix, revision_ids=None):
 
535
        """Create a Packer.
 
536
 
 
537
        :param pack_collection: A RepositoryPackCollection object where the
 
538
            new pack is being written to.
 
539
        :param packs: The packs to combine.
 
540
        :param suffix: The suffix to use on the temporary files for the pack.
 
541
        :param revision_ids: Revision ids to limit the pack to.
 
542
        """
 
543
        self.packs = packs
 
544
        self.suffix = suffix
 
545
        self.revision_ids = revision_ids
 
546
        # The pack object we are creating.
 
547
        self.new_pack = None
 
548
        self._pack_collection = pack_collection
 
549
        # The index layer keys for the revisions being copied. None for 'all
 
550
        # objects'.
 
551
        self._revision_keys = None
 
552
        # What text keys to copy. None for 'all texts'. This is set by
 
553
        # _copy_inventory_texts
 
554
        self._text_filter = None
 
555
        self._extra_init()
 
556
 
 
557
    def _extra_init(self):
 
558
        """A template hook to allow extending the constructor trivially."""
 
559
 
 
560
    def pack(self, pb=None):
 
561
        """Create a new pack by reading data from other packs.
 
562
 
 
563
        This does little more than a bulk copy of data. One key difference
 
564
        is that data with the same item key across multiple packs is elided
 
565
        from the output. The new pack is written into the current pack store
 
566
        along with its indices, and the name added to the pack names. The 
 
567
        source packs are not altered and are not required to be in the current
 
568
        pack collection.
 
569
 
 
570
        :param pb: An optional progress bar to use. A nested bar is created if
 
571
            this is None.
 
572
        :return: A Pack object, or None if nothing was copied.
 
573
        """
 
574
        # open a pack - using the same name as the last temporary file
 
575
        # - which has already been flushed, so its safe.
 
576
        # XXX: - duplicate code warning with start_write_group; fix before
 
577
        #      considering 'done'.
 
578
        if self._pack_collection._new_pack is not None:
 
579
            raise errors.BzrError('call to create_pack_from_packs while '
 
580
                'another pack is being written.')
 
581
        if self.revision_ids is not None:
 
582
            if len(self.revision_ids) == 0:
 
583
                # silly fetch request.
 
584
                return None
 
585
            else:
 
586
                self.revision_ids = frozenset(self.revision_ids)
 
587
                self.revision_keys = frozenset((revid,) for revid in
 
588
                    self.revision_ids)
 
589
        if pb is None:
 
590
            self.pb = ui.ui_factory.nested_progress_bar()
 
591
        else:
 
592
            self.pb = pb
 
593
        try:
 
594
            return self._create_pack_from_packs()
 
595
        finally:
 
596
            if pb is None:
 
597
                self.pb.finished()
 
598
 
 
599
    def open_pack(self):
 
600
        """Open a pack for the pack we are creating."""
 
601
        return NewPack(self._pack_collection._upload_transport,
 
602
            self._pack_collection._index_transport,
 
603
            self._pack_collection._pack_transport, upload_suffix=self.suffix,
 
604
            file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
 
605
 
 
606
    def _copy_revision_texts(self):
 
607
        """Copy revision data to the new pack."""
 
608
        # select revisions
 
609
        if self.revision_ids:
 
610
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
 
611
        else:
 
612
            revision_keys = None
 
613
        # select revision keys
 
614
        revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
615
            self.packs, 'revision_index')[0]
 
616
        revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
 
617
        # copy revision keys and adjust values
 
618
        self.pb.update("Copying revision texts", 1)
 
619
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
 
620
        list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
 
621
            self.new_pack.revision_index, readv_group_iter, total_items))
 
622
        if 'pack' in debug.debug_flags:
 
623
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
 
624
                time.ctime(), self._pack_collection._upload_transport.base,
 
625
                self.new_pack.random_name,
 
626
                self.new_pack.revision_index.key_count(),
 
627
                time.time() - self.new_pack.start_time)
 
628
        self._revision_keys = revision_keys
 
629
 
 
630
    def _copy_inventory_texts(self):
 
631
        """Copy the inventory texts to the new pack.
 
632
 
 
633
        self._revision_keys is used to determine what inventories to copy.
 
634
 
 
635
        Sets self._text_filter appropriately.
 
636
        """
 
637
        # select inventory keys
 
638
        inv_keys = self._revision_keys # currently the same keyspace, and note that
 
639
        # querying for keys here could introduce a bug where an inventory item
 
640
        # is missed, so do not change it to query separately without cross
 
641
        # checking like the text key check below.
 
642
        inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
643
            self.packs, 'inventory_index')[0]
 
644
        inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
 
645
        # copy inventory keys and adjust values
 
646
        # XXX: Should be a helper function to allow different inv representation
 
647
        # at this point.
 
648
        self.pb.update("Copying inventory texts", 2)
 
649
        total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
 
650
        # Only grab the output lines if we will be processing them
 
651
        output_lines = bool(self.revision_ids)
 
652
        inv_lines = self._copy_nodes_graph(inventory_index_map,
 
653
            self.new_pack._writer, self.new_pack.inventory_index,
 
654
            readv_group_iter, total_items, output_lines=output_lines)
 
655
        if self.revision_ids:
 
656
            self._process_inventory_lines(inv_lines)
 
657
        else:
 
658
            # eat the iterator to cause it to execute.
 
659
            list(inv_lines)
 
660
            self._text_filter = None
 
661
        if 'pack' in debug.debug_flags:
 
662
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
 
663
                time.ctime(), self._pack_collection._upload_transport.base,
 
664
                self.new_pack.random_name,
 
665
                self.new_pack.inventory_index.key_count(),
 
666
                time.time() - self.new_pack.start_time)
 
667
 
 
668
    def _copy_text_texts(self):
 
669
        # select text keys
 
670
        text_index_map, text_nodes = self._get_text_nodes()
 
671
        if self._text_filter is not None:
 
672
            # We could return the keys copied as part of the return value from
 
673
            # _copy_nodes_graph but this doesn't work all that well with the
 
674
            # need to get line output too, so we check separately, and as we're
 
675
            # going to buffer everything anyway, we check beforehand, which
 
676
            # saves reading knit data over the wire when we know there are
 
677
            # mising records.
 
678
            text_nodes = set(text_nodes)
 
679
            present_text_keys = set(_node[1] for _node in text_nodes)
 
680
            missing_text_keys = set(self._text_filter) - present_text_keys
 
681
            if missing_text_keys:
 
682
                # TODO: raise a specific error that can handle many missing
 
683
                # keys.
 
684
                a_missing_key = missing_text_keys.pop()
 
685
                raise errors.RevisionNotPresent(a_missing_key[1],
 
686
                    a_missing_key[0])
 
687
        # copy text keys and adjust values
 
688
        self.pb.update("Copying content texts", 3)
 
689
        total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
 
690
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
 
691
            self.new_pack.text_index, readv_group_iter, total_items))
 
692
        self._log_copied_texts()
 
693
 
 
694
    def _check_references(self):
 
695
        """Make sure our external refereneces are present."""
 
696
        external_refs = self.new_pack._external_compression_parents_of_texts()
 
697
        if external_refs:
 
698
            index = self._pack_collection.text_index.combined_index
 
699
            found_items = list(index.iter_entries(external_refs))
 
700
            if len(found_items) != len(external_refs):
 
701
                found_keys = set(k for idx, k, refs, value in found_items)
 
702
                missing_items = external_refs - found_keys
 
703
                missing_file_id, missing_revision_id = missing_items.pop()
 
704
                raise errors.RevisionNotPresent(missing_revision_id,
 
705
                                                missing_file_id)
 
706
 
 
707
    def _create_pack_from_packs(self):
 
708
        self.pb.update("Opening pack", 0, 5)
 
709
        self.new_pack = self.open_pack()
 
710
        new_pack = self.new_pack
 
711
        # buffer data - we won't be reading-back during the pack creation and
 
712
        # this makes a significant difference on sftp pushes.
 
713
        new_pack.set_write_cache_size(1024*1024)
 
714
        if 'pack' in debug.debug_flags:
 
715
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
 
716
                for a_pack in self.packs]
 
717
            if self.revision_ids is not None:
 
718
                rev_count = len(self.revision_ids)
 
719
            else:
 
720
                rev_count = 'all'
 
721
            mutter('%s: create_pack: creating pack from source packs: '
 
722
                '%s%s %s revisions wanted %s t=0',
 
723
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
724
                plain_pack_list, rev_count)
 
725
        self._copy_revision_texts()
 
726
        self._copy_inventory_texts()
 
727
        self._copy_text_texts()
 
728
        # select signature keys
 
729
        signature_filter = self._revision_keys # same keyspace
 
730
        signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
731
            self.packs, 'signature_index')[0]
 
732
        signature_nodes = self._pack_collection._index_contents(signature_index_map,
 
733
            signature_filter)
 
734
        # copy signature keys and adjust values
 
735
        self.pb.update("Copying signature texts", 4)
 
736
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
 
737
            new_pack.signature_index)
 
738
        if 'pack' in debug.debug_flags:
 
739
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
 
740
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
741
                new_pack.signature_index.key_count(),
 
742
                time.time() - new_pack.start_time)
 
743
        self._check_references()
 
744
        if not self._use_pack(new_pack):
 
745
            new_pack.abort()
 
746
            return None
 
747
        self.pb.update("Finishing pack", 5)
 
748
        new_pack.finish()
 
749
        self._pack_collection.allocate(new_pack)
 
750
        return new_pack
 
751
 
 
752
    def _copy_nodes(self, nodes, index_map, writer, write_index):
 
753
        """Copy knit nodes between packs with no graph references."""
 
754
        pb = ui.ui_factory.nested_progress_bar()
 
755
        try:
 
756
            return self._do_copy_nodes(nodes, index_map, writer,
 
757
                write_index, pb)
 
758
        finally:
 
759
            pb.finished()
 
760
 
 
761
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
 
762
        # for record verification
 
763
        knit = KnitVersionedFiles(None, None)
 
764
        # plan a readv on each source pack:
 
765
        # group by pack
 
766
        nodes = sorted(nodes)
 
767
        # how to map this into knit.py - or knit.py into this?
 
768
        # we don't want the typical knit logic, we want grouping by pack
 
769
        # at this point - perhaps a helper library for the following code 
 
770
        # duplication points?
 
771
        request_groups = {}
 
772
        for index, key, value in nodes:
 
773
            if index not in request_groups:
 
774
                request_groups[index] = []
 
775
            request_groups[index].append((key, value))
 
776
        record_index = 0
 
777
        pb.update("Copied record", record_index, len(nodes))
 
778
        for index, items in request_groups.iteritems():
 
779
            pack_readv_requests = []
 
780
            for key, value in items:
 
781
                # ---- KnitGraphIndex.get_position
 
782
                bits = value[1:].split(' ')
 
783
                offset, length = int(bits[0]), int(bits[1])
 
784
                pack_readv_requests.append((offset, length, (key, value[0])))
 
785
            # linear scan up the pack
 
786
            pack_readv_requests.sort()
 
787
            # copy the data
 
788
            transport, path = index_map[index]
 
789
            reader = pack.make_readv_reader(transport, path,
 
790
                [offset[0:2] for offset in pack_readv_requests])
 
791
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
 
792
                izip(reader.iter_records(), pack_readv_requests):
 
793
                raw_data = read_func(None)
 
794
                # check the header only
 
795
                df, _ = knit._parse_record_header(key, raw_data)
 
796
                df.close()
 
797
                pos, size = writer.add_bytes_record(raw_data, names)
 
798
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
 
799
                pb.update("Copied record", record_index)
 
800
                record_index += 1
 
801
 
 
802
    def _copy_nodes_graph(self, index_map, writer, write_index,
 
803
        readv_group_iter, total_items, output_lines=False):
 
804
        """Copy knit nodes between packs.
 
805
 
 
806
        :param output_lines: Return lines present in the copied data as
 
807
            an iterator of line,version_id.
 
808
        """
 
809
        pb = ui.ui_factory.nested_progress_bar()
 
810
        try:
 
811
            for result in self._do_copy_nodes_graph(index_map, writer,
 
812
                write_index, output_lines, pb, readv_group_iter, total_items):
 
813
                yield result
 
814
        except Exception:
 
815
            # Python 2.4 does not permit try:finally: in a generator.
 
816
            pb.finished()
 
817
            raise
 
818
        else:
 
819
            pb.finished()
 
820
 
 
821
    def _do_copy_nodes_graph(self, index_map, writer, write_index,
 
822
        output_lines, pb, readv_group_iter, total_items):
 
823
        # for record verification
 
824
        knit = KnitVersionedFiles(None, None)
 
825
        # for line extraction when requested (inventories only)
 
826
        if output_lines:
 
827
            factory = KnitPlainFactory()
 
828
        record_index = 0
 
829
        pb.update("Copied record", record_index, total_items)
 
830
        for index, readv_vector, node_vector in readv_group_iter:
 
831
            # copy the data
 
832
            transport, path = index_map[index]
 
833
            reader = pack.make_readv_reader(transport, path, readv_vector)
 
834
            for (names, read_func), (key, eol_flag, references) in \
 
835
                izip(reader.iter_records(), node_vector):
 
836
                raw_data = read_func(None)
 
837
                if output_lines:
 
838
                    # read the entire thing
 
839
                    content, _ = knit._parse_record(key[-1], raw_data)
 
840
                    if len(references[-1]) == 0:
 
841
                        line_iterator = factory.get_fulltext_content(content)
 
842
                    else:
 
843
                        line_iterator = factory.get_linedelta_content(content)
 
844
                    for line in line_iterator:
 
845
                        yield line, key
 
846
                else:
 
847
                    # check the header only
 
848
                    df, _ = knit._parse_record_header(key, raw_data)
 
849
                    df.close()
 
850
                pos, size = writer.add_bytes_record(raw_data, names)
 
851
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
 
852
                pb.update("Copied record", record_index)
 
853
                record_index += 1
 
854
 
 
855
    def _get_text_nodes(self):
 
856
        text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
857
            self.packs, 'text_index')[0]
 
858
        return text_index_map, self._pack_collection._index_contents(text_index_map,
 
859
            self._text_filter)
 
860
 
 
861
    def _least_readv_node_readv(self, nodes):
 
862
        """Generate request groups for nodes using the least readv's.
 
863
        
 
864
        :param nodes: An iterable of graph index nodes.
 
865
        :return: Total node count and an iterator of the data needed to perform
 
866
            readvs to obtain the data for nodes. Each item yielded by the
 
867
            iterator is a tuple with:
 
868
            index, readv_vector, node_vector. readv_vector is a list ready to
 
869
            hand to the transport readv method, and node_vector is a list of
 
870
            (key, eol_flag, references) for the the node retrieved by the
 
871
            matching readv_vector.
 
872
        """
 
873
        # group by pack so we do one readv per pack
 
874
        nodes = sorted(nodes)
 
875
        total = len(nodes)
 
876
        request_groups = {}
 
877
        for index, key, value, references in nodes:
 
878
            if index not in request_groups:
 
879
                request_groups[index] = []
 
880
            request_groups[index].append((key, value, references))
 
881
        result = []
 
882
        for index, items in request_groups.iteritems():
 
883
            pack_readv_requests = []
 
884
            for key, value, references in items:
 
885
                # ---- KnitGraphIndex.get_position
 
886
                bits = value[1:].split(' ')
 
887
                offset, length = int(bits[0]), int(bits[1])
 
888
                pack_readv_requests.append(
 
889
                    ((offset, length), (key, value[0], references)))
 
890
            # linear scan up the pack to maximum range combining.
 
891
            pack_readv_requests.sort()
 
892
            # split out the readv and the node data.
 
893
            pack_readv = [readv for readv, node in pack_readv_requests]
 
894
            node_vector = [node for readv, node in pack_readv_requests]
 
895
            result.append((index, pack_readv, node_vector))
 
896
        return total, result
 
897
 
 
898
    def _log_copied_texts(self):
 
899
        if 'pack' in debug.debug_flags:
 
900
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
 
901
                time.ctime(), self._pack_collection._upload_transport.base,
 
902
                self.new_pack.random_name,
 
903
                self.new_pack.text_index.key_count(),
 
904
                time.time() - self.new_pack.start_time)
 
905
 
 
906
    def _process_inventory_lines(self, inv_lines):
 
907
        """Use up the inv_lines generator and setup a text key filter."""
 
908
        repo = self._pack_collection.repo
 
909
        fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
 
910
            inv_lines, self.revision_keys)
 
911
        text_filter = []
 
912
        for fileid, file_revids in fileid_revisions.iteritems():
 
913
            text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
 
914
        self._text_filter = text_filter
 
915
 
 
916
    def _revision_node_readv(self, revision_nodes):
 
917
        """Return the total revisions and the readv's to issue.
 
918
 
 
919
        :param revision_nodes: The revision index contents for the packs being
 
920
            incorporated into the new pack.
 
921
        :return: As per _least_readv_node_readv.
 
922
        """
 
923
        return self._least_readv_node_readv(revision_nodes)
 
924
 
 
925
    def _use_pack(self, new_pack):
 
926
        """Return True if new_pack should be used.
 
927
 
 
928
        :param new_pack: The pack that has just been created.
 
929
        :return: True if the pack should be used.
 
930
        """
 
931
        return new_pack.data_inserted()
 
932
 
 
933
 
 
934
class OptimisingPacker(Packer):
 
935
    """A packer which spends more time to create better disk layouts."""
 
936
 
 
937
    def _revision_node_readv(self, revision_nodes):
 
938
        """Return the total revisions and the readv's to issue.
 
939
 
 
940
        This sort places revisions in topological order with the ancestors
 
941
        after the children.
 
942
 
 
943
        :param revision_nodes: The revision index contents for the packs being
 
944
            incorporated into the new pack.
 
945
        :return: As per _least_readv_node_readv.
 
946
        """
 
947
        # build an ancestors dict
 
948
        ancestors = {}
 
949
        by_key = {}
 
950
        for index, key, value, references in revision_nodes:
 
951
            ancestors[key] = references[0]
 
952
            by_key[key] = (index, value, references)
 
953
        order = tsort.topo_sort(ancestors)
 
954
        total = len(order)
 
955
        # Single IO is pathological, but it will work as a starting point.
 
956
        requests = []
 
957
        for key in reversed(order):
 
958
            index, value, references = by_key[key]
 
959
            # ---- KnitGraphIndex.get_position
 
960
            bits = value[1:].split(' ')
 
961
            offset, length = int(bits[0]), int(bits[1])
 
962
            requests.append(
 
963
                (index, [(offset, length)], [(key, value[0], references)]))
 
964
        # TODO: combine requests in the same index that are in ascending order.
 
965
        return total, requests
 
966
 
 
967
 
 
968
class ReconcilePacker(Packer):
 
969
    """A packer which regenerates indices etc as it copies.
 
970
    
 
971
    This is used by ``bzr reconcile`` to cause parent text pointers to be
 
972
    regenerated.
 
973
    """
 
974
 
 
975
    def _extra_init(self):
 
976
        self._data_changed = False
 
977
 
 
978
    def _process_inventory_lines(self, inv_lines):
 
979
        """Generate a text key reference map rather for reconciling with."""
 
980
        repo = self._pack_collection.repo
 
981
        refs = repo._find_text_key_references_from_xml_inventory_lines(
 
982
            inv_lines)
 
983
        self._text_refs = refs
 
984
        # during reconcile we:
 
985
        #  - convert unreferenced texts to full texts
 
986
        #  - correct texts which reference a text not copied to be full texts
 
987
        #  - copy all others as-is but with corrected parents.
 
988
        #  - so at this point we don't know enough to decide what becomes a full
 
989
        #    text.
 
990
        self._text_filter = None
 
991
 
 
992
    def _copy_text_texts(self):
 
993
        """generate what texts we should have and then copy."""
 
994
        self.pb.update("Copying content texts", 3)
 
995
        # we have three major tasks here:
 
996
        # 1) generate the ideal index
 
997
        repo = self._pack_collection.repo
 
998
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
 
999
            _1, key, _2, refs in 
 
1000
            self.new_pack.revision_index.iter_all_entries()])
 
1001
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
 
1002
        # 2) generate a text_nodes list that contains all the deltas that can
 
1003
        #    be used as-is, with corrected parents.
 
1004
        ok_nodes = []
 
1005
        bad_texts = []
 
1006
        discarded_nodes = []
 
1007
        NULL_REVISION = _mod_revision.NULL_REVISION
 
1008
        text_index_map, text_nodes = self._get_text_nodes()
 
1009
        for node in text_nodes:
 
1010
            # 0 - index
 
1011
            # 1 - key 
 
1012
            # 2 - value
 
1013
            # 3 - refs
 
1014
            try:
 
1015
                ideal_parents = tuple(ideal_index[node[1]])
 
1016
            except KeyError:
 
1017
                discarded_nodes.append(node)
 
1018
                self._data_changed = True
 
1019
            else:
 
1020
                if ideal_parents == (NULL_REVISION,):
 
1021
                    ideal_parents = ()
 
1022
                if ideal_parents == node[3][0]:
 
1023
                    # no change needed.
 
1024
                    ok_nodes.append(node)
 
1025
                elif ideal_parents[0:1] == node[3][0][0:1]:
 
1026
                    # the left most parent is the same, or there are no parents
 
1027
                    # today. Either way, we can preserve the representation as
 
1028
                    # long as we change the refs to be inserted.
 
1029
                    self._data_changed = True
 
1030
                    ok_nodes.append((node[0], node[1], node[2],
 
1031
                        (ideal_parents, node[3][1])))
 
1032
                    self._data_changed = True
 
1033
                else:
 
1034
                    # Reinsert this text completely
 
1035
                    bad_texts.append((node[1], ideal_parents))
 
1036
                    self._data_changed = True
 
1037
        # we're finished with some data.
 
1038
        del ideal_index
 
1039
        del text_nodes
 
1040
        # 3) bulk copy the ok data
 
1041
        total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
 
1042
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
 
1043
            self.new_pack.text_index, readv_group_iter, total_items))
 
1044
        # 4) adhoc copy all the other texts.
 
1045
        # We have to topologically insert all texts otherwise we can fail to
 
1046
        # reconcile when parts of a single delta chain are preserved intact,
 
1047
        # and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
 
1048
        # reinserted, and if d3 has incorrect parents it will also be
 
1049
        # reinserted. If we insert d3 first, d2 is present (as it was bulk
 
1050
        # copied), so we will try to delta, but d2 is not currently able to be
 
1051
        # extracted because it's basis d1 is not present. Topologically sorting
 
1052
        # addresses this. The following generates a sort for all the texts that
 
1053
        # are being inserted without having to reference the entire text key
 
1054
        # space (we only topo sort the revisions, which is smaller).
 
1055
        topo_order = tsort.topo_sort(ancestors)
 
1056
        rev_order = dict(zip(topo_order, range(len(topo_order))))
 
1057
        bad_texts.sort(key=lambda key:rev_order[key[0][1]])
 
1058
        transaction = repo.get_transaction()
 
1059
        file_id_index = GraphIndexPrefixAdapter(
 
1060
            self.new_pack.text_index,
 
1061
            ('blank', ), 1,
 
1062
            add_nodes_callback=self.new_pack.text_index.add_nodes)
 
1063
        data_access = _DirectPackAccess(
 
1064
                {self.new_pack.text_index:self.new_pack.access_tuple()})
 
1065
        data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
 
1066
            self.new_pack.access_tuple())
 
1067
        output_texts = KnitVersionedFiles(
 
1068
            _KnitGraphIndex(self.new_pack.text_index,
 
1069
                add_callback=self.new_pack.text_index.add_nodes,
 
1070
                deltas=True, parents=True, is_locked=repo.is_locked),
 
1071
            data_access=data_access, max_delta_chain=200)
 
1072
        for key, parent_keys in bad_texts:
 
1073
            # We refer to the new pack to delta data being output.
 
1074
            # A possible improvement would be to catch errors on short reads
 
1075
            # and only flush then.
 
1076
            self.new_pack.flush()
 
1077
            parents = []
 
1078
            for parent_key in parent_keys:
 
1079
                if parent_key[0] != key[0]:
 
1080
                    # Graph parents must match the fileid
 
1081
                    raise errors.BzrError('Mismatched key parent %r:%r' %
 
1082
                        (key, parent_keys))
 
1083
                parents.append(parent_key[1])
 
1084
            text_lines = split_lines(repo.texts.get_record_stream(
 
1085
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
 
1086
            output_texts.add_lines(key, parent_keys, text_lines,
 
1087
                random_id=True, check_content=False)
 
1088
        # 5) check that nothing inserted has a reference outside the keyspace.
 
1089
        missing_text_keys = self.new_pack._external_compression_parents_of_texts()
 
1090
        if missing_text_keys:
 
1091
            raise errors.BzrError('Reference to missing compression parents %r'
 
1092
                % (missing_text_keys,))
 
1093
        self._log_copied_texts()
 
1094
 
 
1095
    def _use_pack(self, new_pack):
 
1096
        """Override _use_pack to check for reconcile having changed content."""
 
1097
        # XXX: we might be better checking this at the copy time.
 
1098
        original_inventory_keys = set()
 
1099
        inv_index = self._pack_collection.inventory_index.combined_index
 
1100
        for entry in inv_index.iter_all_entries():
 
1101
            original_inventory_keys.add(entry[1])
 
1102
        new_inventory_keys = set()
 
1103
        for entry in new_pack.inventory_index.iter_all_entries():
 
1104
            new_inventory_keys.add(entry[1])
 
1105
        if new_inventory_keys != original_inventory_keys:
 
1106
            self._data_changed = True
 
1107
        return new_pack.data_inserted() and self._data_changed
 
1108
 
 
1109
 
 
1110
class RepositoryPackCollection(object):
 
1111
    """Management of packs within a repository.
 
1112
    
 
1113
    :ivar _names: map of {pack_name: (index_size,)}
 
1114
    """
 
1115
 
 
1116
    def __init__(self, repo, transport, index_transport, upload_transport,
 
1117
                 pack_transport):
 
1118
        """Create a new RepositoryPackCollection.
 
1119
 
 
1120
        :param transport: Addresses the repository base directory 
 
1121
            (typically .bzr/repository/).
 
1122
        :param index_transport: Addresses the directory containing indices.
 
1123
        :param upload_transport: Addresses the directory into which packs are written
 
1124
            while they're being created.
 
1125
        :param pack_transport: Addresses the directory of existing complete packs.
 
1126
        """
 
1127
        self.repo = repo
 
1128
        self.transport = transport
 
1129
        self._index_transport = index_transport
 
1130
        self._upload_transport = upload_transport
 
1131
        self._pack_transport = pack_transport
 
1132
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
 
1133
        self.packs = []
 
1134
        # name:Pack mapping
 
1135
        self._packs_by_name = {}
 
1136
        # the previous pack-names content
 
1137
        self._packs_at_load = None
 
1138
        # when a pack is being created by this object, the state of that pack.
 
1139
        self._new_pack = None
 
1140
        # aggregated revision index data
 
1141
        self.revision_index = AggregateIndex()
 
1142
        self.inventory_index = AggregateIndex()
 
1143
        self.text_index = AggregateIndex()
 
1144
        self.signature_index = AggregateIndex()
 
1145
 
 
1146
    def add_pack_to_memory(self, pack):
 
1147
        """Make a Pack object available to the repository to satisfy queries.
 
1148
        
 
1149
        :param pack: A Pack object.
 
1150
        """
 
1151
        if pack.name in self._packs_by_name:
 
1152
            raise AssertionError()
 
1153
        self.packs.append(pack)
 
1154
        self._packs_by_name[pack.name] = pack
 
1155
        self.revision_index.add_index(pack.revision_index, pack)
 
1156
        self.inventory_index.add_index(pack.inventory_index, pack)
 
1157
        self.text_index.add_index(pack.text_index, pack)
 
1158
        self.signature_index.add_index(pack.signature_index, pack)
 
1159
        
 
1160
    def all_packs(self):
 
1161
        """Return a list of all the Pack objects this repository has.
 
1162
 
 
1163
        Note that an in-progress pack being created is not returned.
 
1164
 
 
1165
        :return: A list of Pack objects for all the packs in the repository.
 
1166
        """
 
1167
        result = []
 
1168
        for name in self.names():
 
1169
            result.append(self.get_pack_by_name(name))
 
1170
        return result
 
1171
 
 
1172
    def autopack(self):
 
1173
        """Pack the pack collection incrementally.
 
1174
        
 
1175
        This will not attempt global reorganisation or recompression,
 
1176
        rather it will just ensure that the total number of packs does
 
1177
        not grow without bound. It uses the _max_pack_count method to
 
1178
        determine if autopacking is needed, and the pack_distribution
 
1179
        method to determine the number of revisions in each pack.
 
1180
 
 
1181
        If autopacking takes place then the packs name collection will have
 
1182
        been flushed to disk - packing requires updating the name collection
 
1183
        in synchronisation with certain steps. Otherwise the names collection
 
1184
        is not flushed.
 
1185
 
 
1186
        :return: True if packing took place.
 
1187
        """
 
1188
        # XXX: Should not be needed when the management of indices is sane.
 
1189
        total_revisions = self.revision_index.combined_index.key_count()
 
1190
        total_packs = len(self._names)
 
1191
        if self._max_pack_count(total_revisions) >= total_packs:
 
1192
            return False
 
1193
        # XXX: the following may want to be a class, to pack with a given
 
1194
        # policy.
 
1195
        mutter('Auto-packing repository %s, which has %d pack files, '
 
1196
            'containing %d revisions into %d packs.', self, total_packs,
 
1197
            total_revisions, self._max_pack_count(total_revisions))
 
1198
        # determine which packs need changing
 
1199
        pack_distribution = self.pack_distribution(total_revisions)
 
1200
        existing_packs = []
 
1201
        for pack in self.all_packs():
 
1202
            revision_count = pack.get_revision_count()
 
1203
            if revision_count == 0:
 
1204
                # revision less packs are not generated by normal operation,
 
1205
                # only by operations like sign-my-commits, and thus will not
 
1206
                # tend to grow rapdily or without bound like commit containing
 
1207
                # packs do - leave them alone as packing them really should
 
1208
                # group their data with the relevant commit, and that may
 
1209
                # involve rewriting ancient history - which autopack tries to
 
1210
                # avoid. Alternatively we could not group the data but treat
 
1211
                # each of these as having a single revision, and thus add 
 
1212
                # one revision for each to the total revision count, to get
 
1213
                # a matching distribution.
 
1214
                continue
 
1215
            existing_packs.append((revision_count, pack))
 
1216
        pack_operations = self.plan_autopack_combinations(
 
1217
            existing_packs, pack_distribution)
 
1218
        self._execute_pack_operations(pack_operations)
 
1219
        return True
 
1220
 
 
1221
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer):
 
1222
        """Execute a series of pack operations.
 
1223
 
 
1224
        :param pack_operations: A list of [revision_count, packs_to_combine].
 
1225
        :param _packer_class: The class of packer to use (default: Packer).
 
1226
        :return: None.
 
1227
        """
 
1228
        for revision_count, packs in pack_operations:
 
1229
            # we may have no-ops from the setup logic
 
1230
            if len(packs) == 0:
 
1231
                continue
 
1232
            _packer_class(self, packs, '.autopack').pack()
 
1233
            for pack in packs:
 
1234
                self._remove_pack_from_memory(pack)
 
1235
        # record the newly available packs and stop advertising the old
 
1236
        # packs
 
1237
        self._save_pack_names(clear_obsolete_packs=True)
 
1238
        # Move the old packs out of the way now they are no longer referenced.
 
1239
        for revision_count, packs in pack_operations:
 
1240
            self._obsolete_packs(packs)
 
1241
 
 
1242
    def lock_names(self):
 
1243
        """Acquire the mutex around the pack-names index.
 
1244
        
 
1245
        This cannot be used in the middle of a read-only transaction on the
 
1246
        repository.
 
1247
        """
 
1248
        self.repo.control_files.lock_write()
 
1249
 
 
1250
    def pack(self):
 
1251
        """Pack the pack collection totally."""
 
1252
        self.ensure_loaded()
 
1253
        total_packs = len(self._names)
 
1254
        if total_packs < 2:
 
1255
            # This is arguably wrong because we might not be optimal, but for
 
1256
            # now lets leave it in. (e.g. reconcile -> one pack. But not
 
1257
            # optimal.
 
1258
            return
 
1259
        total_revisions = self.revision_index.combined_index.key_count()
 
1260
        # XXX: the following may want to be a class, to pack with a given
 
1261
        # policy.
 
1262
        mutter('Packing repository %s, which has %d pack files, '
 
1263
            'containing %d revisions into 1 packs.', self, total_packs,
 
1264
            total_revisions)
 
1265
        # determine which packs need changing
 
1266
        pack_distribution = [1]
 
1267
        pack_operations = [[0, []]]
 
1268
        for pack in self.all_packs():
 
1269
            pack_operations[-1][0] += pack.get_revision_count()
 
1270
            pack_operations[-1][1].append(pack)
 
1271
        self._execute_pack_operations(pack_operations, OptimisingPacker)
 
1272
 
 
1273
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
 
1274
        """Plan a pack operation.
 
1275
 
 
1276
        :param existing_packs: The packs to pack. (A list of (revcount, Pack)
 
1277
            tuples).
 
1278
        :param pack_distribution: A list with the number of revisions desired
 
1279
            in each pack.
 
1280
        """
 
1281
        if len(existing_packs) <= len(pack_distribution):
 
1282
            return []
 
1283
        existing_packs.sort(reverse=True)
 
1284
        pack_operations = [[0, []]]
 
1285
        # plan out what packs to keep, and what to reorganise
 
1286
        while len(existing_packs):
 
1287
            # take the largest pack, and if its less than the head of the
 
1288
            # distribution chart we will include its contents in the new pack for
 
1289
            # that position. If its larger, we remove its size from the
 
1290
            # distribution chart
 
1291
            next_pack_rev_count, next_pack = existing_packs.pop(0)
 
1292
            if next_pack_rev_count >= pack_distribution[0]:
 
1293
                # this is already packed 'better' than this, so we can
 
1294
                # not waste time packing it.
 
1295
                while next_pack_rev_count > 0:
 
1296
                    next_pack_rev_count -= pack_distribution[0]
 
1297
                    if next_pack_rev_count >= 0:
 
1298
                        # more to go
 
1299
                        del pack_distribution[0]
 
1300
                    else:
 
1301
                        # didn't use that entire bucket up
 
1302
                        pack_distribution[0] = -next_pack_rev_count
 
1303
            else:
 
1304
                # add the revisions we're going to add to the next output pack
 
1305
                pack_operations[-1][0] += next_pack_rev_count
 
1306
                # allocate this pack to the next pack sub operation
 
1307
                pack_operations[-1][1].append(next_pack)
 
1308
                if pack_operations[-1][0] >= pack_distribution[0]:
 
1309
                    # this pack is used up, shift left.
 
1310
                    del pack_distribution[0]
 
1311
                    pack_operations.append([0, []])
 
1312
        
 
1313
        return pack_operations
 
1314
 
 
1315
    def ensure_loaded(self):
 
1316
        # NB: if you see an assertion error here, its probably access against
 
1317
        # an unlocked repo. Naughty.
 
1318
        if not self.repo.is_locked():
 
1319
            raise errors.ObjectNotLocked(self.repo)
 
1320
        if self._names is None:
 
1321
            self._names = {}
 
1322
            self._packs_at_load = set()
 
1323
            for index, key, value in self._iter_disk_pack_index():
 
1324
                name = key[0]
 
1325
                self._names[name] = self._parse_index_sizes(value)
 
1326
                self._packs_at_load.add((key, value))
 
1327
        # populate all the metadata.
 
1328
        self.all_packs()
 
1329
 
 
1330
    def _parse_index_sizes(self, value):
 
1331
        """Parse a string of index sizes."""
 
1332
        return tuple([int(digits) for digits in value.split(' ')])
 
1333
 
 
1334
    def get_pack_by_name(self, name):
 
1335
        """Get a Pack object by name.
 
1336
 
 
1337
        :param name: The name of the pack - e.g. '123456'
 
1338
        :return: A Pack object.
 
1339
        """
 
1340
        try:
 
1341
            return self._packs_by_name[name]
 
1342
        except KeyError:
 
1343
            rev_index = self._make_index(name, '.rix')
 
1344
            inv_index = self._make_index(name, '.iix')
 
1345
            txt_index = self._make_index(name, '.tix')
 
1346
            sig_index = self._make_index(name, '.six')
 
1347
            result = ExistingPack(self._pack_transport, name, rev_index,
 
1348
                inv_index, txt_index, sig_index)
 
1349
            self.add_pack_to_memory(result)
 
1350
            return result
 
1351
 
 
1352
    def allocate(self, a_new_pack):
 
1353
        """Allocate name in the list of packs.
 
1354
 
 
1355
        :param a_new_pack: A NewPack instance to be added to the collection of
 
1356
            packs for this repository.
 
1357
        """
 
1358
        self.ensure_loaded()
 
1359
        if a_new_pack.name in self._names:
 
1360
            raise errors.BzrError(
 
1361
                'Pack %r already exists in %s' % (a_new_pack.name, self))
 
1362
        self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
 
1363
        self.add_pack_to_memory(a_new_pack)
 
1364
 
 
1365
    def _iter_disk_pack_index(self):
 
1366
        """Iterate over the contents of the pack-names index.
 
1367
        
 
1368
        This is used when loading the list from disk, and before writing to
 
1369
        detect updates from others during our write operation.
 
1370
        :return: An iterator of the index contents.
 
1371
        """
 
1372
        return GraphIndex(self.transport, 'pack-names', None
 
1373
                ).iter_all_entries()
 
1374
 
 
1375
    def _make_index(self, name, suffix):
 
1376
        size_offset = self._suffix_offsets[suffix]
 
1377
        index_name = name + suffix
 
1378
        index_size = self._names[name][size_offset]
 
1379
        return GraphIndex(
 
1380
            self._index_transport, index_name, index_size)
 
1381
 
 
1382
    def _max_pack_count(self, total_revisions):
 
1383
        """Return the maximum number of packs to use for total revisions.
 
1384
        
 
1385
        :param total_revisions: The total number of revisions in the
 
1386
            repository.
 
1387
        """
 
1388
        if not total_revisions:
 
1389
            return 1
 
1390
        digits = str(total_revisions)
 
1391
        result = 0
 
1392
        for digit in digits:
 
1393
            result += int(digit)
 
1394
        return result
 
1395
 
 
1396
    def names(self):
 
1397
        """Provide an order to the underlying names."""
 
1398
        return sorted(self._names.keys())
 
1399
 
 
1400
    def _obsolete_packs(self, packs):
 
1401
        """Move a number of packs which have been obsoleted out of the way.
 
1402
 
 
1403
        Each pack and its associated indices are moved out of the way.
 
1404
 
 
1405
        Note: for correctness this function should only be called after a new
 
1406
        pack names index has been written without these pack names, and with
 
1407
        the names of packs that contain the data previously available via these
 
1408
        packs.
 
1409
 
 
1410
        :param packs: The packs to obsolete.
 
1411
        :param return: None.
 
1412
        """
 
1413
        for pack in packs:
 
1414
            pack.pack_transport.rename(pack.file_name(),
 
1415
                '../obsolete_packs/' + pack.file_name())
 
1416
            # TODO: Probably needs to know all possible indices for this pack
 
1417
            # - or maybe list the directory and move all indices matching this
 
1418
            # name whether we recognize it or not?
 
1419
            for suffix in ('.iix', '.six', '.tix', '.rix'):
 
1420
                self._index_transport.rename(pack.name + suffix,
 
1421
                    '../obsolete_packs/' + pack.name + suffix)
 
1422
 
 
1423
    def pack_distribution(self, total_revisions):
 
1424
        """Generate a list of the number of revisions to put in each pack.
 
1425
 
 
1426
        :param total_revisions: The total number of revisions in the
 
1427
            repository.
 
1428
        """
 
1429
        if total_revisions == 0:
 
1430
            return [0]
 
1431
        digits = reversed(str(total_revisions))
 
1432
        result = []
 
1433
        for exponent, count in enumerate(digits):
 
1434
            size = 10 ** exponent
 
1435
            for pos in range(int(count)):
 
1436
                result.append(size)
 
1437
        return list(reversed(result))
 
1438
 
 
1439
    def _pack_tuple(self, name):
 
1440
        """Return a tuple with the transport and file name for a pack name."""
 
1441
        return self._pack_transport, name + '.pack'
 
1442
 
 
1443
    def _remove_pack_from_memory(self, pack):
 
1444
        """Remove pack from the packs accessed by this repository.
 
1445
        
 
1446
        Only affects memory state, until self._save_pack_names() is invoked.
 
1447
        """
 
1448
        self._names.pop(pack.name)
 
1449
        self._packs_by_name.pop(pack.name)
 
1450
        self._remove_pack_indices(pack)
 
1451
 
 
1452
    def _remove_pack_indices(self, pack):
 
1453
        """Remove the indices for pack from the aggregated indices."""
 
1454
        self.revision_index.remove_index(pack.revision_index, pack)
 
1455
        self.inventory_index.remove_index(pack.inventory_index, pack)
 
1456
        self.text_index.remove_index(pack.text_index, pack)
 
1457
        self.signature_index.remove_index(pack.signature_index, pack)
 
1458
 
 
1459
    def reset(self):
 
1460
        """Clear all cached data."""
 
1461
        # cached revision data
 
1462
        self.repo._revision_knit = None
 
1463
        self.revision_index.clear()
 
1464
        # cached signature data
 
1465
        self.repo._signature_knit = None
 
1466
        self.signature_index.clear()
 
1467
        # cached file text data
 
1468
        self.text_index.clear()
 
1469
        self.repo._text_knit = None
 
1470
        # cached inventory data
 
1471
        self.inventory_index.clear()
 
1472
        # remove the open pack
 
1473
        self._new_pack = None
 
1474
        # information about packs.
 
1475
        self._names = None
 
1476
        self.packs = []
 
1477
        self._packs_by_name = {}
 
1478
        self._packs_at_load = None
 
1479
 
 
1480
    def _make_index_map(self, index_suffix):
 
1481
        """Return information on existing indices.
 
1482
 
 
1483
        :param suffix: Index suffix added to pack name.
 
1484
 
 
1485
        :returns: (pack_map, indices) where indices is a list of GraphIndex 
 
1486
        objects, and pack_map is a mapping from those objects to the 
 
1487
        pack tuple they describe.
 
1488
        """
 
1489
        # TODO: stop using this; it creates new indices unnecessarily.
 
1490
        self.ensure_loaded()
 
1491
        suffix_map = {'.rix': 'revision_index',
 
1492
            '.six': 'signature_index',
 
1493
            '.iix': 'inventory_index',
 
1494
            '.tix': 'text_index',
 
1495
        }
 
1496
        return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
 
1497
            suffix_map[index_suffix])
 
1498
 
 
1499
    def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
 
1500
        """Convert a list of packs to an index pack map and index list.
 
1501
 
 
1502
        :param packs: The packs list to process.
 
1503
        :param index_attribute: The attribute that the desired index is found
 
1504
            on.
 
1505
        :return: A tuple (map, list) where map contains the dict from
 
1506
            index:pack_tuple, and lsit contains the indices in the same order
 
1507
            as the packs list.
 
1508
        """
 
1509
        indices = []
 
1510
        pack_map = {}
 
1511
        for pack in packs:
 
1512
            index = getattr(pack, index_attribute)
 
1513
            indices.append(index)
 
1514
            pack_map[index] = (pack.pack_transport, pack.file_name())
 
1515
        return pack_map, indices
 
1516
 
 
1517
    def _index_contents(self, pack_map, key_filter=None):
 
1518
        """Get an iterable of the index contents from a pack_map.
 
1519
 
 
1520
        :param pack_map: A map from indices to pack details.
 
1521
        :param key_filter: An optional filter to limit the
 
1522
            keys returned.
 
1523
        """
 
1524
        indices = [index for index in pack_map.iterkeys()]
 
1525
        all_index = CombinedGraphIndex(indices)
 
1526
        if key_filter is None:
 
1527
            return all_index.iter_all_entries()
 
1528
        else:
 
1529
            return all_index.iter_entries(key_filter)
 
1530
 
 
1531
    def _unlock_names(self):
 
1532
        """Release the mutex around the pack-names index."""
 
1533
        self.repo.control_files.unlock()
 
1534
 
 
1535
    def _save_pack_names(self, clear_obsolete_packs=False):
 
1536
        """Save the list of packs.
 
1537
 
 
1538
        This will take out the mutex around the pack names list for the
 
1539
        duration of the method call. If concurrent updates have been made, a
 
1540
        three-way merge between the current list and the current in memory list
 
1541
        is performed.
 
1542
 
 
1543
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1544
            obsolete_packs directory.
 
1545
        """
 
1546
        self.lock_names()
 
1547
        try:
 
1548
            builder = GraphIndexBuilder()
 
1549
            # load the disk nodes across
 
1550
            disk_nodes = set()
 
1551
            for index, key, value in self._iter_disk_pack_index():
 
1552
                disk_nodes.add((key, value))
 
1553
            # do a two-way diff against our original content
 
1554
            current_nodes = set()
 
1555
            for name, sizes in self._names.iteritems():
 
1556
                current_nodes.add(
 
1557
                    ((name, ), ' '.join(str(size) for size in sizes)))
 
1558
            deleted_nodes = self._packs_at_load - current_nodes
 
1559
            new_nodes = current_nodes - self._packs_at_load
 
1560
            disk_nodes.difference_update(deleted_nodes)
 
1561
            disk_nodes.update(new_nodes)
 
1562
            # TODO: handle same-name, index-size-changes here - 
 
1563
            # e.g. use the value from disk, not ours, *unless* we're the one
 
1564
            # changing it.
 
1565
            for key, value in disk_nodes:
 
1566
                builder.add_node(key, value)
 
1567
            self.transport.put_file('pack-names', builder.finish(),
 
1568
                mode=self.repo.bzrdir._get_file_mode())
 
1569
            # move the baseline forward
 
1570
            self._packs_at_load = disk_nodes
 
1571
            if clear_obsolete_packs:
 
1572
                self._clear_obsolete_packs()
 
1573
        finally:
 
1574
            self._unlock_names()
 
1575
        # synchronise the memory packs list with what we just wrote:
 
1576
        new_names = dict(disk_nodes)
 
1577
        # drop no longer present nodes
 
1578
        for pack in self.all_packs():
 
1579
            if (pack.name,) not in new_names:
 
1580
                self._remove_pack_from_memory(pack)
 
1581
        # add new nodes/refresh existing ones
 
1582
        for key, value in disk_nodes:
 
1583
            name = key[0]
 
1584
            sizes = self._parse_index_sizes(value)
 
1585
            if name in self._names:
 
1586
                # existing
 
1587
                if sizes != self._names[name]:
 
1588
                    # the pack for name has had its indices replaced - rare but
 
1589
                    # important to handle. XXX: probably can never happen today
 
1590
                    # because the three-way merge code above does not handle it
 
1591
                    # - you may end up adding the same key twice to the new
 
1592
                    # disk index because the set values are the same, unless
 
1593
                    # the only index shows up as deleted by the set difference
 
1594
                    # - which it may. Until there is a specific test for this,
 
1595
                    # assume its broken. RBC 20071017.
 
1596
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
 
1597
                    self._names[name] = sizes
 
1598
                    self.get_pack_by_name(name)
 
1599
            else:
 
1600
                # new
 
1601
                self._names[name] = sizes
 
1602
                self.get_pack_by_name(name)
 
1603
 
 
1604
    def _clear_obsolete_packs(self):
 
1605
        """Delete everything from the obsolete-packs directory.
 
1606
        """
 
1607
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
 
1608
        for filename in obsolete_pack_transport.list_dir('.'):
 
1609
            try:
 
1610
                obsolete_pack_transport.delete(filename)
 
1611
            except (errors.PathError, errors.TransportError), e:
 
1612
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
 
1613
 
 
1614
    def _start_write_group(self):
 
1615
        # Do not permit preparation for writing if we're not in a 'write lock'.
 
1616
        if not self.repo.is_write_locked():
 
1617
            raise errors.NotWriteLocked(self)
 
1618
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
 
1619
            self._pack_transport, upload_suffix='.pack',
 
1620
            file_mode=self.repo.bzrdir._get_file_mode())
 
1621
        # allow writing: queue writes to a new index
 
1622
        self.revision_index.add_writable_index(self._new_pack.revision_index,
 
1623
            self._new_pack)
 
1624
        self.inventory_index.add_writable_index(self._new_pack.inventory_index,
 
1625
            self._new_pack)
 
1626
        self.text_index.add_writable_index(self._new_pack.text_index,
 
1627
            self._new_pack)
 
1628
        self.signature_index.add_writable_index(self._new_pack.signature_index,
 
1629
            self._new_pack)
 
1630
 
 
1631
        self.repo.inventories._index._add_callback = self.inventory_index.add_callback
 
1632
        self.repo.revisions._index._add_callback = self.revision_index.add_callback
 
1633
        self.repo.signatures._index._add_callback = self.signature_index.add_callback
 
1634
        self.repo.texts._index._add_callback = self.text_index.add_callback
 
1635
 
 
1636
    def _abort_write_group(self):
 
1637
        # FIXME: just drop the transient index.
 
1638
        # forget what names there are
 
1639
        if self._new_pack is not None:
 
1640
            self._new_pack.abort()
 
1641
            self._remove_pack_indices(self._new_pack)
 
1642
            self._new_pack = None
 
1643
        self.repo._text_knit = None
 
1644
 
 
1645
    def _commit_write_group(self):
 
1646
        self._remove_pack_indices(self._new_pack)
 
1647
        if self._new_pack.data_inserted():
 
1648
            # get all the data to disk and read to use
 
1649
            self._new_pack.finish()
 
1650
            self.allocate(self._new_pack)
 
1651
            self._new_pack = None
 
1652
            if not self.autopack():
 
1653
                # when autopack takes no steps, the names list is still
 
1654
                # unsaved.
 
1655
                self._save_pack_names()
 
1656
        else:
 
1657
            self._new_pack.abort()
 
1658
            self._new_pack = None
 
1659
        self.repo._text_knit = None
 
1660
 
 
1661
 
 
1662
class KnitPackRepository(KnitRepository):
 
1663
    """Repository with knit objects stored inside pack containers.
 
1664
    
 
1665
    The layering for a KnitPackRepository is:
 
1666
 
 
1667
    Graph        |  HPSS    | Repository public layer |
 
1668
    ===================================================
 
1669
    Tuple based apis below, string based, and key based apis above
 
1670
    ---------------------------------------------------
 
1671
    KnitVersionedFiles
 
1672
      Provides .texts, .revisions etc
 
1673
      This adapts the N-tuple keys to physical knit records which only have a
 
1674
      single string identifier (for historical reasons), which in older formats
 
1675
      was always the revision_id, and in the mapped code for packs is always
 
1676
      the last element of key tuples.
 
1677
    ---------------------------------------------------
 
1678
    GraphIndex
 
1679
      A separate GraphIndex is used for each of the
 
1680
      texts/inventories/revisions/signatures contained within each individual
 
1681
      pack file. The GraphIndex layer works in N-tuples and is unaware of any
 
1682
      semantic value.
 
1683
    ===================================================
 
1684
    
 
1685
    """
 
1686
 
 
1687
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
 
1688
        _serializer):
 
1689
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
 
1690
            _commit_builder_class, _serializer)
 
1691
        index_transport = self._transport.clone('indices')
 
1692
        self._pack_collection = RepositoryPackCollection(self, self._transport,
 
1693
            index_transport,
 
1694
            self._transport.clone('upload'),
 
1695
            self._transport.clone('packs'))
 
1696
        self.inventories = KnitVersionedFiles(
 
1697
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
 
1698
                add_callback=self._pack_collection.inventory_index.add_callback,
 
1699
                deltas=True, parents=True, is_locked=self.is_locked),
 
1700
            data_access=self._pack_collection.inventory_index.data_access,
 
1701
            max_delta_chain=200)
 
1702
        self.revisions = KnitVersionedFiles(
 
1703
            _KnitGraphIndex(self._pack_collection.revision_index.combined_index,
 
1704
                add_callback=self._pack_collection.revision_index.add_callback,
 
1705
                deltas=False, parents=True, is_locked=self.is_locked),
 
1706
            data_access=self._pack_collection.revision_index.data_access,
 
1707
            max_delta_chain=0)
 
1708
        self.signatures = KnitVersionedFiles(
 
1709
            _KnitGraphIndex(self._pack_collection.signature_index.combined_index,
 
1710
                add_callback=self._pack_collection.signature_index.add_callback,
 
1711
                deltas=False, parents=False, is_locked=self.is_locked),
 
1712
            data_access=self._pack_collection.signature_index.data_access,
 
1713
            max_delta_chain=0)
 
1714
        self.texts = KnitVersionedFiles(
 
1715
            _KnitGraphIndex(self._pack_collection.text_index.combined_index,
 
1716
                add_callback=self._pack_collection.text_index.add_callback,
 
1717
                deltas=True, parents=True, is_locked=self.is_locked),
 
1718
            data_access=self._pack_collection.text_index.data_access,
 
1719
            max_delta_chain=200)
 
1720
        # True when the repository object is 'write locked' (as opposed to the
 
1721
        # physical lock only taken out around changes to the pack-names list.) 
 
1722
        # Another way to represent this would be a decorator around the control
 
1723
        # files object that presents logical locks as physical ones - if this
 
1724
        # gets ugly consider that alternative design. RBC 20071011
 
1725
        self._write_lock_count = 0
 
1726
        self._transaction = None
 
1727
        # for tests
 
1728
        self._reconcile_does_inventory_gc = True
 
1729
        self._reconcile_fixes_text_parents = True
 
1730
        self._reconcile_backsup_inventory = False
 
1731
 
 
1732
    def _abort_write_group(self):
 
1733
        self._pack_collection._abort_write_group()
 
1734
 
 
1735
    def _find_inconsistent_revision_parents(self):
 
1736
        """Find revisions with incorrectly cached parents.
 
1737
 
 
1738
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
1739
            parents-in-revision).
 
1740
        """
 
1741
        if not self.is_locked():
 
1742
            raise errors.ObjectNotLocked(self)
 
1743
        pb = ui.ui_factory.nested_progress_bar()
 
1744
        result = []
 
1745
        try:
 
1746
            revision_nodes = self._pack_collection.revision_index \
 
1747
                .combined_index.iter_all_entries()
 
1748
            index_positions = []
 
1749
            # Get the cached index values for all revisions, and also the location
 
1750
            # in each index of the revision text so we can perform linear IO.
 
1751
            for index, key, value, refs in revision_nodes:
 
1752
                pos, length = value[1:].split(' ')
 
1753
                index_positions.append((index, int(pos), key[0],
 
1754
                    tuple(parent[0] for parent in refs[0])))
 
1755
                pb.update("Reading revision index.", 0, 0)
 
1756
            index_positions.sort()
 
1757
            batch_count = len(index_positions) / 1000 + 1
 
1758
            pb.update("Checking cached revision graph.", 0, batch_count)
 
1759
            for offset in xrange(batch_count):
 
1760
                pb.update("Checking cached revision graph.", offset)
 
1761
                to_query = index_positions[offset * 1000:(offset + 1) * 1000]
 
1762
                if not to_query:
 
1763
                    break
 
1764
                rev_ids = [item[2] for item in to_query]
 
1765
                revs = self.get_revisions(rev_ids)
 
1766
                for revision, item in zip(revs, to_query):
 
1767
                    index_parents = item[3]
 
1768
                    rev_parents = tuple(revision.parent_ids)
 
1769
                    if index_parents != rev_parents:
 
1770
                        result.append((revision.revision_id, index_parents, rev_parents))
 
1771
        finally:
 
1772
            pb.finished()
 
1773
        return result
 
1774
 
 
1775
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
 
1776
    def get_parents(self, revision_ids):
 
1777
        """See graph._StackedParentsProvider.get_parents."""
 
1778
        parent_map = self.get_parent_map(revision_ids)
 
1779
        return [parent_map.get(r, None) for r in revision_ids]
 
1780
 
 
1781
    def _make_parents_provider(self):
 
1782
        return graph.CachingParentsProvider(self)
 
1783
 
 
1784
    def _refresh_data(self):
 
1785
        if self._write_lock_count == 1 or (
 
1786
            self.control_files._lock_count == 1 and
 
1787
            self.control_files._lock_mode == 'r'):
 
1788
            # forget what names there are
 
1789
            self._pack_collection.reset()
 
1790
            # XXX: Better to do an in-memory merge when acquiring a new lock -
 
1791
            # factor out code from _save_pack_names.
 
1792
            self._pack_collection.ensure_loaded()
 
1793
 
 
1794
    def _start_write_group(self):
 
1795
        self._pack_collection._start_write_group()
 
1796
 
 
1797
    def _commit_write_group(self):
 
1798
        return self._pack_collection._commit_write_group()
 
1799
 
 
1800
    def get_transaction(self):
 
1801
        if self._write_lock_count:
 
1802
            return self._transaction
 
1803
        else:
 
1804
            return self.control_files.get_transaction()
 
1805
 
 
1806
    def is_locked(self):
 
1807
        return self._write_lock_count or self.control_files.is_locked()
 
1808
 
 
1809
    def is_write_locked(self):
 
1810
        return self._write_lock_count
 
1811
 
 
1812
    def lock_write(self, token=None):
 
1813
        if not self._write_lock_count and self.is_locked():
 
1814
            raise errors.ReadOnlyError(self)
 
1815
        self._write_lock_count += 1
 
1816
        if self._write_lock_count == 1:
 
1817
            from bzrlib import transactions
 
1818
            self._transaction = transactions.WriteTransaction()
 
1819
            for repo in self._fallback_repositories:
 
1820
                # Writes don't affect fallback repos
 
1821
                repo.lock_read()
 
1822
        self._refresh_data()
 
1823
 
 
1824
    def lock_read(self):
 
1825
        if self._write_lock_count:
 
1826
            self._write_lock_count += 1
 
1827
        else:
 
1828
            self.control_files.lock_read()
 
1829
            for repo in self._fallback_repositories:
 
1830
                # Writes don't affect fallback repos
 
1831
                repo.lock_read()
 
1832
        self._refresh_data()
 
1833
 
 
1834
    def leave_lock_in_place(self):
 
1835
        # not supported - raise an error
 
1836
        raise NotImplementedError(self.leave_lock_in_place)
 
1837
 
 
1838
    def dont_leave_lock_in_place(self):
 
1839
        # not supported - raise an error
 
1840
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
1841
 
 
1842
    @needs_write_lock
 
1843
    def pack(self):
 
1844
        """Compress the data within the repository.
 
1845
 
 
1846
        This will pack all the data to a single pack. In future it may
 
1847
        recompress deltas or do other such expensive operations.
 
1848
        """
 
1849
        self._pack_collection.pack()
 
1850
 
 
1851
    @needs_write_lock
 
1852
    def reconcile(self, other=None, thorough=False):
 
1853
        """Reconcile this repository."""
 
1854
        from bzrlib.reconcile import PackReconciler
 
1855
        reconciler = PackReconciler(self, thorough=thorough)
 
1856
        reconciler.reconcile()
 
1857
        return reconciler
 
1858
 
 
1859
    def unlock(self):
 
1860
        if self._write_lock_count == 1 and self._write_group is not None:
 
1861
            self.abort_write_group()
 
1862
            self._transaction = None
 
1863
            self._write_lock_count = 0
 
1864
            raise errors.BzrError(
 
1865
                'Must end write group before releasing write lock on %s'
 
1866
                % self)
 
1867
        if self._write_lock_count:
 
1868
            self._write_lock_count -= 1
 
1869
            if not self._write_lock_count:
 
1870
                transaction = self._transaction
 
1871
                self._transaction = None
 
1872
                transaction.finish()
 
1873
                for repo in self._fallback_repositories:
 
1874
                    repo.unlock()
 
1875
        else:
 
1876
            self.control_files.unlock()
 
1877
            for repo in self._fallback_repositories:
 
1878
                repo.unlock()
 
1879
 
 
1880
 
 
1881
class RepositoryFormatPack(MetaDirRepositoryFormat):
 
1882
    """Format logic for pack structured repositories.
 
1883
 
 
1884
    This repository format has:
 
1885
     - a list of packs in pack-names
 
1886
     - packs in packs/NAME.pack
 
1887
     - indices in indices/NAME.{iix,six,tix,rix}
 
1888
     - knit deltas in the packs, knit indices mapped to the indices.
 
1889
     - thunk objects to support the knits programming API.
 
1890
     - a format marker of its own
 
1891
     - an optional 'shared-storage' flag
 
1892
     - an optional 'no-working-trees' flag
 
1893
     - a LockDir lock
 
1894
    """
 
1895
 
 
1896
    # Set this attribute in derived classes to control the repository class
 
1897
    # created by open and initialize.
 
1898
    repository_class = None
 
1899
    # Set this attribute in derived classes to control the
 
1900
    # _commit_builder_class that the repository objects will have passed to
 
1901
    # their constructor.
 
1902
    _commit_builder_class = None
 
1903
    # Set this attribute in derived clases to control the _serializer that the
 
1904
    # repository objects will have passed to their constructor.
 
1905
    _serializer = None
 
1906
    # External references are not supported in pack repositories yet.
 
1907
    supports_external_lookups = False
 
1908
 
 
1909
    def initialize(self, a_bzrdir, shared=False):
 
1910
        """Create a pack based repository.
 
1911
 
 
1912
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
1913
            be initialized.
 
1914
        :param shared: If true the repository will be initialized as a shared
 
1915
                       repository.
 
1916
        """
 
1917
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1918
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
 
1919
        builder = GraphIndexBuilder()
 
1920
        files = [('pack-names', builder.finish())]
 
1921
        utf8_files = [('format', self.get_format_string())]
 
1922
        
 
1923
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
1924
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1925
 
 
1926
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1927
        """See RepositoryFormat.open().
 
1928
        
 
1929
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1930
                                    repository at a slightly different url
 
1931
                                    than normal. I.e. during 'upgrade'.
 
1932
        """
 
1933
        if not _found:
 
1934
            format = RepositoryFormat.find_format(a_bzrdir)
 
1935
        if _override_transport is not None:
 
1936
            repo_transport = _override_transport
 
1937
        else:
 
1938
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1939
        control_files = lockable_files.LockableFiles(repo_transport,
 
1940
                                'lock', lockdir.LockDir)
 
1941
        return self.repository_class(_format=self,
 
1942
                              a_bzrdir=a_bzrdir,
 
1943
                              control_files=control_files,
 
1944
                              _commit_builder_class=self._commit_builder_class,
 
1945
                              _serializer=self._serializer)
 
1946
 
 
1947
 
 
1948
class RepositoryFormatKnitPack1(RepositoryFormatPack):
 
1949
    """A no-subtrees parameterized Pack repository.
 
1950
 
 
1951
    This format was introduced in 0.92.
 
1952
    """
 
1953
 
 
1954
    repository_class = KnitPackRepository
 
1955
    _commit_builder_class = PackCommitBuilder
 
1956
    _serializer = xml5.serializer_v5
 
1957
 
 
1958
    def _get_matching_bzrdir(self):
 
1959
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
 
1960
 
 
1961
    def _ignore_setting_bzrdir(self, format):
 
1962
        pass
 
1963
 
 
1964
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1965
 
 
1966
    def get_format_string(self):
 
1967
        """See RepositoryFormat.get_format_string()."""
 
1968
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
 
1969
 
 
1970
    def get_format_description(self):
 
1971
        """See RepositoryFormat.get_format_description()."""
 
1972
        return "Packs containing knits without subtree support"
 
1973
 
 
1974
    def check_conversion_target(self, target_format):
 
1975
        pass
 
1976
 
 
1977
 
 
1978
class RepositoryFormatPack(MetaDirRepositoryFormat):
 
1979
    """Format logic for pack structured repositories.
 
1980
 
 
1981
    This repository format has:
 
1982
     - a list of packs in pack-names
 
1983
     - packs in packs/NAME.pack
 
1984
     - indices in indices/NAME.{iix,six,tix,rix}
 
1985
     - knit deltas in the packs, knit indices mapped to the indices.
 
1986
     - thunk objects to support the knits programming API.
 
1987
     - a format marker of its own
 
1988
     - an optional 'shared-storage' flag
 
1989
     - an optional 'no-working-trees' flag
 
1990
     - a LockDir lock
 
1991
    """
 
1992
 
 
1993
    # Set this attribute in derived classes to control the repository class
 
1994
    # created by open and initialize.
 
1995
    repository_class = None
 
1996
    # Set this attribute in derived classes to control the
 
1997
    # _commit_builder_class that the repository objects will have passed to
 
1998
    # their constructor.
 
1999
    _commit_builder_class = None
 
2000
    # Set this attribute in derived clases to control the _serializer that the
 
2001
    # repository objects will have passed to their constructor.
 
2002
    _serializer = None
 
2003
    # External references are not supported in pack repositories yet.
 
2004
    supports_external_lookups = False
 
2005
 
 
2006
    def initialize(self, a_bzrdir, shared=False):
 
2007
        """Create a pack based repository.
 
2008
 
 
2009
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
2010
            be initialized.
 
2011
        :param shared: If true the repository will be initialized as a shared
 
2012
                       repository.
 
2013
        """
 
2014
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
2015
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
 
2016
        builder = GraphIndexBuilder()
 
2017
        files = [('pack-names', builder.finish())]
 
2018
        utf8_files = [('format', self.get_format_string())]
 
2019
        
 
2020
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
2021
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
2022
 
 
2023
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
2024
        """See RepositoryFormat.open().
 
2025
        
 
2026
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
2027
                                    repository at a slightly different url
 
2028
                                    than normal. I.e. during 'upgrade'.
 
2029
        """
 
2030
        if not _found:
 
2031
            format = RepositoryFormat.find_format(a_bzrdir)
 
2032
        if _override_transport is not None:
 
2033
            repo_transport = _override_transport
 
2034
        else:
 
2035
            repo_transport = a_bzrdir.get_repository_transport(None)
 
2036
        control_files = lockable_files.LockableFiles(repo_transport,
 
2037
                                'lock', lockdir.LockDir)
 
2038
        return self.repository_class(_format=self,
 
2039
                              a_bzrdir=a_bzrdir,
 
2040
                              control_files=control_files,
 
2041
                              _commit_builder_class=self._commit_builder_class,
 
2042
                              _serializer=self._serializer)
 
2043
 
 
2044
 
 
2045
class RepositoryFormatKnitPack1(RepositoryFormatPack):
 
2046
    """A no-subtrees parameterized Pack repository.
 
2047
 
 
2048
    This format was introduced in 0.92.
 
2049
    """
 
2050
 
 
2051
    repository_class = KnitPackRepository
 
2052
    _commit_builder_class = PackCommitBuilder
 
2053
    _serializer = xml5.serializer_v5
 
2054
 
 
2055
    def _get_matching_bzrdir(self):
 
2056
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
 
2057
 
 
2058
    def _ignore_setting_bzrdir(self, format):
 
2059
        pass
 
2060
 
 
2061
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2062
 
 
2063
    def get_format_string(self):
 
2064
        """See RepositoryFormat.get_format_string()."""
 
2065
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
 
2066
 
 
2067
    def get_format_description(self):
 
2068
        """See RepositoryFormat.get_format_description()."""
 
2069
        return "Packs containing knits without subtree support"
 
2070
 
 
2071
    def check_conversion_target(self, target_format):
 
2072
        pass
 
2073
 
 
2074
 
 
2075
class RepositoryFormatKnitPack3(RepositoryFormatPack):
 
2076
    """A subtrees parameterized Pack repository.
 
2077
 
 
2078
    This repository format uses the xml7 serializer to get:
 
2079
     - support for recording full info about the tree root
 
2080
     - support for recording tree-references
 
2081
 
 
2082
    This format was introduced in 0.92.
 
2083
    """
 
2084
 
 
2085
    repository_class = KnitPackRepository
 
2086
    _commit_builder_class = PackRootCommitBuilder
 
2087
    rich_root_data = True
 
2088
    supports_tree_reference = True
 
2089
    _serializer = xml7.serializer_v7
 
2090
 
 
2091
    def _get_matching_bzrdir(self):
 
2092
        return bzrdir.format_registry.make_bzrdir(
 
2093
            'pack-0.92-subtree')
 
2094
 
 
2095
    def _ignore_setting_bzrdir(self, format):
 
2096
        pass
 
2097
 
 
2098
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2099
 
 
2100
    def check_conversion_target(self, target_format):
 
2101
        if not target_format.rich_root_data:
 
2102
            raise errors.BadConversionTarget(
 
2103
                'Does not support rich root data.', target_format)
 
2104
        if not getattr(target_format, 'supports_tree_reference', False):
 
2105
            raise errors.BadConversionTarget(
 
2106
                'Does not support nested trees', target_format)
 
2107
            
 
2108
    def get_format_string(self):
 
2109
        """See RepositoryFormat.get_format_string()."""
 
2110
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
 
2111
 
 
2112
    def get_format_description(self):
 
2113
        """See RepositoryFormat.get_format_description()."""
 
2114
        return "Packs containing knits with subtree support\n"
 
2115
 
 
2116
 
 
2117
class RepositoryFormatKnitPack4(RepositoryFormatPack):
 
2118
    """A rich-root, no subtrees parameterized Pack repository.
 
2119
 
 
2120
    This repository format uses the xml6 serializer to get:
 
2121
     - support for recording full info about the tree root
 
2122
 
 
2123
    This format was introduced in 1.0.
 
2124
    """
 
2125
 
 
2126
    repository_class = KnitPackRepository
 
2127
    _commit_builder_class = PackRootCommitBuilder
 
2128
    rich_root_data = True
 
2129
    supports_tree_reference = False
 
2130
    _serializer = xml6.serializer_v6
 
2131
 
 
2132
    def _get_matching_bzrdir(self):
 
2133
        return bzrdir.format_registry.make_bzrdir(
 
2134
            'rich-root-pack')
 
2135
 
 
2136
    def _ignore_setting_bzrdir(self, format):
 
2137
        pass
 
2138
 
 
2139
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2140
 
 
2141
    def check_conversion_target(self, target_format):
 
2142
        if not target_format.rich_root_data:
 
2143
            raise errors.BadConversionTarget(
 
2144
                'Does not support rich root data.', target_format)
 
2145
 
 
2146
    def get_format_string(self):
 
2147
        """See RepositoryFormat.get_format_string()."""
 
2148
        return ("Bazaar pack repository format 1 with rich root"
 
2149
                " (needs bzr 1.0)\n")
 
2150
 
 
2151
    def get_format_description(self):
 
2152
        """See RepositoryFormat.get_format_description()."""
 
2153
        return "Packs containing knits with rich root support\n"
 
2154
 
 
2155
 
 
2156
class RepositoryFormatPackDevelopment0(RepositoryFormatPack):
 
2157
    """A no-subtrees development repository.
 
2158
 
 
2159
    This format should be retained until the second release after bzr 1.0.
 
2160
 
 
2161
    No changes to the disk behaviour from pack-0.92.
 
2162
    """
 
2163
 
 
2164
    repository_class = KnitPackRepository
 
2165
    _commit_builder_class = PackCommitBuilder
 
2166
    _serializer = xml5.serializer_v5
 
2167
 
 
2168
    def _get_matching_bzrdir(self):
 
2169
        return bzrdir.format_registry.make_bzrdir('development0')
 
2170
 
 
2171
    def _ignore_setting_bzrdir(self, format):
 
2172
        pass
 
2173
 
 
2174
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2175
 
 
2176
    def get_format_string(self):
 
2177
        """See RepositoryFormat.get_format_string()."""
 
2178
        return "Bazaar development format 0 (needs bzr.dev from before 1.3)\n"
 
2179
 
 
2180
    def get_format_description(self):
 
2181
        """See RepositoryFormat.get_format_description()."""
 
2182
        return ("Development repository format, currently the same as "
 
2183
            "pack-0.92\n")
 
2184
 
 
2185
    def check_conversion_target(self, target_format):
 
2186
        pass
 
2187
 
 
2188
 
 
2189
class RepositoryFormatPackDevelopment0Subtree(RepositoryFormatPack):
 
2190
    """A subtrees development repository.
 
2191
 
 
2192
    This format should be retained until the second release after bzr 1.0.
 
2193
 
 
2194
    No changes to the disk behaviour from pack-0.92-subtree.
 
2195
    """
 
2196
 
 
2197
    repository_class = KnitPackRepository
 
2198
    _commit_builder_class = PackRootCommitBuilder
 
2199
    rich_root_data = True
 
2200
    supports_tree_reference = True
 
2201
    _serializer = xml7.serializer_v7
 
2202
 
 
2203
    def _get_matching_bzrdir(self):
 
2204
        return bzrdir.format_registry.make_bzrdir(
 
2205
            'development0-subtree')
 
2206
 
 
2207
    def _ignore_setting_bzrdir(self, format):
 
2208
        pass
 
2209
 
 
2210
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2211
 
 
2212
    def check_conversion_target(self, target_format):
 
2213
        if not target_format.rich_root_data:
 
2214
            raise errors.BadConversionTarget(
 
2215
                'Does not support rich root data.', target_format)
 
2216
        if not getattr(target_format, 'supports_tree_reference', False):
 
2217
            raise errors.BadConversionTarget(
 
2218
                'Does not support nested trees', target_format)
 
2219
            
 
2220
    def get_format_string(self):
 
2221
        """See RepositoryFormat.get_format_string()."""
 
2222
        return ("Bazaar development format 0 with subtree support "
 
2223
            "(needs bzr.dev from before 1.3)\n")
 
2224
 
 
2225
    def get_format_description(self):
 
2226
        """See RepositoryFormat.get_format_description()."""
 
2227
        return ("Development repository format, currently the same as "
 
2228
            "pack-0.92-subtree\n")
 
2229
 
 
2230
 
 
2231
class RepositoryFormatPackDevelopment1(RepositoryFormatPackDevelopment0):
 
2232
    """A no-subtrees development repository.
 
2233
 
 
2234
    This format should be retained until the second release after bzr 1.5.
 
2235
 
 
2236
    Supports external lookups, which results in non-truncated ghosts after
 
2237
    reconcile compared to pack-0.92 formats.
 
2238
    """
 
2239
 
 
2240
    supports_external_lookups = True
 
2241
 
 
2242
    def _get_matching_bzrdir(self):
 
2243
        return bzrdir.format_registry.make_bzrdir('development1')
 
2244
 
 
2245
    def _ignore_setting_bzrdir(self, format):
 
2246
        pass
 
2247
 
 
2248
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2249
 
 
2250
    def get_format_string(self):
 
2251
        """See RepositoryFormat.get_format_string()."""
 
2252
        return "Bazaar development format 1 (needs bzr.dev from before 1.6)\n"
 
2253
 
 
2254
    def get_format_description(self):
 
2255
        """See RepositoryFormat.get_format_description()."""
 
2256
        return ("Development repository format, currently the same as "
 
2257
            "pack-0.92 with external reference support.\n")
 
2258
 
 
2259
    def check_conversion_target(self, target_format):
 
2260
        pass
 
2261
 
 
2262
 
 
2263
class RepositoryFormatPackDevelopment1Subtree(RepositoryFormatPackDevelopment0Subtree):
 
2264
    """A subtrees development repository.
 
2265
 
 
2266
    This format should be retained until the second release after bzr 1.5.
 
2267
 
 
2268
    Supports external lookups, which results in non-truncated ghosts after
 
2269
    reconcile compared to pack-0.92 formats.
 
2270
    """
 
2271
 
 
2272
    supports_external_lookups = True
 
2273
 
 
2274
    def _get_matching_bzrdir(self):
 
2275
        return bzrdir.format_registry.make_bzrdir(
 
2276
            'development1-subtree')
 
2277
 
 
2278
    def _ignore_setting_bzrdir(self, format):
 
2279
        pass
 
2280
 
 
2281
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2282
 
 
2283
    def check_conversion_target(self, target_format):
 
2284
        if not target_format.rich_root_data:
 
2285
            raise errors.BadConversionTarget(
 
2286
                'Does not support rich root data.', target_format)
 
2287
        if not getattr(target_format, 'supports_tree_reference', False):
 
2288
            raise errors.BadConversionTarget(
 
2289
                'Does not support nested trees', target_format)
 
2290
            
 
2291
    def get_format_string(self):
 
2292
        """See RepositoryFormat.get_format_string()."""
 
2293
        return ("Bazaar development format 1 with subtree support "
 
2294
            "(needs bzr.dev from before 1.6)\n")
 
2295
 
 
2296
    def get_format_description(self):
 
2297
        """See RepositoryFormat.get_format_description()."""
 
2298
        return ("Development repository format, currently the same as "
 
2299
            "pack-0.92-subtree with external reference support.\n")