~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Aaron Bentley
  • Date: 2007-02-06 14:52:16 UTC
  • mfrom: (2266 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2268.
  • Revision ID: abentley@panoramicfeedback.com-20070206145216-fcpi8o3ufvuzwbp9
Merge bzr.dev

Show diffs side-by-side

added added

removed removed

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