/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: John Arbash Meinel
  • Date: 2008-10-02 16:56:01 UTC
  • mto: This revision was merged to the branch mainline in revision 3763.
  • Revision ID: john@arbash-meinel.com-20081002165601-gx13duszt9c425ec
Merge returns code 1 to indicate there were conflicts.

I didn't notice because I had an older qbzr installed which suppressed
all returncodes.

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