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