/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

Fix python2.6 deprecation warnings related to hashlib.

* bzrlib/osutils.py: 
Wrap md5 and sha imports to be compatible with python 2.4, 2.5 and
above.  Replace all sha.new() calls by sha() calls they are
reputedly faster (not profiled).

* bzrlib/weave.py: 
Update sha import, fix use.     

* bzrlib/transport/http/_urllib2_wrappers.py: 
Update md5 and sha imports, fix use.    

* bzrlib/tests/test_testament.py:
Update sha import, fix use.     

* bzrlib/tests/test_knit.py:
Update sha import, fix use.     

* bzrlib/tests/test_hashcache.py: 
Update sha import, fix use.     

* bzrlib/tests/per_repository/test_check_reconcile.py:
Update sha import, fix use.     

* bzrlib/tests/http_utils.py: 
Update md5 and sha imports, fix use.    

* bzrlib/testament.py: 
Update sha import, fix use.     

* bzrlib/repofmt/pack_repo.py: 
Update md5 import, fix use.     

* bzrlib/hashcache.py: 
Update sha import, fix use.     

* bzrlib/btree_index.py: 
Delete useless sha import.

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