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
"""Knit versionedfile implementation.
19
A knit is a versioned file implementation that supports efficient append only
23
lifeless: the data file is made up of "delta records". each delta record has a delta header
24
that contains; (1) a version id, (2) the size of the delta (in lines), and (3) the digest of
25
the -expanded data- (ie, the delta applied to the parent). the delta also ends with a
26
end-marker; simply "end VERSION"
28
delta can be line or full contents.a
29
... the 8's there are the index number of the annotation.
30
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
34
8 e.set('executable', 'yes')
36
8 if elt.get('executable') == 'yes':
37
8 ie.executable = True
38
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad
42
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
43
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
44
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
45
09:33 < lifeless> right
46
09:33 < jrydberg> lifeless: the position and size is the range in the data file
49
so the index sequence is the dictionary compressed sequence number used
50
in the deltas to provide line annotation
55
from cStringIO import StringIO
56
from itertools import izip, chain
61
from bzrlib.lazy_import import lazy_import
62
lazy_import(globals(), """
82
from bzrlib.errors import (
90
RevisionAlreadyPresent,
93
from bzrlib.osutils import (
100
from bzrlib.versionedfile import (
101
AbsentContentFactory,
105
ChunkedContentFactory,
111
# TODO: Split out code specific to this format into an associated object.
113
# TODO: Can we put in some kind of value to check that the index and data
114
# files belong together?
116
# TODO: accommodate binaries, perhaps by storing a byte count
118
# TODO: function to check whole file
120
# TODO: atomically append data, then measure backwards from the cursor
121
# position after writing to work out where it was located. we may need to
122
# bypass python file buffering.
124
DATA_SUFFIX = '.knit'
125
INDEX_SUFFIX = '.kndx'
128
class KnitAdapter(object):
129
"""Base class for knit record adaption."""
131
def __init__(self, basis_vf):
132
"""Create an adapter which accesses full texts from basis_vf.
134
:param basis_vf: A versioned file to access basis texts of deltas from.
135
May be None for adapters that do not need to access basis texts.
137
self._data = KnitVersionedFiles(None, None)
138
self._annotate_factory = KnitAnnotateFactory()
139
self._plain_factory = KnitPlainFactory()
140
self._basis_vf = basis_vf
143
class FTAnnotatedToUnannotated(KnitAdapter):
144
"""An adapter from FT annotated knits to unannotated ones."""
146
def get_bytes(self, factory):
147
annotated_compressed_bytes = factory._raw_record
149
self._data._parse_record_unchecked(annotated_compressed_bytes)
150
content = self._annotate_factory.parse_fulltext(contents, rec[1])
151
size, bytes = self._data._record_to_data((rec[1],), rec[3], content.text())
155
class DeltaAnnotatedToUnannotated(KnitAdapter):
156
"""An adapter for deltas from annotated to unannotated."""
158
def get_bytes(self, factory):
159
annotated_compressed_bytes = factory._raw_record
161
self._data._parse_record_unchecked(annotated_compressed_bytes)
162
delta = self._annotate_factory.parse_line_delta(contents, rec[1],
164
contents = self._plain_factory.lower_line_delta(delta)
165
size, bytes = self._data._record_to_data((rec[1],), rec[3], contents)
169
class FTAnnotatedToFullText(KnitAdapter):
170
"""An adapter from FT annotated knits to unannotated ones."""
172
def get_bytes(self, factory):
173
annotated_compressed_bytes = factory._raw_record
175
self._data._parse_record_unchecked(annotated_compressed_bytes)
176
content, delta = self._annotate_factory.parse_record(factory.key[-1],
177
contents, factory._build_details, None)
178
return ''.join(content.text())
181
class DeltaAnnotatedToFullText(KnitAdapter):
182
"""An adapter for deltas from annotated to unannotated."""
184
def get_bytes(self, factory):
185
annotated_compressed_bytes = factory._raw_record
187
self._data._parse_record_unchecked(annotated_compressed_bytes)
188
delta = self._annotate_factory.parse_line_delta(contents, rec[1],
190
compression_parent = factory.parents[0]
191
basis_entry = self._basis_vf.get_record_stream(
192
[compression_parent], 'unordered', True).next()
193
if basis_entry.storage_kind == 'absent':
194
raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
195
basis_chunks = basis_entry.get_bytes_as('chunked')
196
basis_lines = osutils.chunks_to_lines(basis_chunks)
197
# Manually apply the delta because we have one annotated content and
199
basis_content = PlainKnitContent(basis_lines, compression_parent)
200
basis_content.apply_delta(delta, rec[1])
201
basis_content._should_strip_eol = factory._build_details[1]
202
return ''.join(basis_content.text())
205
class FTPlainToFullText(KnitAdapter):
206
"""An adapter from FT plain knits to unannotated ones."""
208
def get_bytes(self, factory):
209
compressed_bytes = factory._raw_record
211
self._data._parse_record_unchecked(compressed_bytes)
212
content, delta = self._plain_factory.parse_record(factory.key[-1],
213
contents, factory._build_details, None)
214
return ''.join(content.text())
217
class DeltaPlainToFullText(KnitAdapter):
218
"""An adapter for deltas from annotated to unannotated."""
220
def get_bytes(self, factory):
221
compressed_bytes = factory._raw_record
223
self._data._parse_record_unchecked(compressed_bytes)
224
delta = self._plain_factory.parse_line_delta(contents, rec[1])
225
compression_parent = factory.parents[0]
226
# XXX: string splitting overhead.
227
basis_entry = self._basis_vf.get_record_stream(
228
[compression_parent], 'unordered', True).next()
229
if basis_entry.storage_kind == 'absent':
230
raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
231
basis_chunks = basis_entry.get_bytes_as('chunked')
232
basis_lines = osutils.chunks_to_lines(basis_chunks)
233
basis_content = PlainKnitContent(basis_lines, compression_parent)
234
# Manually apply the delta because we have one annotated content and
236
content, _ = self._plain_factory.parse_record(rec[1], contents,
237
factory._build_details, basis_content)
238
return ''.join(content.text())
241
class KnitContentFactory(ContentFactory):
242
"""Content factory for streaming from knits.
244
:seealso ContentFactory:
247
def __init__(self, key, parents, build_details, sha1, raw_record,
248
annotated, knit=None, network_bytes=None):
249
"""Create a KnitContentFactory for key.
252
:param parents: The parents.
253
:param build_details: The build details as returned from
255
:param sha1: The sha1 expected from the full text of this object.
256
:param raw_record: The bytes of the knit data from disk.
257
:param annotated: True if the raw data is annotated.
258
:param network_bytes: None to calculate the network bytes on demand,
259
not-none if they are already known.
261
ContentFactory.__init__(self)
264
self.parents = parents
265
if build_details[0] == 'line-delta':
270
annotated_kind = 'annotated-'
273
self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
274
self._raw_record = raw_record
275
self._network_bytes = network_bytes
276
self._build_details = build_details
279
def _create_network_bytes(self):
280
"""Create a fully serialised network version for transmission."""
281
# storage_kind, key, parents, Noeol, raw_record
282
key_bytes = '\x00'.join(self.key)
283
if self.parents is None:
284
parent_bytes = 'None:'
286
parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
287
if self._build_details[1]:
291
network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
292
parent_bytes, noeol, self._raw_record)
293
self._network_bytes = network_bytes
295
def get_bytes_as(self, storage_kind):
296
if storage_kind == self.storage_kind:
297
if self._network_bytes is None:
298
self._create_network_bytes()
299
return self._network_bytes
300
if self._knit is not None:
301
if storage_kind == 'chunked':
302
return self._knit.get_lines(self.key[0])
303
elif storage_kind == 'fulltext':
304
return self._knit.get_text(self.key[0])
305
raise errors.UnavailableRepresentation(self.key, storage_kind,
309
class LazyKnitContentFactory(ContentFactory):
310
"""A ContentFactory which can either generate full text or a wire form.
312
:seealso ContentFactory:
315
def __init__(self, key, parents, generator, first):
316
"""Create a LazyKnitContentFactory.
318
:param key: The key of the record.
319
:param parents: The parents of the record.
320
:param generator: A _ContentMapGenerator containing the record for this
322
:param first: Is this the first content object returned from generator?
323
if it is, its storage kind is knit-delta-closure, otherwise it is
324
knit-delta-closure-ref
327
self.parents = parents
329
self._generator = generator
330
self.storage_kind = "knit-delta-closure"
332
self.storage_kind = self.storage_kind + "-ref"
335
def get_bytes_as(self, storage_kind):
336
if storage_kind == self.storage_kind:
338
return self._generator._wire_bytes()
340
# all the keys etc are contained in the bytes returned in the
343
if storage_kind in ('chunked', 'fulltext'):
344
chunks = self._generator._get_one_work(self.key).text()
345
if storage_kind == 'chunked':
348
return ''.join(chunks)
349
raise errors.UnavailableRepresentation(self.key, storage_kind,
353
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
354
"""Convert a network record to a iterator over stream records.
356
:param storage_kind: The storage kind of the record.
357
Must be 'knit-delta-closure'.
358
:param bytes: The bytes of the record on the network.
360
generator = _NetworkContentMapGenerator(bytes, line_end)
361
return generator.get_record_stream()
364
def knit_network_to_record(storage_kind, bytes, line_end):
365
"""Convert a network record to a record object.
367
:param storage_kind: The storage kind of the record.
368
:param bytes: The bytes of the record on the network.
371
line_end = bytes.find('\n', start)
372
key = tuple(bytes[start:line_end].split('\x00'))
374
line_end = bytes.find('\n', start)
375
parent_line = bytes[start:line_end]
376
if parent_line == 'None:':
380
[tuple(segment.split('\x00')) for segment in parent_line.split('\t')
383
noeol = bytes[start] == 'N'
384
if 'ft' in storage_kind:
387
method = 'line-delta'
388
build_details = (method, noeol)
390
raw_record = bytes[start:]
391
annotated = 'annotated' in storage_kind
392
return [KnitContentFactory(key, parents, build_details, None, raw_record,
393
annotated, network_bytes=bytes)]
396
class KnitContent(object):
397
"""Content of a knit version to which deltas can be applied.
399
This is always stored in memory as a list of lines with \n at the end,
400
plus a flag saying if the final ending is really there or not, because that
401
corresponds to the on-disk knit representation.
405
self._should_strip_eol = False
407
def apply_delta(self, delta, new_version_id):
408
"""Apply delta to this object to become new_version_id."""
409
raise NotImplementedError(self.apply_delta)
411
def line_delta_iter(self, new_lines):
412
"""Generate line-based delta from this content to new_lines."""
413
new_texts = new_lines.text()
414
old_texts = self.text()
415
s = patiencediff.PatienceSequenceMatcher(None, old_texts, new_texts)
416
for tag, i1, i2, j1, j2 in s.get_opcodes():
419
# ofrom, oto, length, data
420
yield i1, i2, j2 - j1, new_lines._lines[j1:j2]
422
def line_delta(self, new_lines):
423
return list(self.line_delta_iter(new_lines))
426
def get_line_delta_blocks(knit_delta, source, target):
427
"""Extract SequenceMatcher.get_matching_blocks() from a knit delta"""
428
target_len = len(target)
431
for s_begin, s_end, t_len, new_text in knit_delta:
432
true_n = s_begin - s_pos
435
# knit deltas do not provide reliable info about whether the
436
# last line of a file matches, due to eol handling.
437
if source[s_pos + n -1] != target[t_pos + n -1]:
440
yield s_pos, t_pos, n
441
t_pos += t_len + true_n
443
n = target_len - t_pos
445
if source[s_pos + n -1] != target[t_pos + n -1]:
448
yield s_pos, t_pos, n
449
yield s_pos + (target_len - t_pos), target_len, 0
452
class AnnotatedKnitContent(KnitContent):
453
"""Annotated content."""
455
def __init__(self, lines):
456
KnitContent.__init__(self)
460
"""Return a list of (origin, text) for each content line."""
461
lines = self._lines[:]
462
if self._should_strip_eol:
463
origin, last_line = lines[-1]
464
lines[-1] = (origin, last_line.rstrip('\n'))
467
def apply_delta(self, delta, new_version_id):
468
"""Apply delta to this object to become new_version_id."""
471
for start, end, count, delta_lines in delta:
472
lines[offset+start:offset+end] = delta_lines
473
offset = offset + (start - end) + count
477
lines = [text for origin, text in self._lines]
478
except ValueError, e:
479
# most commonly (only?) caused by the internal form of the knit
480
# missing annotation information because of a bug - see thread
482
raise KnitCorrupt(self,
483
"line in annotated knit missing annotation information: %s"
485
if self._should_strip_eol:
486
lines[-1] = lines[-1].rstrip('\n')
490
return AnnotatedKnitContent(self._lines[:])
493
class PlainKnitContent(KnitContent):
494
"""Unannotated content.
496
When annotate[_iter] is called on this content, the same version is reported
497
for all lines. Generally, annotate[_iter] is not useful on PlainKnitContent
501
def __init__(self, lines, version_id):
502
KnitContent.__init__(self)
504
self._version_id = version_id
507
"""Return a list of (origin, text) for each content line."""
508
return [(self._version_id, line) for line in self._lines]
510
def apply_delta(self, delta, new_version_id):
511
"""Apply delta to this object to become new_version_id."""
514
for start, end, count, delta_lines in delta:
515
lines[offset+start:offset+end] = delta_lines
516
offset = offset + (start - end) + count
517
self._version_id = new_version_id
520
return PlainKnitContent(self._lines[:], self._version_id)
524
if self._should_strip_eol:
526
lines[-1] = lines[-1].rstrip('\n')
530
class _KnitFactory(object):
531
"""Base class for common Factory functions."""
533
def parse_record(self, version_id, record, record_details,
534
base_content, copy_base_content=True):
535
"""Parse a record into a full content object.
537
:param version_id: The official version id for this content
538
:param record: The data returned by read_records_iter()
539
:param record_details: Details about the record returned by
541
:param base_content: If get_build_details returns a compression_parent,
542
you must return a base_content here, else use None
543
:param copy_base_content: When building from the base_content, decide
544
you can either copy it and return a new object, or modify it in
546
:return: (content, delta) A Content object and possibly a line-delta,
549
method, noeol = record_details
550
if method == 'line-delta':
551
if copy_base_content:
552
content = base_content.copy()
554
content = base_content
555
delta = self.parse_line_delta(record, version_id)
556
content.apply_delta(delta, version_id)
558
content = self.parse_fulltext(record, version_id)
560
content._should_strip_eol = noeol
561
return (content, delta)
564
class KnitAnnotateFactory(_KnitFactory):
565
"""Factory for creating annotated Content objects."""
569
def make(self, lines, version_id):
570
num_lines = len(lines)
571
return AnnotatedKnitContent(zip([version_id] * num_lines, lines))
573
def parse_fulltext(self, content, version_id):
574
"""Convert fulltext to internal representation
576
fulltext content is of the format
577
revid(utf8) plaintext\n
578
internal representation is of the format:
581
# TODO: jam 20070209 The tests expect this to be returned as tuples,
582
# but the code itself doesn't really depend on that.
583
# Figure out a way to not require the overhead of turning the
584
# list back into tuples.
585
lines = [tuple(line.split(' ', 1)) for line in content]
586
return AnnotatedKnitContent(lines)
588
def parse_line_delta_iter(self, lines):
589
return iter(self.parse_line_delta(lines))
591
def parse_line_delta(self, lines, version_id, plain=False):
592
"""Convert a line based delta into internal representation.
594
line delta is in the form of:
595
intstart intend intcount
597
revid(utf8) newline\n
598
internal representation is
599
(start, end, count, [1..count tuples (revid, newline)])
601
:param plain: If True, the lines are returned as a plain
602
list without annotations, not as a list of (origin, content) tuples, i.e.
603
(start, end, count, [1..count newline])
610
def cache_and_return(line):
611
origin, text = line.split(' ', 1)
612
return cache.setdefault(origin, origin), text
614
# walk through the lines parsing.
615
# Note that the plain test is explicitly pulled out of the
616
# loop to minimise any performance impact
619
start, end, count = [int(n) for n in header.split(',')]
620
contents = [next().split(' ', 1)[1] for i in xrange(count)]
621
result.append((start, end, count, contents))
624
start, end, count = [int(n) for n in header.split(',')]
625
contents = [tuple(next().split(' ', 1)) for i in xrange(count)]
626
result.append((start, end, count, contents))
629
def get_fulltext_content(self, lines):
630
"""Extract just the content lines from a fulltext."""
631
return (line.split(' ', 1)[1] for line in lines)
633
def get_linedelta_content(self, lines):
634
"""Extract just the content from a line delta.
636
This doesn't return all of the extra information stored in a delta.
637
Only the actual content lines.
642
header = header.split(',')
643
count = int(header[2])
644
for i in xrange(count):
645
origin, text = next().split(' ', 1)
648
def lower_fulltext(self, content):
649
"""convert a fulltext content record into a serializable form.
651
see parse_fulltext which this inverts.
653
# TODO: jam 20070209 We only do the caching thing to make sure that
654
# the origin is a valid utf-8 line, eventually we could remove it
655
return ['%s %s' % (o, t) for o, t in content._lines]
657
def lower_line_delta(self, delta):
658
"""convert a delta into a serializable form.
660
See parse_line_delta which this inverts.
662
# TODO: jam 20070209 We only do the caching thing to make sure that
663
# the origin is a valid utf-8 line, eventually we could remove it
665
for start, end, c, lines in delta:
666
out.append('%d,%d,%d\n' % (start, end, c))
667
out.extend(origin + ' ' + text
668
for origin, text in lines)
671
def annotate(self, knit, key):
672
content = knit._get_content(key)
673
# adjust for the fact that serialised annotations are only key suffixes
675
if type(key) == tuple:
677
origins = content.annotate()
679
for origin, line in origins:
680
result.append((prefix + (origin,), line))
683
# XXX: This smells a bit. Why would key ever be a non-tuple here?
684
# Aren't keys defined to be tuples? -- spiv 20080618
685
return content.annotate()
688
class KnitPlainFactory(_KnitFactory):
689
"""Factory for creating plain Content objects."""
693
def make(self, lines, version_id):
694
return PlainKnitContent(lines, version_id)
696
def parse_fulltext(self, content, version_id):
697
"""This parses an unannotated fulltext.
699
Note that this is not a noop - the internal representation
700
has (versionid, line) - its just a constant versionid.
702
return self.make(content, version_id)
704
def parse_line_delta_iter(self, lines, version_id):
706
num_lines = len(lines)
707
while cur < num_lines:
710
start, end, c = [int(n) for n in header.split(',')]
711
yield start, end, c, lines[cur:cur+c]
714
def parse_line_delta(self, lines, version_id):
715
return list(self.parse_line_delta_iter(lines, version_id))
717
def get_fulltext_content(self, lines):
718
"""Extract just the content lines from a fulltext."""
721
def get_linedelta_content(self, lines):
722
"""Extract just the content from a line delta.
724
This doesn't return all of the extra information stored in a delta.
725
Only the actual content lines.
730
header = header.split(',')
731
count = int(header[2])
732
for i in xrange(count):
735
def lower_fulltext(self, content):
736
return content.text()
738
def lower_line_delta(self, delta):
740
for start, end, c, lines in delta:
741
out.append('%d,%d,%d\n' % (start, end, c))
745
def annotate(self, knit, key):
746
annotator = _KnitAnnotator(knit)
747
return annotator.annotate(key)
751
def make_file_factory(annotated, mapper):
752
"""Create a factory for creating a file based KnitVersionedFiles.
754
This is only functional enough to run interface tests, it doesn't try to
755
provide a full pack environment.
757
:param annotated: knit annotations are wanted.
758
:param mapper: The mapper from keys to paths.
760
def factory(transport):
761
index = _KndxIndex(transport, mapper, lambda:None, lambda:True, lambda:True)
762
access = _KnitKeyAccess(transport, mapper)
763
return KnitVersionedFiles(index, access, annotated=annotated)
767
def make_pack_factory(graph, delta, keylength):
768
"""Create a factory for creating a pack based VersionedFiles.
770
This is only functional enough to run interface tests, it doesn't try to
771
provide a full pack environment.
773
:param graph: Store a graph.
774
:param delta: Delta compress contents.
775
:param keylength: How long should keys be.
777
def factory(transport):
778
parents = graph or delta
784
max_delta_chain = 200
787
graph_index = _mod_index.InMemoryGraphIndex(reference_lists=ref_length,
788
key_elements=keylength)
789
stream = transport.open_write_stream('newpack')
790
writer = pack.ContainerWriter(stream.write)
792
index = _KnitGraphIndex(graph_index, lambda:True, parents=parents,
793
deltas=delta, add_callback=graph_index.add_nodes)
794
access = _DirectPackAccess({})
795
access.set_writer(writer, graph_index, (transport, 'newpack'))
796
result = KnitVersionedFiles(index, access,
797
max_delta_chain=max_delta_chain)
798
result.stream = stream
799
result.writer = writer
804
def cleanup_pack_knit(versioned_files):
805
versioned_files.stream.close()
806
versioned_files.writer.end()
809
class KnitVersionedFiles(VersionedFiles):
810
"""Storage for many versioned files using knit compression.
812
Backend storage is managed by indices and data objects.
814
:ivar _index: A _KnitGraphIndex or similar that can describe the
815
parents, graph, compression and data location of entries in this
816
KnitVersionedFiles. Note that this is only the index for
817
*this* vfs; if there are fallbacks they must be queried separately.
820
def __init__(self, index, data_access, max_delta_chain=200,
821
annotated=False, reload_func=None):
822
"""Create a KnitVersionedFiles with index and data_access.
824
:param index: The index for the knit data.
825
:param data_access: The access object to store and retrieve knit
827
:param max_delta_chain: The maximum number of deltas to permit during
828
insertion. Set to 0 to prohibit the use of deltas.
829
:param annotated: Set to True to cause annotations to be calculated and
830
stored during insertion.
831
:param reload_func: An function that can be called if we think we need
832
to reload the pack listing and try again. See
833
'bzrlib.repofmt.pack_repo.AggregateIndex' for the signature.
836
self._access = data_access
837
self._max_delta_chain = max_delta_chain
839
self._factory = KnitAnnotateFactory()
841
self._factory = KnitPlainFactory()
842
self._fallback_vfs = []
843
self._reload_func = reload_func
846
return "%s(%r, %r)" % (
847
self.__class__.__name__,
851
def add_fallback_versioned_files(self, a_versioned_files):
852
"""Add a source of texts for texts not present in this knit.
854
:param a_versioned_files: A VersionedFiles object.
856
self._fallback_vfs.append(a_versioned_files)
858
def add_lines(self, key, parents, lines, parent_texts=None,
859
left_matching_blocks=None, nostore_sha=None, random_id=False,
861
"""See VersionedFiles.add_lines()."""
862
self._index._check_write_ok()
863
self._check_add(key, lines, random_id, check_content)
865
# The caller might pass None if there is no graph data, but kndx
866
# indexes can't directly store that, so we give them
867
# an empty tuple instead.
869
return self._add(key, lines, parents,
870
parent_texts, left_matching_blocks, nostore_sha, random_id)
872
def _add(self, key, lines, parents, parent_texts,
873
left_matching_blocks, nostore_sha, random_id):
874
"""Add a set of lines on top of version specified by parents.
876
Any versions not present will be converted into ghosts.
878
# first thing, if the content is something we don't need to store, find
880
line_bytes = ''.join(lines)
881
digest = sha_string(line_bytes)
882
if nostore_sha == digest:
883
raise errors.ExistingContent
886
if parent_texts is None:
888
# Do a single query to ascertain parent presence; we only compress
889
# against parents in the same kvf.
890
present_parent_map = self._index.get_parent_map(parents)
891
for parent in parents:
892
if parent in present_parent_map:
893
present_parents.append(parent)
895
# Currently we can only compress against the left most present parent.
896
if (len(present_parents) == 0 or
897
present_parents[0] != parents[0]):
900
# To speed the extract of texts the delta chain is limited
901
# to a fixed number of deltas. This should minimize both
902
# I/O and the time spend applying deltas.
903
delta = self._check_should_delta(present_parents[0])
905
text_length = len(line_bytes)
908
if lines[-1][-1] != '\n':
909
# copy the contents of lines.
911
options.append('no-eol')
912
lines[-1] = lines[-1] + '\n'
916
if type(element) != str:
917
raise TypeError("key contains non-strings: %r" % (key,))
918
# Knit hunks are still last-element only
920
content = self._factory.make(lines, version_id)
921
if 'no-eol' in options:
922
# Hint to the content object that its text() call should strip the
924
content._should_strip_eol = True
925
if delta or (self._factory.annotated and len(present_parents) > 0):
926
# Merge annotations from parent texts if needed.
927
delta_hunks = self._merge_annotations(content, present_parents,
928
parent_texts, delta, self._factory.annotated,
929
left_matching_blocks)
932
options.append('line-delta')
933
store_lines = self._factory.lower_line_delta(delta_hunks)
934
size, bytes = self._record_to_data(key, digest,
937
options.append('fulltext')
938
# isinstance is slower and we have no hierarchy.
939
if self._factory.__class__ == KnitPlainFactory:
940
# Use the already joined bytes saving iteration time in
942
size, bytes = self._record_to_data(key, digest,
945
# get mixed annotation + content and feed it into the
947
store_lines = self._factory.lower_fulltext(content)
948
size, bytes = self._record_to_data(key, digest,
951
access_memo = self._access.add_raw_records([(key, size)], bytes)[0]
952
self._index.add_records(
953
((key, options, access_memo, parents),),
955
return digest, text_length, content
957
def annotate(self, key):
958
"""See VersionedFiles.annotate."""
959
return self._factory.annotate(self, key)
961
def check(self, progress_bar=None):
962
"""See VersionedFiles.check()."""
963
# This doesn't actually test extraction of everything, but that will
964
# impact 'bzr check' substantially, and needs to be integrated with
965
# care. However, it does check for the obvious problem of a delta with
967
keys = self._index.keys()
968
parent_map = self.get_parent_map(keys)
970
if self._index.get_method(key) != 'fulltext':
971
compression_parent = parent_map[key][0]
972
if compression_parent not in parent_map:
973
raise errors.KnitCorrupt(self,
974
"Missing basis parent %s for %s" % (
975
compression_parent, key))
976
for fallback_vfs in self._fallback_vfs:
979
def _check_add(self, key, lines, random_id, check_content):
980
"""check that version_id and lines are safe to add."""
982
if contains_whitespace(version_id):
983
raise InvalidRevisionId(version_id, self)
984
self.check_not_reserved_id(version_id)
985
# TODO: If random_id==False and the key is already present, we should
986
# probably check that the existing content is identical to what is
987
# being inserted, and otherwise raise an exception. This would make
988
# the bundle code simpler.
990
self._check_lines_not_unicode(lines)
991
self._check_lines_are_lines(lines)
993
def _check_header(self, key, line):
994
rec = self._split_header(line)
995
self._check_header_version(rec, key[-1])
998
def _check_header_version(self, rec, version_id):
999
"""Checks the header version on original format knit records.
1001
These have the last component of the key embedded in the record.
1003
if rec[1] != version_id:
1004
raise KnitCorrupt(self,
1005
'unexpected version, wanted %r, got %r' % (version_id, rec[1]))
1007
def _check_should_delta(self, parent):
1008
"""Iterate back through the parent listing, looking for a fulltext.
1010
This is used when we want to decide whether to add a delta or a new
1011
fulltext. It searches for _max_delta_chain parents. When it finds a
1012
fulltext parent, it sees if the total size of the deltas leading up to
1013
it is large enough to indicate that we want a new full text anyway.
1015
Return True if we should create a new delta, False if we should use a
1019
fulltext_size = None
1020
for count in xrange(self._max_delta_chain):
1022
# Note that this only looks in the index of this particular
1023
# KnitVersionedFiles, not in the fallbacks. This ensures that
1024
# we won't store a delta spanning physical repository
1026
build_details = self._index.get_build_details([parent])
1027
parent_details = build_details[parent]
1028
except (RevisionNotPresent, KeyError), e:
1029
# Some basis is not locally present: always fulltext
1031
index_memo, compression_parent, _, _ = parent_details
1032
_, _, size = index_memo
1033
if compression_parent is None:
1034
fulltext_size = size
1037
# We don't explicitly check for presence because this is in an
1038
# inner loop, and if it's missing it'll fail anyhow.
1039
parent = compression_parent
1041
# We couldn't find a fulltext, so we must create a new one
1043
# Simple heuristic - if the total I/O wold be greater as a delta than
1044
# the originally installed fulltext, we create a new fulltext.
1045
return fulltext_size > delta_size
1047
def _build_details_to_components(self, build_details):
1048
"""Convert a build_details tuple to a position tuple."""
1049
# record_details, access_memo, compression_parent
1050
return build_details[3], build_details[0], build_details[1]
1052
def _get_components_positions(self, keys, allow_missing=False):
1053
"""Produce a map of position data for the components of keys.
1055
This data is intended to be used for retrieving the knit records.
1057
A dict of key to (record_details, index_memo, next, parents) is
1059
method is the way referenced data should be applied.
1060
index_memo is the handle to pass to the data access to actually get the
1062
next is the build-parent of the version, or None for fulltexts.
1063
parents is the version_ids of the parents of this version
1065
:param allow_missing: If True do not raise an error on a missing component,
1069
pending_components = keys
1070
while pending_components:
1071
build_details = self._index.get_build_details(pending_components)
1072
current_components = set(pending_components)
1073
pending_components = set()
1074
for key, details in build_details.iteritems():
1075
(index_memo, compression_parent, parents,
1076
record_details) = details
1077
method = record_details[0]
1078
if compression_parent is not None:
1079
pending_components.add(compression_parent)
1080
component_data[key] = self._build_details_to_components(details)
1081
missing = current_components.difference(build_details)
1082
if missing and not allow_missing:
1083
raise errors.RevisionNotPresent(missing.pop(), self)
1084
return component_data
1086
def _get_content(self, key, parent_texts={}):
1087
"""Returns a content object that makes up the specified
1089
cached_version = parent_texts.get(key, None)
1090
if cached_version is not None:
1091
# Ensure the cache dict is valid.
1092
if not self.get_parent_map([key]):
1093
raise RevisionNotPresent(key, self)
1094
return cached_version
1095
generator = _VFContentMapGenerator(self, [key])
1096
return generator._get_content(key)
1098
def get_parent_map(self, keys):
1099
"""Get a map of the graph parents of keys.
1101
:param keys: The keys to look up parents for.
1102
:return: A mapping from keys to parents. Absent keys are absent from
1105
return self._get_parent_map_with_sources(keys)[0]
1107
def _get_parent_map_with_sources(self, keys):
1108
"""Get a map of the parents of keys.
1110
:param keys: The keys to look up parents for.
1111
:return: A tuple. The first element is a mapping from keys to parents.
1112
Absent keys are absent from the mapping. The second element is a
1113
list with the locations each key was found in. The first element
1114
is the in-this-knit parents, the second the first fallback source,
1118
sources = [self._index] + self._fallback_vfs
1121
for source in sources:
1124
new_result = source.get_parent_map(missing)
1125
source_results.append(new_result)
1126
result.update(new_result)
1127
missing.difference_update(set(new_result))
1128
return result, source_results
1130
def _get_record_map(self, keys, allow_missing=False):
1131
"""Produce a dictionary of knit records.
1133
:return: {key:(record, record_details, digest, next)}
1135
data returned from read_records (a KnitContentobject)
1137
opaque information to pass to parse_record
1139
SHA1 digest of the full text after all steps are done
1141
build-parent of the version, i.e. the leftmost ancestor.
1142
Will be None if the record is not a delta.
1143
:param keys: The keys to build a map for
1144
:param allow_missing: If some records are missing, rather than
1145
error, just return the data that could be generated.
1147
raw_map = self._get_record_map_unparsed(keys,
1148
allow_missing=allow_missing)
1149
return self._raw_map_to_record_map(raw_map)
1151
def _raw_map_to_record_map(self, raw_map):
1152
"""Parse the contents of _get_record_map_unparsed.
1154
:return: see _get_record_map.
1158
data, record_details, next = raw_map[key]
1159
content, digest = self._parse_record(key[-1], data)
1160
result[key] = content, record_details, digest, next
1163
def _get_record_map_unparsed(self, keys, allow_missing=False):
1164
"""Get the raw data for reconstructing keys without parsing it.
1166
:return: A dict suitable for parsing via _raw_map_to_record_map.
1167
key-> raw_bytes, (method, noeol), compression_parent
1169
# This retries the whole request if anything fails. Potentially we
1170
# could be a bit more selective. We could track the keys whose records
1171
# we have successfully found, and then only request the new records
1172
# from there. However, _get_components_positions grabs the whole build
1173
# chain, which means we'll likely try to grab the same records again
1174
# anyway. Also, can the build chains change as part of a pack
1175
# operation? We wouldn't want to end up with a broken chain.
1178
position_map = self._get_components_positions(keys,
1179
allow_missing=allow_missing)
1180
# key = component_id, r = record_details, i_m = index_memo,
1182
records = [(key, i_m) for key, (r, i_m, n)
1183
in position_map.iteritems()]
1185
for key, data in self._read_records_iter_unchecked(records):
1186
(record_details, index_memo, next) = position_map[key]
1187
raw_record_map[key] = data, record_details, next
1188
return raw_record_map
1189
except errors.RetryWithNewPacks, e:
1190
self._access.reload_or_raise(e)
1192
def _split_by_prefix(self, keys):
1193
"""For the given keys, split them up based on their prefix.
1195
To keep memory pressure somewhat under control, split the
1196
requests back into per-file-id requests, otherwise "bzr co"
1197
extracts the full tree into memory before writing it to disk.
1198
This should be revisited if _get_content_maps() can ever cross
1201
:param keys: An iterable of key tuples
1202
:return: A dict of {prefix: [key_list]}
1204
split_by_prefix = {}
1207
split_by_prefix.setdefault('', []).append(key)
1209
split_by_prefix.setdefault(key[0], []).append(key)
1210
return split_by_prefix
1212
def get_record_stream(self, keys, ordering, include_delta_closure):
1213
"""Get a stream of records for keys.
1215
:param keys: The keys to include.
1216
:param ordering: Either 'unordered' or 'topological'. A topologically
1217
sorted stream has compression parents strictly before their
1219
:param include_delta_closure: If True then the closure across any
1220
compression parents will be included (in the opaque data).
1221
:return: An iterator of ContentFactory objects, each of which is only
1222
valid until the iterator is advanced.
1224
# keys might be a generator
1228
if not self._index.has_graph:
1229
# Cannot topological order when no graph has been stored.
1230
ordering = 'unordered'
1232
remaining_keys = keys
1235
keys = set(remaining_keys)
1236
for content_factory in self._get_remaining_record_stream(keys,
1237
ordering, include_delta_closure):
1238
remaining_keys.discard(content_factory.key)
1239
yield content_factory
1241
except errors.RetryWithNewPacks, e:
1242
self._access.reload_or_raise(e)
1244
def _get_remaining_record_stream(self, keys, ordering,
1245
include_delta_closure):
1246
"""This function is the 'retry' portion for get_record_stream."""
1247
if include_delta_closure:
1248
positions = self._get_components_positions(keys, allow_missing=True)
1250
build_details = self._index.get_build_details(keys)
1252
# (record_details, access_memo, compression_parent_key)
1253
positions = dict((key, self._build_details_to_components(details))
1254
for key, details in build_details.iteritems())
1255
absent_keys = keys.difference(set(positions))
1256
# There may be more absent keys : if we're missing the basis component
1257
# and are trying to include the delta closure.
1258
# XXX: We should not ever need to examine remote sources because we do
1259
# not permit deltas across versioned files boundaries.
1260
if include_delta_closure:
1261
needed_from_fallback = set()
1262
# Build up reconstructable_keys dict. key:True in this dict means
1263
# the key can be reconstructed.
1264
reconstructable_keys = {}
1268
chain = [key, positions[key][2]]
1270
needed_from_fallback.add(key)
1273
while chain[-1] is not None:
1274
if chain[-1] in reconstructable_keys:
1275
result = reconstructable_keys[chain[-1]]
1279
chain.append(positions[chain[-1]][2])
1281
# missing basis component
1282
needed_from_fallback.add(chain[-1])
1285
for chain_key in chain[:-1]:
1286
reconstructable_keys[chain_key] = result
1288
needed_from_fallback.add(key)
1289
# Double index lookups here : need a unified api ?
1290
global_map, parent_maps = self._get_parent_map_with_sources(keys)
1291
if ordering == 'topological':
1292
# Global topological sort
1293
present_keys = tsort.topo_sort(global_map)
1294
# Now group by source:
1296
current_source = None
1297
for key in present_keys:
1298
for parent_map in parent_maps:
1299
if key in parent_map:
1300
key_source = parent_map
1302
if current_source is not key_source:
1303
source_keys.append((key_source, []))
1304
current_source = key_source
1305
source_keys[-1][1].append(key)
1307
if ordering != 'unordered':
1308
raise AssertionError('valid values for ordering are:'
1309
' "unordered" or "topological" not: %r'
1311
# Just group by source; remote sources first.
1314
for parent_map in reversed(parent_maps):
1315
source_keys.append((parent_map, []))
1316
for key in parent_map:
1317
present_keys.append(key)
1318
source_keys[-1][1].append(key)
1319
# We have been requested to return these records in an order that
1320
# suits us. So we ask the index to give us an optimally sorted
1322
for source, sub_keys in source_keys:
1323
if source is parent_maps[0]:
1324
# Only sort the keys for this VF
1325
self._index._sort_keys_by_io(sub_keys, positions)
1326
absent_keys = keys - set(global_map)
1327
for key in absent_keys:
1328
yield AbsentContentFactory(key)
1329
# restrict our view to the keys we can answer.
1330
# XXX: Memory: TODO: batch data here to cap buffered data at (say) 1MB.
1331
# XXX: At that point we need to consider the impact of double reads by
1332
# utilising components multiple times.
1333
if include_delta_closure:
1334
# XXX: get_content_maps performs its own index queries; allow state
1336
non_local_keys = needed_from_fallback - absent_keys
1337
prefix_split_keys = self._split_by_prefix(present_keys)
1338
prefix_split_non_local_keys = self._split_by_prefix(non_local_keys)
1339
for prefix, keys in prefix_split_keys.iteritems():
1340
non_local = prefix_split_non_local_keys.get(prefix, [])
1341
non_local = set(non_local)
1342
generator = _VFContentMapGenerator(self, keys, non_local,
1344
for record in generator.get_record_stream():
1347
for source, keys in source_keys:
1348
if source is parent_maps[0]:
1349
# this KnitVersionedFiles
1350
records = [(key, positions[key][1]) for key in keys]
1351
for key, raw_data, sha1 in self._read_records_iter_raw(records):
1352
(record_details, index_memo, _) = positions[key]
1353
yield KnitContentFactory(key, global_map[key],
1354
record_details, sha1, raw_data, self._factory.annotated, None)
1356
vf = self._fallback_vfs[parent_maps.index(source) - 1]
1357
for record in vf.get_record_stream(keys, ordering,
1358
include_delta_closure):
1361
def get_sha1s(self, keys):
1362
"""See VersionedFiles.get_sha1s()."""
1364
record_map = self._get_record_map(missing, allow_missing=True)
1366
for key, details in record_map.iteritems():
1367
if key not in missing:
1369
# record entry 2 is the 'digest'.
1370
result[key] = details[2]
1371
missing.difference_update(set(result))
1372
for source in self._fallback_vfs:
1375
new_result = source.get_sha1s(missing)
1376
result.update(new_result)
1377
missing.difference_update(set(new_result))
1380
def insert_record_stream(self, stream):
1381
"""Insert a record stream into this container.
1383
:param stream: A stream of records to insert.
1385
:seealso VersionedFiles.get_record_stream:
1387
def get_adapter(adapter_key):
1389
return adapters[adapter_key]
1391
adapter_factory = adapter_registry.get(adapter_key)
1392
adapter = adapter_factory(self)
1393
adapters[adapter_key] = adapter
1396
if self._factory.annotated:
1397
# self is annotated, we need annotated knits to use directly.
1398
annotated = "annotated-"
1401
# self is not annotated, but we can strip annotations cheaply.
1403
convertibles = set(["knit-annotated-ft-gz"])
1404
if self._max_delta_chain:
1405
delta_types.add("knit-annotated-delta-gz")
1406
convertibles.add("knit-annotated-delta-gz")
1407
# The set of types we can cheaply adapt without needing basis texts.
1408
native_types = set()
1409
if self._max_delta_chain:
1410
native_types.add("knit-%sdelta-gz" % annotated)
1411
delta_types.add("knit-%sdelta-gz" % annotated)
1412
native_types.add("knit-%sft-gz" % annotated)
1413
knit_types = native_types.union(convertibles)
1415
# Buffer all index entries that we can't add immediately because their
1416
# basis parent is missing. We don't buffer all because generating
1417
# annotations may require access to some of the new records. However we
1418
# can't generate annotations from new deltas until their basis parent
1419
# is present anyway, so we get away with not needing an index that
1420
# includes the new keys.
1422
# See <http://launchpad.net/bugs/300177> about ordering of compression
1423
# parents in the records - to be conservative, we insist that all
1424
# parents must be present to avoid expanding to a fulltext.
1426
# key = basis_parent, value = index entry to add
1427
buffered_index_entries = {}
1428
for record in stream:
1429
parents = record.parents
1430
if record.storage_kind in delta_types:
1431
# TODO: eventually the record itself should track
1432
# compression_parent
1433
compression_parent = parents[0]
1435
compression_parent = None
1436
# Raise an error when a record is missing.
1437
if record.storage_kind == 'absent':
1438
raise RevisionNotPresent([record.key], self)
1439
elif ((record.storage_kind in knit_types)
1440
and (compression_parent is None
1441
or not self._fallback_vfs
1442
or self._index.has_key(compression_parent)
1443
or not self.has_key(compression_parent))):
1444
# we can insert the knit record literally if either it has no
1445
# compression parent OR we already have its basis in this kvf
1446
# OR the basis is not present even in the fallbacks. In the
1447
# last case it will either turn up later in the stream and all
1448
# will be well, or it won't turn up at all and we'll raise an
1451
# TODO: self.has_key is somewhat redundant with
1452
# self._index.has_key; we really want something that directly
1453
# asks if it's only present in the fallbacks. -- mbp 20081119
1454
if record.storage_kind not in native_types:
1456
adapter_key = (record.storage_kind, "knit-delta-gz")
1457
adapter = get_adapter(adapter_key)
1459
adapter_key = (record.storage_kind, "knit-ft-gz")
1460
adapter = get_adapter(adapter_key)
1461
bytes = adapter.get_bytes(record)
1463
# It's a knit record, it has a _raw_record field (even if
1464
# it was reconstituted from a network stream).
1465
bytes = record._raw_record
1466
options = [record._build_details[0]]
1467
if record._build_details[1]:
1468
options.append('no-eol')
1469
# Just blat it across.
1470
# Note: This does end up adding data on duplicate keys. As
1471
# modern repositories use atomic insertions this should not
1472
# lead to excessive growth in the event of interrupted fetches.
1473
# 'knit' repositories may suffer excessive growth, but as a
1474
# deprecated format this is tolerable. It can be fixed if
1475
# needed by in the kndx index support raising on a duplicate
1476
# add with identical parents and options.
1477
access_memo = self._access.add_raw_records(
1478
[(record.key, len(bytes))], bytes)[0]
1479
index_entry = (record.key, options, access_memo, parents)
1481
if 'fulltext' not in options:
1482
# Not a fulltext, so we need to make sure the compression
1483
# parent will also be present.
1484
# Note that pack backed knits don't need to buffer here
1485
# because they buffer all writes to the transaction level,
1486
# but we don't expose that difference at the index level. If
1487
# the query here has sufficient cost to show up in
1488
# profiling we should do that.
1490
# They're required to be physically in this
1491
# KnitVersionedFiles, not in a fallback.
1492
if not self._index.has_key(compression_parent):
1493
pending = buffered_index_entries.setdefault(
1494
compression_parent, [])
1495
pending.append(index_entry)
1498
self._index.add_records([index_entry])
1499
elif record.storage_kind == 'chunked':
1500
self.add_lines(record.key, parents,
1501
osutils.chunks_to_lines(record.get_bytes_as('chunked')))
1503
# Not suitable for direct insertion as a
1504
# delta, either because it's not the right format, or this
1505
# KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
1506
# 0) or because it depends on a base only present in the
1509
# Try getting a fulltext directly from the record.
1510
bytes = record.get_bytes_as('fulltext')
1511
except errors.UnavailableRepresentation:
1512
adapter_key = record.storage_kind, 'fulltext'
1513
adapter = get_adapter(adapter_key)
1514
bytes = adapter.get_bytes(record)
1515
lines = split_lines(bytes)
1517
self.add_lines(record.key, parents, lines)
1518
except errors.RevisionAlreadyPresent:
1520
# Add any records whose basis parent is now available.
1521
added_keys = [record.key]
1523
key = added_keys.pop(0)
1524
if key in buffered_index_entries:
1525
index_entries = buffered_index_entries[key]
1526
self._index.add_records(index_entries)
1528
[index_entry[0] for index_entry in index_entries])
1529
del buffered_index_entries[key]
1530
if buffered_index_entries:
1531
# There were index entries buffered at the end of the stream,
1532
# So these need to be added (if the index supports holding such
1533
# entries for later insertion)
1534
for key in buffered_index_entries:
1535
index_entries = buffered_index_entries[key]
1536
self._index.add_records(index_entries,
1537
missing_compression_parents=True)
1539
def get_missing_compression_parent_keys(self):
1540
"""Return an iterable of keys of missing compression parents.
1542
Check this after calling insert_record_stream to find out if there are
1543
any missing compression parents. If there are, the records that
1544
depend on them are not able to be inserted safely. For atomic
1545
KnitVersionedFiles built on packs, the transaction should be aborted or
1546
suspended - commit will fail at this point. Nonatomic knits will error
1547
earlier because they have no staging area to put pending entries into.
1549
return self._index.get_missing_compression_parents()
1551
def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1552
"""Iterate over the lines in the versioned files from keys.
1554
This may return lines from other keys. Each item the returned
1555
iterator yields is a tuple of a line and a text version that that line
1556
is present in (not introduced in).
1558
Ordering of results is in whatever order is most suitable for the
1559
underlying storage format.
1561
If a progress bar is supplied, it may be used to indicate progress.
1562
The caller is responsible for cleaning up progress bars (because this
1566
* Lines are normalised by the underlying store: they will all have \\n
1568
* Lines are returned in arbitrary order.
1569
* If a requested key did not change any lines (or didn't have any
1570
lines), it may not be mentioned at all in the result.
1572
:return: An iterator over (line, key).
1575
pb = progress.DummyProgress()
1581
# we don't care about inclusions, the caller cares.
1582
# but we need to setup a list of records to visit.
1583
# we need key, position, length
1585
build_details = self._index.get_build_details(keys)
1586
for key, details in build_details.iteritems():
1588
key_records.append((key, details[0]))
1589
records_iter = enumerate(self._read_records_iter(key_records))
1590
for (key_idx, (key, data, sha_value)) in records_iter:
1591
pb.update('Walking content.', key_idx, total)
1592
compression_parent = build_details[key][1]
1593
if compression_parent is None:
1595
line_iterator = self._factory.get_fulltext_content(data)
1598
line_iterator = self._factory.get_linedelta_content(data)
1599
# Now that we are yielding the data for this key, remove it
1602
# XXX: It might be more efficient to yield (key,
1603
# line_iterator) in the future. However for now, this is a
1604
# simpler change to integrate into the rest of the
1605
# codebase. RBC 20071110
1606
for line in line_iterator:
1609
except errors.RetryWithNewPacks, e:
1610
self._access.reload_or_raise(e)
1611
# If there are still keys we've not yet found, we look in the fallback
1612
# vfs, and hope to find them there. Note that if the keys are found
1613
# but had no changes or no content, the fallback may not return
1615
if keys and not self._fallback_vfs:
1616
# XXX: strictly the second parameter is meant to be the file id
1617
# but it's not easily accessible here.
1618
raise RevisionNotPresent(keys, repr(self))
1619
for source in self._fallback_vfs:
1623
for line, key in source.iter_lines_added_or_present_in_keys(keys):
1624
source_keys.add(key)
1626
keys.difference_update(source_keys)
1627
pb.update('Walking content.', total, total)
1629
def _make_line_delta(self, delta_seq, new_content):
1630
"""Generate a line delta from delta_seq and new_content."""
1632
for op in delta_seq.get_opcodes():
1633
if op[0] == 'equal':
1635
diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
1638
def _merge_annotations(self, content, parents, parent_texts={},
1639
delta=None, annotated=None,
1640
left_matching_blocks=None):
1641
"""Merge annotations for content and generate deltas.
1643
This is done by comparing the annotations based on changes to the text
1644
and generating a delta on the resulting full texts. If annotations are
1645
not being created then a simple delta is created.
1647
if left_matching_blocks is not None:
1648
delta_seq = diff._PrematchedMatcher(left_matching_blocks)
1652
for parent_key in parents:
1653
merge_content = self._get_content(parent_key, parent_texts)
1654
if (parent_key == parents[0] and delta_seq is not None):
1657
seq = patiencediff.PatienceSequenceMatcher(
1658
None, merge_content.text(), content.text())
1659
for i, j, n in seq.get_matching_blocks():
1662
# this copies (origin, text) pairs across to the new
1663
# content for any line that matches the last-checked
1665
content._lines[j:j+n] = merge_content._lines[i:i+n]
1666
# XXX: Robert says the following block is a workaround for a
1667
# now-fixed bug and it can probably be deleted. -- mbp 20080618
1668
if content._lines and content._lines[-1][1][-1] != '\n':
1669
# The copied annotation was from a line without a trailing EOL,
1670
# reinstate one for the content object, to ensure correct
1672
line = content._lines[-1][1] + '\n'
1673
content._lines[-1] = (content._lines[-1][0], line)
1675
if delta_seq is None:
1676
reference_content = self._get_content(parents[0], parent_texts)
1677
new_texts = content.text()
1678
old_texts = reference_content.text()
1679
delta_seq = patiencediff.PatienceSequenceMatcher(
1680
None, old_texts, new_texts)
1681
return self._make_line_delta(delta_seq, content)
1683
def _parse_record(self, version_id, data):
1684
"""Parse an original format knit record.
1686
These have the last element of the key only present in the stored data.
1688
rec, record_contents = self._parse_record_unchecked(data)
1689
self._check_header_version(rec, version_id)
1690
return record_contents, rec[3]
1692
def _parse_record_header(self, key, raw_data):
1693
"""Parse a record header for consistency.
1695
:return: the header and the decompressor stream.
1696
as (stream, header_record)
1698
df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
1701
rec = self._check_header(key, df.readline())
1702
except Exception, e:
1703
raise KnitCorrupt(self,
1704
"While reading {%s} got %s(%s)"
1705
% (key, e.__class__.__name__, str(e)))
1708
def _parse_record_unchecked(self, data):
1710
# 4168 calls in 2880 217 internal
1711
# 4168 calls to _parse_record_header in 2121
1712
# 4168 calls to readlines in 330
1713
df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(data))
1715
record_contents = df.readlines()
1716
except Exception, e:
1717
raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1718
(data, e.__class__.__name__, str(e)))
1719
header = record_contents.pop(0)
1720
rec = self._split_header(header)
1721
last_line = record_contents.pop()
1722
if len(record_contents) != int(rec[2]):
1723
raise KnitCorrupt(self,
1724
'incorrect number of lines %s != %s'
1725
' for version {%s} %s'
1726
% (len(record_contents), int(rec[2]),
1727
rec[1], record_contents))
1728
if last_line != 'end %s\n' % rec[1]:
1729
raise KnitCorrupt(self,
1730
'unexpected version end line %r, wanted %r'
1731
% (last_line, rec[1]))
1733
return rec, record_contents
1735
def _read_records_iter(self, records):
1736
"""Read text records from data file and yield result.
1738
The result will be returned in whatever is the fastest to read.
1739
Not by the order requested. Also, multiple requests for the same
1740
record will only yield 1 response.
1741
:param records: A list of (key, access_memo) entries
1742
:return: Yields (key, contents, digest) in the order
1743
read, not the order requested
1748
# XXX: This smells wrong, IO may not be getting ordered right.
1749
needed_records = sorted(set(records), key=operator.itemgetter(1))
1750
if not needed_records:
1753
# The transport optimizes the fetching as well
1754
# (ie, reads continuous ranges.)
1755
raw_data = self._access.get_raw_records(
1756
[index_memo for key, index_memo in needed_records])
1758
for (key, index_memo), data in \
1759
izip(iter(needed_records), raw_data):
1760
content, digest = self._parse_record(key[-1], data)
1761
yield key, content, digest
1763
def _read_records_iter_raw(self, records):
1764
"""Read text records from data file and yield raw data.
1766
This unpacks enough of the text record to validate the id is
1767
as expected but thats all.
1769
Each item the iterator yields is (key, bytes,
1770
expected_sha1_of_full_text).
1772
for key, data in self._read_records_iter_unchecked(records):
1773
# validate the header (note that we can only use the suffix in
1774
# current knit records).
1775
df, rec = self._parse_record_header(key, data)
1777
yield key, data, rec[3]
1779
def _read_records_iter_unchecked(self, records):
1780
"""Read text records from data file and yield raw data.
1782
No validation is done.
1784
Yields tuples of (key, data).
1786
# setup an iterator of the external records:
1787
# uses readv so nice and fast we hope.
1789
# grab the disk data needed.
1790
needed_offsets = [index_memo for key, index_memo
1792
raw_records = self._access.get_raw_records(needed_offsets)
1794
for key, index_memo in records:
1795
data = raw_records.next()
1798
def _record_to_data(self, key, digest, lines, dense_lines=None):
1799
"""Convert key, digest, lines into a raw data block.
1801
:param key: The key of the record. Currently keys are always serialised
1802
using just the trailing component.
1803
:param dense_lines: The bytes of lines but in a denser form. For
1804
instance, if lines is a list of 1000 bytestrings each ending in \n,
1805
dense_lines may be a list with one line in it, containing all the
1806
1000's lines and their \n's. Using dense_lines if it is already
1807
known is a win because the string join to create bytes in this
1808
function spends less time resizing the final string.
1809
:return: (len, a StringIO instance with the raw data ready to read.)
1811
# Note: using a string copy here increases memory pressure with e.g.
1812
# ISO's, but it is about 3 seconds faster on a 1.2Ghz intel machine
1813
# when doing the initial commit of a mozilla tree. RBC 20070921
1814
bytes = ''.join(chain(
1815
["version %s %d %s\n" % (key[-1],
1818
dense_lines or lines,
1819
["end %s\n" % key[-1]]))
1820
if type(bytes) != str:
1821
raise AssertionError(
1822
'data must be plain bytes was %s' % type(bytes))
1823
if lines and lines[-1][-1] != '\n':
1824
raise ValueError('corrupt lines value %r' % lines)
1825
compressed_bytes = tuned_gzip.bytes_to_gzip(bytes)
1826
return len(compressed_bytes), compressed_bytes
1828
def _split_header(self, line):
1831
raise KnitCorrupt(self,
1832
'unexpected number of elements in record header')
1836
"""See VersionedFiles.keys."""
1837
if 'evil' in debug.debug_flags:
1838
trace.mutter_callsite(2, "keys scales with size of history")
1839
sources = [self._index] + self._fallback_vfs
1841
for source in sources:
1842
result.update(source.keys())
1846
class _ContentMapGenerator(object):
1847
"""Generate texts or expose raw deltas for a set of texts."""
1849
def _get_content(self, key):
1850
"""Get the content object for key."""
1851
# Note that _get_content is only called when the _ContentMapGenerator
1852
# has been constructed with just one key requested for reconstruction.
1853
if key in self.nonlocal_keys:
1854
record = self.get_record_stream().next()
1855
# Create a content object on the fly
1856
lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
1857
return PlainKnitContent(lines, record.key)
1859
# local keys we can ask for directly
1860
return self._get_one_work(key)
1862
def get_record_stream(self):
1863
"""Get a record stream for the keys requested during __init__."""
1864
for record in self._work():
1868
"""Produce maps of text and KnitContents as dicts.
1870
:return: (text_map, content_map) where text_map contains the texts for
1871
the requested versions and content_map contains the KnitContents.
1873
# NB: By definition we never need to read remote sources unless texts
1874
# are requested from them: we don't delta across stores - and we
1875
# explicitly do not want to to prevent data loss situations.
1876
if self.global_map is None:
1877
self.global_map = self.vf.get_parent_map(self.keys)
1878
nonlocal_keys = self.nonlocal_keys
1880
missing_keys = set(nonlocal_keys)
1881
# Read from remote versioned file instances and provide to our caller.
1882
for source in self.vf._fallback_vfs:
1883
if not missing_keys:
1885
# Loop over fallback repositories asking them for texts - ignore
1886
# any missing from a particular fallback.
1887
for record in source.get_record_stream(missing_keys,
1889
if record.storage_kind == 'absent':
1890
# Not in thie particular stream, may be in one of the
1891
# other fallback vfs objects.
1893
missing_keys.remove(record.key)
1896
self._raw_record_map = self.vf._get_record_map_unparsed(self.keys,
1899
for key in self.keys:
1900
if key in self.nonlocal_keys:
1902
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
1905
def _get_one_work(self, requested_key):
1906
# Now, if we have calculated everything already, just return the
1908
if requested_key in self._contents_map:
1909
return self._contents_map[requested_key]
1910
# To simplify things, parse everything at once - code that wants one text
1911
# probably wants them all.
1912
# FUTURE: This function could be improved for the 'extract many' case
1913
# by tracking each component and only doing the copy when the number of
1914
# children than need to apply delta's to it is > 1 or it is part of the
1916
multiple_versions = len(self.keys) != 1
1917
if self._record_map is None:
1918
self._record_map = self.vf._raw_map_to_record_map(
1919
self._raw_record_map)
1920
record_map = self._record_map
1921
# raw_record_map is key:
1922
# Have read and parsed records at this point.
1923
for key in self.keys:
1924
if key in self.nonlocal_keys:
1929
while cursor is not None:
1931
record, record_details, digest, next = record_map[cursor]
1933
raise RevisionNotPresent(cursor, self)
1934
components.append((cursor, record, record_details, digest))
1936
if cursor in self._contents_map:
1937
# no need to plan further back
1938
components.append((cursor, None, None, None))
1942
for (component_id, record, record_details,
1943
digest) in reversed(components):
1944
if component_id in self._contents_map:
1945
content = self._contents_map[component_id]
1947
content, delta = self._factory.parse_record(key[-1],
1948
record, record_details, content,
1949
copy_base_content=multiple_versions)
1950
if multiple_versions:
1951
self._contents_map[component_id] = content
1953
# digest here is the digest from the last applied component.
1954
text = content.text()
1955
actual_sha = sha_strings(text)
1956
if actual_sha != digest:
1957
raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
1958
if multiple_versions:
1959
return self._contents_map[requested_key]
1963
def _wire_bytes(self):
1964
"""Get the bytes to put on the wire for 'key'.
1966
The first collection of bytes asked for returns the serialised
1967
raw_record_map and the additional details (key, parent) for key.
1968
Subsequent calls return just the additional details (key, parent).
1969
The wire storage_kind given for the first key is 'knit-delta-closure',
1970
For subsequent keys it is 'knit-delta-closure-ref'.
1972
:param key: A key from the content generator.
1973
:return: Bytes to put on the wire.
1976
# kind marker for dispatch on the far side,
1977
lines.append('knit-delta-closure')
1979
if self.vf._factory.annotated:
1980
lines.append('annotated')
1983
# then the list of keys
1984
lines.append('\t'.join(['\x00'.join(key) for key in self.keys
1985
if key not in self.nonlocal_keys]))
1986
# then the _raw_record_map in serialised form:
1988
# for each item in the map:
1990
# 1 line with parents if the key is to be yielded (None: for None, '' for ())
1991
# one line with method
1992
# one line with noeol
1993
# one line with next ('' for None)
1994
# one line with byte count of the record bytes
1996
for key, (record_bytes, (method, noeol), next) in \
1997
self._raw_record_map.iteritems():
1998
key_bytes = '\x00'.join(key)
1999
parents = self.global_map.get(key, None)
2001
parent_bytes = 'None:'
2003
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2004
method_bytes = method
2010
next_bytes = '\x00'.join(next)
2013
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2014
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2015
len(record_bytes), record_bytes))
2016
map_bytes = ''.join(map_byte_list)
2017
lines.append(map_bytes)
2018
bytes = '\n'.join(lines)
2022
class _VFContentMapGenerator(_ContentMapGenerator):
2023
"""Content map generator reading from a VersionedFiles object."""
2025
def __init__(self, versioned_files, keys, nonlocal_keys=None,
2026
global_map=None, raw_record_map=None):
2027
"""Create a _ContentMapGenerator.
2029
:param versioned_files: The versioned files that the texts are being
2031
:param keys: The keys to produce content maps for.
2032
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2033
which are known to not be in this knit, but rather in one of the
2035
:param global_map: The result of get_parent_map(keys) (or a supermap).
2036
This is required if get_record_stream() is to be used.
2037
:param raw_record_map: A unparsed raw record map to use for answering
2040
# The vf to source data from
2041
self.vf = versioned_files
2043
self.keys = list(keys)
2044
# Keys known to be in fallback vfs objects
2045
if nonlocal_keys is None:
2046
self.nonlocal_keys = set()
2048
self.nonlocal_keys = frozenset(nonlocal_keys)
2049
# Parents data for keys to be returned in get_record_stream
2050
self.global_map = global_map
2051
# The chunked lists for self.keys in text form
2053
# A cache of KnitContent objects used in extracting texts.
2054
self._contents_map = {}
2055
# All the knit records needed to assemble the requested keys as full
2057
self._record_map = None
2058
if raw_record_map is None:
2059
self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2062
self._raw_record_map = raw_record_map
2063
# the factory for parsing records
2064
self._factory = self.vf._factory
2067
class _NetworkContentMapGenerator(_ContentMapGenerator):
2068
"""Content map generator sourced from a network stream."""
2070
def __init__(self, bytes, line_end):
2071
"""Construct a _NetworkContentMapGenerator from a bytes block."""
2073
self.global_map = {}
2074
self._raw_record_map = {}
2075
self._contents_map = {}
2076
self._record_map = None
2077
self.nonlocal_keys = []
2078
# Get access to record parsing facilities
2079
self.vf = KnitVersionedFiles(None, None)
2082
line_end = bytes.find('\n', start)
2083
line = bytes[start:line_end]
2084
start = line_end + 1
2085
if line == 'annotated':
2086
self._factory = KnitAnnotateFactory()
2088
self._factory = KnitPlainFactory()
2089
# list of keys to emit in get_record_stream
2090
line_end = bytes.find('\n', start)
2091
line = bytes[start:line_end]
2092
start = line_end + 1
2094
tuple(segment.split('\x00')) for segment in line.split('\t')
2096
# now a loop until the end. XXX: It would be nice if this was just a
2097
# bunch of the same records as get_record_stream(..., False) gives, but
2098
# there is a decent sized gap stopping that at the moment.
2102
line_end = bytes.find('\n', start)
2103
key = tuple(bytes[start:line_end].split('\x00'))
2104
start = line_end + 1
2105
# 1 line with parents (None: for None, '' for ())
2106
line_end = bytes.find('\n', start)
2107
line = bytes[start:line_end]
2112
[tuple(segment.split('\x00')) for segment in line.split('\t')
2114
self.global_map[key] = parents
2115
start = line_end + 1
2116
# one line with method
2117
line_end = bytes.find('\n', start)
2118
line = bytes[start:line_end]
2120
start = line_end + 1
2121
# one line with noeol
2122
line_end = bytes.find('\n', start)
2123
line = bytes[start:line_end]
2125
start = line_end + 1
2126
# one line with next ('' for None)
2127
line_end = bytes.find('\n', start)
2128
line = bytes[start:line_end]
2132
next = tuple(bytes[start:line_end].split('\x00'))
2133
start = line_end + 1
2134
# one line with byte count of the record bytes
2135
line_end = bytes.find('\n', start)
2136
line = bytes[start:line_end]
2138
start = line_end + 1
2140
record_bytes = bytes[start:start+count]
2141
start = start + count
2143
self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2145
def get_record_stream(self):
2146
"""Get a record stream for for keys requested by the bytestream."""
2148
for key in self.keys:
2149
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2152
def _wire_bytes(self):
2156
class _KndxIndex(object):
2157
"""Manages knit index files
2159
The index is kept in memory and read on startup, to enable
2160
fast lookups of revision information. The cursor of the index
2161
file is always pointing to the end, making it easy to append
2164
_cache is a cache for fast mapping from version id to a Index
2167
_history is a cache for fast mapping from indexes to version ids.
2169
The index data format is dictionary compressed when it comes to
2170
parent references; a index entry may only have parents that with a
2171
lover index number. As a result, the index is topological sorted.
2173
Duplicate entries may be written to the index for a single version id
2174
if this is done then the latter one completely replaces the former:
2175
this allows updates to correct version and parent information.
2176
Note that the two entries may share the delta, and that successive
2177
annotations and references MUST point to the first entry.
2179
The index file on disc contains a header, followed by one line per knit
2180
record. The same revision can be present in an index file more than once.
2181
The first occurrence gets assigned a sequence number starting from 0.
2183
The format of a single line is
2184
REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
2185
REVISION_ID is a utf8-encoded revision id
2186
FLAGS is a comma separated list of flags about the record. Values include
2187
no-eol, line-delta, fulltext.
2188
BYTE_OFFSET is the ascii representation of the byte offset in the data file
2189
that the the compressed data starts at.
2190
LENGTH is the ascii representation of the length of the data file.
2191
PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
2193
PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
2194
revision id already in the knit that is a parent of REVISION_ID.
2195
The ' :' marker is the end of record marker.
2198
when a write is interrupted to the index file, it will result in a line
2199
that does not end in ' :'. If the ' :' is not present at the end of a line,
2200
or at the end of the file, then the record that is missing it will be
2201
ignored by the parser.
2203
When writing new records to the index file, the data is preceded by '\n'
2204
to ensure that records always start on new lines even if the last write was
2205
interrupted. As a result its normal for the last line in the index to be
2206
missing a trailing newline. One can be added with no harmful effects.
2208
:ivar _kndx_cache: dict from prefix to the old state of KnitIndex objects,
2209
where prefix is e.g. the (fileid,) for .texts instances or () for
2210
constant-mapped things like .revisions, and the old state is
2211
tuple(history_vector, cache_dict). This is used to prevent having an
2212
ABI change with the C extension that reads .kndx files.
2215
HEADER = "# bzr knit index 8\n"
2217
def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
2218
"""Create a _KndxIndex on transport using mapper."""
2219
self._transport = transport
2220
self._mapper = mapper
2221
self._get_scope = get_scope
2222
self._allow_writes = allow_writes
2223
self._is_locked = is_locked
2225
self.has_graph = True
2227
def add_records(self, records, random_id=False, missing_compression_parents=False):
2228
"""Add multiple records to the index.
2230
:param records: a list of tuples:
2231
(key, options, access_memo, parents).
2232
:param random_id: If True the ids being added were randomly generated
2233
and no check for existence will be performed.
2234
:param missing_compression_parents: If True the records being added are
2235
only compressed against texts already in the index (or inside
2236
records). If False the records all refer to unavailable texts (or
2237
texts inside records) as compression parents.
2239
if missing_compression_parents:
2240
# It might be nice to get the edge of the records. But keys isn't
2242
keys = sorted(record[0] for record in records)
2243
raise errors.RevisionNotPresent(keys, self)
2245
for record in records:
2248
path = self._mapper.map(key) + '.kndx'
2249
path_keys = paths.setdefault(path, (prefix, []))
2250
path_keys[1].append(record)
2251
for path in sorted(paths):
2252
prefix, path_keys = paths[path]
2253
self._load_prefixes([prefix])
2255
orig_history = self._kndx_cache[prefix][1][:]
2256
orig_cache = self._kndx_cache[prefix][0].copy()
2259
for key, options, (_, pos, size), parents in path_keys:
2261
# kndx indices cannot be parentless.
2263
line = "\n%s %s %s %s %s :" % (
2264
key[-1], ','.join(options), pos, size,
2265
self._dictionary_compress(parents))
2266
if type(line) != str:
2267
raise AssertionError(
2268
'data must be utf8 was %s' % type(line))
2270
self._cache_key(key, options, pos, size, parents)
2271
if len(orig_history):
2272
self._transport.append_bytes(path, ''.join(lines))
2274
self._init_index(path, lines)
2276
# If any problems happen, restore the original values and re-raise
2277
self._kndx_cache[prefix] = (orig_cache, orig_history)
2280
def scan_unvalidated_index(self, graph_index):
2281
"""See _KnitGraphIndex.scan_unvalidated_index."""
2282
# Because kndx files do not support atomic insertion via separate index
2283
# files, they do not support this method.
2284
raise NotImplementedError(self.scan_unvalidated_index)
2286
def get_missing_compression_parents(self):
2287
"""See _KnitGraphIndex.get_missing_compression_parents."""
2288
# Because kndx files do not support atomic insertion via separate index
2289
# files, they do not support this method.
2290
raise NotImplementedError(self.get_missing_compression_parents)
2292
def _cache_key(self, key, options, pos, size, parent_keys):
2293
"""Cache a version record in the history array and index cache.
2295
This is inlined into _load_data for performance. KEEP IN SYNC.
2296
(It saves 60ms, 25% of the __init__ overhead on local 4000 record
2300
version_id = key[-1]
2301
# last-element only for compatibilty with the C load_data.
2302
parents = tuple(parent[-1] for parent in parent_keys)
2303
for parent in parent_keys:
2304
if parent[:-1] != prefix:
2305
raise ValueError("mismatched prefixes for %r, %r" % (
2307
cache, history = self._kndx_cache[prefix]
2308
# only want the _history index to reference the 1st index entry
2310
if version_id not in cache:
2311
index = len(history)
2312
history.append(version_id)
2314
index = cache[version_id][5]
2315
cache[version_id] = (version_id,
2322
def check_header(self, fp):
2323
line = fp.readline()
2325
# An empty file can actually be treated as though the file doesn't
2327
raise errors.NoSuchFile(self)
2328
if line != self.HEADER:
2329
raise KnitHeaderError(badline=line, filename=self)
2331
def _check_read(self):
2332
if not self._is_locked():
2333
raise errors.ObjectNotLocked(self)
2334
if self._get_scope() != self._scope:
2337
def _check_write_ok(self):
2338
"""Assert if not writes are permitted."""
2339
if not self._is_locked():
2340
raise errors.ObjectNotLocked(self)
2341
if self._get_scope() != self._scope:
2343
if self._mode != 'w':
2344
raise errors.ReadOnlyObjectDirtiedError(self)
2346
def get_build_details(self, keys):
2347
"""Get the method, index_memo and compression parent for keys.
2349
Ghosts are omitted from the result.
2351
:param keys: An iterable of keys.
2352
:return: A dict of key:(index_memo, compression_parent, parents,
2355
opaque structure to pass to read_records to extract the raw
2358
Content that this record is built upon, may be None
2360
Logical parents of this node
2362
extra information about the content which needs to be passed to
2363
Factory.parse_record
2365
parent_map = self.get_parent_map(keys)
2368
if key not in parent_map:
2370
method = self.get_method(key)
2371
parents = parent_map[key]
2372
if method == 'fulltext':
2373
compression_parent = None
2375
compression_parent = parents[0]
2376
noeol = 'no-eol' in self.get_options(key)
2377
index_memo = self.get_position(key)
2378
result[key] = (index_memo, compression_parent,
2379
parents, (method, noeol))
2382
def get_method(self, key):
2383
"""Return compression method of specified key."""
2384
options = self.get_options(key)
2385
if 'fulltext' in options:
2387
elif 'line-delta' in options:
2390
raise errors.KnitIndexUnknownMethod(self, options)
2392
def get_options(self, key):
2393
"""Return a list representing options.
2397
prefix, suffix = self._split_key(key)
2398
self._load_prefixes([prefix])
2400
return self._kndx_cache[prefix][0][suffix][1]
2402
raise RevisionNotPresent(key, self)
2404
def get_parent_map(self, keys):
2405
"""Get a map of the parents of keys.
2407
:param keys: The keys to look up parents for.
2408
:return: A mapping from keys to parents. Absent keys are absent from
2411
# Parse what we need to up front, this potentially trades off I/O
2412
# locality (.kndx and .knit in the same block group for the same file
2413
# id) for less checking in inner loops.
2414
prefixes = set(key[:-1] for key in keys)
2415
self._load_prefixes(prefixes)
2420
suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
2424
result[key] = tuple(prefix + (suffix,) for
2425
suffix in suffix_parents)
2428
def get_position(self, key):
2429
"""Return details needed to access the version.
2431
:return: a tuple (key, data position, size) to hand to the access
2432
logic to get the record.
2434
prefix, suffix = self._split_key(key)
2435
self._load_prefixes([prefix])
2436
entry = self._kndx_cache[prefix][0][suffix]
2437
return key, entry[2], entry[3]
2439
has_key = _mod_index._has_key_from_parent_map
2441
def _init_index(self, path, extra_lines=[]):
2442
"""Initialize an index."""
2444
sio.write(self.HEADER)
2445
sio.writelines(extra_lines)
2447
self._transport.put_file_non_atomic(path, sio,
2448
create_parent_dir=True)
2449
# self._create_parent_dir)
2450
# mode=self._file_mode,
2451
# dir_mode=self._dir_mode)
2454
"""Get all the keys in the collection.
2456
The keys are not ordered.
2459
# Identify all key prefixes.
2460
# XXX: A bit hacky, needs polish.
2461
if type(self._mapper) == ConstantMapper:
2465
for quoted_relpath in self._transport.iter_files_recursive():
2466
path, ext = os.path.splitext(quoted_relpath)
2468
prefixes = [self._mapper.unmap(path) for path in relpaths]
2469
self._load_prefixes(prefixes)
2470
for prefix in prefixes:
2471
for suffix in self._kndx_cache[prefix][1]:
2472
result.add(prefix + (suffix,))
2475
def _load_prefixes(self, prefixes):
2476
"""Load the indices for prefixes."""
2478
for prefix in prefixes:
2479
if prefix not in self._kndx_cache:
2480
# the load_data interface writes to these variables.
2483
self._filename = prefix
2485
path = self._mapper.map(prefix) + '.kndx'
2486
fp = self._transport.get(path)
2488
# _load_data may raise NoSuchFile if the target knit is
2490
_load_data(self, fp)
2493
self._kndx_cache[prefix] = (self._cache, self._history)
2498
self._kndx_cache[prefix] = ({}, [])
2499
if type(self._mapper) == ConstantMapper:
2500
# preserve behaviour for revisions.kndx etc.
2501
self._init_index(path)
2506
missing_keys = _mod_index._missing_keys_from_parent_map
2508
def _partition_keys(self, keys):
2509
"""Turn keys into a dict of prefix:suffix_list."""
2512
prefix_keys = result.setdefault(key[:-1], [])
2513
prefix_keys.append(key[-1])
2516
def _dictionary_compress(self, keys):
2517
"""Dictionary compress keys.
2519
:param keys: The keys to generate references to.
2520
:return: A string representation of keys. keys which are present are
2521
dictionary compressed, and others are emitted as fulltext with a
2527
prefix = keys[0][:-1]
2528
cache = self._kndx_cache[prefix][0]
2530
if key[:-1] != prefix:
2531
# kndx indices cannot refer across partitioned storage.
2532
raise ValueError("mismatched prefixes for %r" % keys)
2533
if key[-1] in cache:
2534
# -- inlined lookup() --
2535
result_list.append(str(cache[key[-1]][5]))
2536
# -- end lookup () --
2538
result_list.append('.' + key[-1])
2539
return ' '.join(result_list)
2541
def _reset_cache(self):
2542
# Possibly this should be a LRU cache. A dictionary from key_prefix to
2543
# (cache_dict, history_vector) for parsed kndx files.
2544
self._kndx_cache = {}
2545
self._scope = self._get_scope()
2546
allow_writes = self._allow_writes()
2552
def _sort_keys_by_io(self, keys, positions):
2553
"""Figure out an optimal order to read the records for the given keys.
2555
Sort keys, grouped by index and sorted by position.
2557
:param keys: A list of keys whose records we want to read. This will be
2559
:param positions: A dict, such as the one returned by
2560
_get_components_positions()
2563
def get_sort_key(key):
2564
index_memo = positions[key][1]
2565
# Group by prefix and position. index_memo[0] is the key, so it is
2566
# (file_id, revision_id) and we don't want to sort on revision_id,
2567
# index_memo[1] is the position, and index_memo[2] is the size,
2568
# which doesn't matter for the sort
2569
return index_memo[0][:-1], index_memo[1]
2570
return keys.sort(key=get_sort_key)
2572
def _split_key(self, key):
2573
"""Split key into a prefix and suffix."""
2574
return key[:-1], key[-1]
2577
class _KnitGraphIndex(object):
2578
"""A KnitVersionedFiles index layered on GraphIndex."""
2580
def __init__(self, graph_index, is_locked, deltas=False, parents=True,
2582
"""Construct a KnitGraphIndex on a graph_index.
2584
:param graph_index: An implementation of bzrlib.index.GraphIndex.
2585
:param is_locked: A callback to check whether the object should answer
2587
:param deltas: Allow delta-compressed records.
2588
:param parents: If True, record knits parents, if not do not record
2590
:param add_callback: If not None, allow additions to the index and call
2591
this callback with a list of added GraphIndex nodes:
2592
[(node, value, node_refs), ...]
2593
:param is_locked: A callback, returns True if the index is locked and
2596
self._add_callback = add_callback
2597
self._graph_index = graph_index
2598
self._deltas = deltas
2599
self._parents = parents
2600
if deltas and not parents:
2601
# XXX: TODO: Delta tree and parent graph should be conceptually
2603
raise KnitCorrupt(self, "Cannot do delta compression without "
2605
self.has_graph = parents
2606
self._is_locked = is_locked
2607
self._missing_compression_parents = set()
2610
return "%s(%r)" % (self.__class__.__name__, self._graph_index)
2612
def add_records(self, records, random_id=False,
2613
missing_compression_parents=False):
2614
"""Add multiple records to the index.
2616
This function does not insert data into the Immutable GraphIndex
2617
backing the KnitGraphIndex, instead it prepares data for insertion by
2618
the caller and checks that it is safe to insert then calls
2619
self._add_callback with the prepared GraphIndex nodes.
2621
:param records: a list of tuples:
2622
(key, options, access_memo, parents).
2623
:param random_id: If True the ids being added were randomly generated
2624
and no check for existence will be performed.
2625
:param missing_compression_parents: If True the records being added are
2626
only compressed against texts already in the index (or inside
2627
records). If False the records all refer to unavailable texts (or
2628
texts inside records) as compression parents.
2630
if not self._add_callback:
2631
raise errors.ReadOnlyError(self)
2632
# we hope there are no repositories with inconsistent parentage
2636
compression_parents = set()
2637
for (key, options, access_memo, parents) in records:
2639
parents = tuple(parents)
2640
index, pos, size = access_memo
2641
if 'no-eol' in options:
2645
value += "%d %d" % (pos, size)
2646
if not self._deltas:
2647
if 'line-delta' in options:
2648
raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
2651
if 'line-delta' in options:
2652
node_refs = (parents, (parents[0],))
2653
if missing_compression_parents:
2654
compression_parents.add(parents[0])
2656
node_refs = (parents, ())
2658
node_refs = (parents, )
2661
raise KnitCorrupt(self, "attempt to add node with parents "
2662
"in parentless index.")
2664
keys[key] = (value, node_refs)
2667
present_nodes = self._get_entries(keys)
2668
for (index, key, value, node_refs) in present_nodes:
2669
if (value[0] != keys[key][0][0] or
2670
node_refs[:1] != keys[key][1][:1]):
2671
raise KnitCorrupt(self, "inconsistent details in add_records"
2672
": %s %s" % ((value, node_refs), keys[key]))
2676
for key, (value, node_refs) in keys.iteritems():
2677
result.append((key, value, node_refs))
2679
for key, (value, node_refs) in keys.iteritems():
2680
result.append((key, value))
2681
self._add_callback(result)
2682
if missing_compression_parents:
2683
# This may appear to be incorrect (it does not check for
2684
# compression parents that are in the existing graph index),
2685
# but such records won't have been buffered, so this is
2686
# actually correct: every entry when
2687
# missing_compression_parents==True either has a missing parent, or
2688
# a parent that is one of the keys in records.
2689
compression_parents.difference_update(keys)
2690
self._missing_compression_parents.update(compression_parents)
2691
# Adding records may have satisfied missing compression parents.
2692
self._missing_compression_parents.difference_update(keys)
2694
def scan_unvalidated_index(self, graph_index):
2695
"""Inform this _KnitGraphIndex that there is an unvalidated index.
2697
This allows this _KnitGraphIndex to keep track of any missing
2698
compression parents we may want to have filled in to make those
2701
:param graph_index: A GraphIndex
2704
new_missing = graph_index.external_references(ref_list_num=1)
2705
new_missing.difference_update(self.get_parent_map(new_missing))
2706
self._missing_compression_parents.update(new_missing)
2708
def get_missing_compression_parents(self):
2709
"""Return the keys of missing compression parents.
2711
Missing compression parents occur when a record stream was missing
2712
basis texts, or a index was scanned that had missing basis texts.
2714
return frozenset(self._missing_compression_parents)
2716
def _check_read(self):
2717
"""raise if reads are not permitted."""
2718
if not self._is_locked():
2719
raise errors.ObjectNotLocked(self)
2721
def _check_write_ok(self):
2722
"""Assert if writes are not permitted."""
2723
if not self._is_locked():
2724
raise errors.ObjectNotLocked(self)
2726
def _compression_parent(self, an_entry):
2727
# return the key that an_entry is compressed against, or None
2728
# Grab the second parent list (as deltas implies parents currently)
2729
compression_parents = an_entry[3][1]
2730
if not compression_parents:
2732
if len(compression_parents) != 1:
2733
raise AssertionError(
2734
"Too many compression parents: %r" % compression_parents)
2735
return compression_parents[0]
2737
def get_build_details(self, keys):
2738
"""Get the method, index_memo and compression parent for version_ids.
2740
Ghosts are omitted from the result.
2742
:param keys: An iterable of keys.
2743
:return: A dict of key:
2744
(index_memo, compression_parent, parents, record_details).
2746
opaque structure to pass to read_records to extract the raw
2749
Content that this record is built upon, may be None
2751
Logical parents of this node
2753
extra information about the content which needs to be passed to
2754
Factory.parse_record
2758
entries = self._get_entries(keys, False)
2759
for entry in entries:
2761
if not self._parents:
2764
parents = entry[3][0]
2765
if not self._deltas:
2766
compression_parent_key = None
2768
compression_parent_key = self._compression_parent(entry)
2769
noeol = (entry[2][0] == 'N')
2770
if compression_parent_key:
2771
method = 'line-delta'
2774
result[key] = (self._node_to_position(entry),
2775
compression_parent_key, parents,
2779
def _get_entries(self, keys, check_present=False):
2780
"""Get the entries for keys.
2782
:param keys: An iterable of index key tuples.
2787
for node in self._graph_index.iter_entries(keys):
2789
found_keys.add(node[1])
2791
# adapt parentless index to the rest of the code.
2792
for node in self._graph_index.iter_entries(keys):
2793
yield node[0], node[1], node[2], ()
2794
found_keys.add(node[1])
2796
missing_keys = keys.difference(found_keys)
2798
raise RevisionNotPresent(missing_keys.pop(), self)
2800
def get_method(self, key):
2801
"""Return compression method of specified key."""
2802
return self._get_method(self._get_node(key))
2804
def _get_method(self, node):
2805
if not self._deltas:
2807
if self._compression_parent(node):
2812
def _get_node(self, key):
2814
return list(self._get_entries([key]))[0]
2816
raise RevisionNotPresent(key, self)
2818
def get_options(self, key):
2819
"""Return a list representing options.
2823
node = self._get_node(key)
2824
options = [self._get_method(node)]
2825
if node[2][0] == 'N':
2826
options.append('no-eol')
2829
def get_parent_map(self, keys):
2830
"""Get a map of the parents of keys.
2832
:param keys: The keys to look up parents for.
2833
:return: A mapping from keys to parents. Absent keys are absent from
2837
nodes = self._get_entries(keys)
2841
result[node[1]] = node[3][0]
2844
result[node[1]] = None
2847
def get_position(self, key):
2848
"""Return details needed to access the version.
2850
:return: a tuple (index, data position, size) to hand to the access
2851
logic to get the record.
2853
node = self._get_node(key)
2854
return self._node_to_position(node)
2856
has_key = _mod_index._has_key_from_parent_map
2859
"""Get all the keys in the collection.
2861
The keys are not ordered.
2864
return [node[1] for node in self._graph_index.iter_all_entries()]
2866
missing_keys = _mod_index._missing_keys_from_parent_map
2868
def _node_to_position(self, node):
2869
"""Convert an index value to position details."""
2870
bits = node[2][1:].split(' ')
2871
return node[0], int(bits[0]), int(bits[1])
2873
def _sort_keys_by_io(self, keys, positions):
2874
"""Figure out an optimal order to read the records for the given keys.
2876
Sort keys, grouped by index and sorted by position.
2878
:param keys: A list of keys whose records we want to read. This will be
2880
:param positions: A dict, such as the one returned by
2881
_get_components_positions()
2884
def get_index_memo(key):
2885
# index_memo is at offset [1]. It is made up of (GraphIndex,
2886
# position, size). GI is an object, which will be unique for each
2887
# pack file. This causes us to group by pack file, then sort by
2888
# position. Size doesn't matter, but it isn't worth breaking up the
2890
return positions[key][1]
2891
return keys.sort(key=get_index_memo)
2894
class _KnitKeyAccess(object):
2895
"""Access to records in .knit files."""
2897
def __init__(self, transport, mapper):
2898
"""Create a _KnitKeyAccess with transport and mapper.
2900
:param transport: The transport the access object is rooted at.
2901
:param mapper: The mapper used to map keys to .knit files.
2903
self._transport = transport
2904
self._mapper = mapper
2906
def add_raw_records(self, key_sizes, raw_data):
2907
"""Add raw knit bytes to a storage area.
2909
The data is spooled to the container writer in one bytes-record per
2912
:param sizes: An iterable of tuples containing the key and size of each
2914
:param raw_data: A bytestring containing the data.
2915
:return: A list of memos to retrieve the record later. Each memo is an
2916
opaque index memo. For _KnitKeyAccess the memo is (key, pos,
2917
length), where the key is the record key.
2919
if type(raw_data) != str:
2920
raise AssertionError(
2921
'data must be plain bytes was %s' % type(raw_data))
2924
# TODO: This can be tuned for writing to sftp and other servers where
2925
# append() is relatively expensive by grouping the writes to each key
2927
for key, size in key_sizes:
2928
path = self._mapper.map(key)
2930
base = self._transport.append_bytes(path + '.knit',
2931
raw_data[offset:offset+size])
2932
except errors.NoSuchFile:
2933
self._transport.mkdir(osutils.dirname(path))
2934
base = self._transport.append_bytes(path + '.knit',
2935
raw_data[offset:offset+size])
2939
result.append((key, base, size))
2942
def get_raw_records(self, memos_for_retrieval):
2943
"""Get the raw bytes for a records.
2945
:param memos_for_retrieval: An iterable containing the access memo for
2946
retrieving the bytes.
2947
:return: An iterator over the bytes of the records.
2949
# first pass, group into same-index request to minimise readv's issued.
2951
current_prefix = None
2952
for (key, offset, length) in memos_for_retrieval:
2953
if current_prefix == key[:-1]:
2954
current_list.append((offset, length))
2956
if current_prefix is not None:
2957
request_lists.append((current_prefix, current_list))
2958
current_prefix = key[:-1]
2959
current_list = [(offset, length)]
2960
# handle the last entry
2961
if current_prefix is not None:
2962
request_lists.append((current_prefix, current_list))
2963
for prefix, read_vector in request_lists:
2964
path = self._mapper.map(prefix) + '.knit'
2965
for pos, data in self._transport.readv(path, read_vector):
2969
class _DirectPackAccess(object):
2970
"""Access to data in one or more packs with less translation."""
2972
def __init__(self, index_to_packs, reload_func=None):
2973
"""Create a _DirectPackAccess object.
2975
:param index_to_packs: A dict mapping index objects to the transport
2976
and file names for obtaining data.
2977
:param reload_func: A function to call if we determine that the pack
2978
files have moved and we need to reload our caches. See
2979
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
2981
self._container_writer = None
2982
self._write_index = None
2983
self._indices = index_to_packs
2984
self._reload_func = reload_func
2986
def add_raw_records(self, key_sizes, raw_data):
2987
"""Add raw knit bytes to a storage area.
2989
The data is spooled to the container writer in one bytes-record per
2992
:param sizes: An iterable of tuples containing the key and size of each
2994
:param raw_data: A bytestring containing the data.
2995
:return: A list of memos to retrieve the record later. Each memo is an
2996
opaque index memo. For _DirectPackAccess the memo is (index, pos,
2997
length), where the index field is the write_index object supplied
2998
to the PackAccess object.
3000
if type(raw_data) != str:
3001
raise AssertionError(
3002
'data must be plain bytes was %s' % type(raw_data))
3005
for key, size in key_sizes:
3006
p_offset, p_length = self._container_writer.add_bytes_record(
3007
raw_data[offset:offset+size], [])
3009
result.append((self._write_index, p_offset, p_length))
3012
def get_raw_records(self, memos_for_retrieval):
3013
"""Get the raw bytes for a records.
3015
:param memos_for_retrieval: An iterable containing the (index, pos,
3016
length) memo for retrieving the bytes. The Pack access method
3017
looks up the pack to use for a given record in its index_to_pack
3019
:return: An iterator over the bytes of the records.
3021
# first pass, group into same-index requests
3023
current_index = None
3024
for (index, offset, length) in memos_for_retrieval:
3025
if current_index == index:
3026
current_list.append((offset, length))
3028
if current_index is not None:
3029
request_lists.append((current_index, current_list))
3030
current_index = index
3031
current_list = [(offset, length)]
3032
# handle the last entry
3033
if current_index is not None:
3034
request_lists.append((current_index, current_list))
3035
for index, offsets in request_lists:
3037
transport, path = self._indices[index]
3039
# A KeyError here indicates that someone has triggered an index
3040
# reload, and this index has gone missing, we need to start
3042
if self._reload_func is None:
3043
# If we don't have a _reload_func there is nothing that can
3046
raise errors.RetryWithNewPacks(index,
3047
reload_occurred=True,
3048
exc_info=sys.exc_info())
3050
reader = pack.make_readv_reader(transport, path, offsets)
3051
for names, read_func in reader.iter_records():
3052
yield read_func(None)
3053
except errors.NoSuchFile:
3054
# A NoSuchFile error indicates that a pack file has gone
3055
# missing on disk, we need to trigger a reload, and start over.
3056
if self._reload_func is None:
3058
raise errors.RetryWithNewPacks(transport.abspath(path),
3059
reload_occurred=False,
3060
exc_info=sys.exc_info())
3062
def set_writer(self, writer, index, transport_packname):
3063
"""Set a writer to use for adding data."""
3064
if index is not None:
3065
self._indices[index] = transport_packname
3066
self._container_writer = writer
3067
self._write_index = index
3069
def reload_or_raise(self, retry_exc):
3070
"""Try calling the reload function, or re-raise the original exception.
3072
This should be called after _DirectPackAccess raises a
3073
RetryWithNewPacks exception. This function will handle the common logic
3074
of determining when the error is fatal versus being temporary.
3075
It will also make sure that the original exception is raised, rather
3076
than the RetryWithNewPacks exception.
3078
If this function returns, then the calling function should retry
3079
whatever operation was being performed. Otherwise an exception will
3082
:param retry_exc: A RetryWithNewPacks exception.
3085
if self._reload_func is None:
3087
elif not self._reload_func():
3088
# The reload claimed that nothing changed
3089
if not retry_exc.reload_occurred:
3090
# If there wasn't an earlier reload, then we really were
3091
# expecting to find changes. We didn't find them, so this is a
3095
exc_class, exc_value, exc_traceback = retry_exc.exc_info
3096
raise exc_class, exc_value, exc_traceback
3099
# Deprecated, use PatienceSequenceMatcher instead
3100
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
3103
def annotate_knit(knit, revision_id):
3104
"""Annotate a knit with no cached annotations.
3106
This implementation is for knits with no cached annotations.
3107
It will work for knits with cached annotations, but this is not
3110
annotator = _KnitAnnotator(knit)
3111
return iter(annotator.annotate(revision_id))
3114
class _KnitAnnotator(object):
3115
"""Build up the annotations for a text."""
3117
def __init__(self, knit):
3120
# Content objects, differs from fulltexts because of how final newlines
3121
# are treated by knits. the content objects here will always have a
3123
self._fulltext_contents = {}
3125
# Annotated lines of specific revisions
3126
self._annotated_lines = {}
3128
# Track the raw data for nodes that we could not process yet.
3129
# This maps the revision_id of the base to a list of children that will
3130
# annotated from it.
3131
self._pending_children = {}
3133
# Nodes which cannot be extracted
3134
self._ghosts = set()
3136
# Track how many children this node has, so we know if we need to keep
3138
self._annotate_children = {}
3139
self._compression_children = {}
3141
self._all_build_details = {}
3142
# The children => parent revision_id graph
3143
self._revision_id_graph = {}
3145
self._heads_provider = None
3147
self._nodes_to_keep_annotations = set()
3148
self._generations_until_keep = 100
3150
def set_generations_until_keep(self, value):
3151
"""Set the number of generations before caching a node.
3153
Setting this to -1 will cache every merge node, setting this higher
3154
will cache fewer nodes.
3156
self._generations_until_keep = value
3158
def _add_fulltext_content(self, revision_id, content_obj):
3159
self._fulltext_contents[revision_id] = content_obj
3160
# TODO: jam 20080305 It might be good to check the sha1digest here
3161
return content_obj.text()
3163
def _check_parents(self, child, nodes_to_annotate):
3164
"""Check if all parents have been processed.
3166
:param child: A tuple of (rev_id, parents, raw_content)
3167
:param nodes_to_annotate: If child is ready, add it to
3168
nodes_to_annotate, otherwise put it back in self._pending_children
3170
for parent_id in child[1]:
3171
if (parent_id not in self._annotated_lines):
3172
# This parent is present, but another parent is missing
3173
self._pending_children.setdefault(parent_id,
3177
# This one is ready to be processed
3178
nodes_to_annotate.append(child)
3180
def _add_annotation(self, revision_id, fulltext, parent_ids,
3181
left_matching_blocks=None):
3182
"""Add an annotation entry.
3184
All parents should already have been annotated.
3185
:return: A list of children that now have their parents satisfied.
3187
a = self._annotated_lines
3188
annotated_parent_lines = [a[p] for p in parent_ids]
3189
annotated_lines = list(annotate.reannotate(annotated_parent_lines,
3190
fulltext, revision_id, left_matching_blocks,
3191
heads_provider=self._get_heads_provider()))
3192
self._annotated_lines[revision_id] = annotated_lines
3193
for p in parent_ids:
3194
ann_children = self._annotate_children[p]
3195
ann_children.remove(revision_id)
3196
if (not ann_children
3197
and p not in self._nodes_to_keep_annotations):
3198
del self._annotated_lines[p]
3199
del self._all_build_details[p]
3200
if p in self._fulltext_contents:
3201
del self._fulltext_contents[p]
3202
# Now that we've added this one, see if there are any pending
3203
# deltas to be done, certainly this parent is finished
3204
nodes_to_annotate = []
3205
for child in self._pending_children.pop(revision_id, []):
3206
self._check_parents(child, nodes_to_annotate)
3207
return nodes_to_annotate
3209
def _get_build_graph(self, key):
3210
"""Get the graphs for building texts and annotations.
3212
The data you need for creating a full text may be different than the
3213
data you need to annotate that text. (At a minimum, you need both
3214
parents to create an annotation, but only need 1 parent to generate the
3217
:return: A list of (key, index_memo) records, suitable for
3218
passing to read_records_iter to start reading in the raw data fro/
3221
if key in self._annotated_lines:
3224
pending = set([key])
3229
# get all pending nodes
3231
this_iteration = pending
3232
build_details = self._knit._index.get_build_details(this_iteration)
3233
self._all_build_details.update(build_details)
3234
# new_nodes = self._knit._index._get_entries(this_iteration)
3236
for key, details in build_details.iteritems():
3237
(index_memo, compression_parent, parents,
3238
record_details) = details
3239
self._revision_id_graph[key] = parents
3240
records.append((key, index_memo))
3241
# Do we actually need to check _annotated_lines?
3242
pending.update(p for p in parents
3243
if p not in self._all_build_details)
3244
if compression_parent:
3245
self._compression_children.setdefault(compression_parent,
3248
for parent in parents:
3249
self._annotate_children.setdefault(parent,
3251
num_gens = generation - kept_generation
3252
if ((num_gens >= self._generations_until_keep)
3253
and len(parents) > 1):
3254
kept_generation = generation
3255
self._nodes_to_keep_annotations.add(key)
3257
missing_versions = this_iteration.difference(build_details.keys())
3258
self._ghosts.update(missing_versions)
3259
for missing_version in missing_versions:
3260
# add a key, no parents
3261
self._revision_id_graph[missing_version] = ()
3262
pending.discard(missing_version) # don't look for it
3263
if self._ghosts.intersection(self._compression_children):
3265
"We cannot have nodes which have a ghost compression parent:\n"
3267
"compression children: %r"
3268
% (self._ghosts, self._compression_children))
3269
# Cleanout anything that depends on a ghost so that we don't wait for
3270
# the ghost to show up
3271
for node in self._ghosts:
3272
if node in self._annotate_children:
3273
# We won't be building this node
3274
del self._annotate_children[node]
3275
# Generally we will want to read the records in reverse order, because
3276
# we find the parent nodes after the children
3280
def _annotate_records(self, records):
3281
"""Build the annotations for the listed records."""
3282
# We iterate in the order read, rather than a strict order requested
3283
# However, process what we can, and put off to the side things that
3284
# still need parents, cleaning them up when those parents are
3286
for (rev_id, record,
3287
digest) in self._knit._read_records_iter(records):
3288
if rev_id in self._annotated_lines:
3290
parent_ids = self._revision_id_graph[rev_id]
3291
parent_ids = [p for p in parent_ids if p not in self._ghosts]
3292
details = self._all_build_details[rev_id]
3293
(index_memo, compression_parent, parents,
3294
record_details) = details
3295
nodes_to_annotate = []
3296
# TODO: Remove the punning between compression parents, and
3297
# parent_ids, we should be able to do this without assuming
3299
if len(parent_ids) == 0:
3300
# There are no parents for this node, so just add it
3301
# TODO: This probably needs to be decoupled
3302
fulltext_content, delta = self._knit._factory.parse_record(
3303
rev_id, record, record_details, None)
3304
fulltext = self._add_fulltext_content(rev_id, fulltext_content)
3305
nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
3306
parent_ids, left_matching_blocks=None))
3308
child = (rev_id, parent_ids, record)
3309
# Check if all the parents are present
3310
self._check_parents(child, nodes_to_annotate)
3311
while nodes_to_annotate:
3312
# Should we use a queue here instead of a stack?
3313
(rev_id, parent_ids, record) = nodes_to_annotate.pop()
3314
(index_memo, compression_parent, parents,
3315
record_details) = self._all_build_details[rev_id]
3317
if compression_parent is not None:
3318
comp_children = self._compression_children[compression_parent]
3319
if rev_id not in comp_children:
3320
raise AssertionError("%r not in compression children %r"
3321
% (rev_id, comp_children))
3322
# If there is only 1 child, it is safe to reuse this
3324
reuse_content = (len(comp_children) == 1
3325
and compression_parent not in
3326
self._nodes_to_keep_annotations)
3328
# Remove it from the cache since it will be changing
3329
parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
3330
# Make sure to copy the fulltext since it might be
3332
parent_fulltext = list(parent_fulltext_content.text())
3334
parent_fulltext_content = self._fulltext_contents[compression_parent]
3335
parent_fulltext = parent_fulltext_content.text()
3336
comp_children.remove(rev_id)
3337
fulltext_content, delta = self._knit._factory.parse_record(
3338
rev_id, record, record_details,
3339
parent_fulltext_content,
3340
copy_base_content=(not reuse_content))
3341
fulltext = self._add_fulltext_content(rev_id,
3343
if compression_parent == parent_ids[0]:
3344
# the compression_parent is the left parent, so we can
3346
blocks = KnitContent.get_line_delta_blocks(delta,
3347
parent_fulltext, fulltext)
3349
fulltext_content = self._knit._factory.parse_fulltext(
3351
fulltext = self._add_fulltext_content(rev_id,
3353
nodes_to_annotate.extend(
3354
self._add_annotation(rev_id, fulltext, parent_ids,
3355
left_matching_blocks=blocks))
3357
def _get_heads_provider(self):
3358
"""Create a heads provider for resolving ancestry issues."""
3359
if self._heads_provider is not None:
3360
return self._heads_provider
3361
parent_provider = _mod_graph.DictParentsProvider(
3362
self._revision_id_graph)
3363
graph_obj = _mod_graph.Graph(parent_provider)
3364
head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
3365
self._heads_provider = head_cache
3368
def annotate(self, key):
3369
"""Return the annotated fulltext at the given key.
3371
:param key: The key to annotate.
3373
if len(self._knit._fallback_vfs) > 0:
3374
# stacked knits can't use the fast path at present.
3375
return self._simple_annotate(key)
3378
records = self._get_build_graph(key)
3379
if key in self._ghosts:
3380
raise errors.RevisionNotPresent(key, self._knit)
3381
self._annotate_records(records)
3382
return self._annotated_lines[key]
3383
except errors.RetryWithNewPacks, e:
3384
self._knit._access.reload_or_raise(e)
3385
# The cached build_details are no longer valid
3386
self._all_build_details.clear()
3388
def _simple_annotate(self, key):
3389
"""Return annotated fulltext, rediffing from the full texts.
3391
This is slow but makes no assumptions about the repository
3392
being able to produce line deltas.
3394
# TODO: this code generates a parent maps of present ancestors; it
3395
# could be split out into a separate method, and probably should use
3396
# iter_ancestry instead. -- mbp and robertc 20080704
3397
graph = _mod_graph.Graph(self._knit)
3398
head_cache = _mod_graph.FrozenHeadsCache(graph)
3399
search = graph._make_breadth_first_searcher([key])
3403
present, ghosts = search.next_with_ghosts()
3404
except StopIteration:
3406
keys.update(present)
3407
parent_map = self._knit.get_parent_map(keys)
3409
reannotate = annotate.reannotate
3410
for record in self._knit.get_record_stream(keys, 'topological', True):
3412
fulltext = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
3413
parents = parent_map[key]
3414
if parents is not None:
3415
parent_lines = [parent_cache[parent] for parent in parent_map[key]]
3418
parent_cache[key] = list(
3419
reannotate(parent_lines, fulltext, key, None, head_cache))
3421
return parent_cache[key]
3423
raise errors.RevisionNotPresent(key, self._knit)
3427
from bzrlib._knit_load_data_c import _load_data_c as _load_data
3429
from bzrlib._knit_load_data_py import _load_data_py as _load_data