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
# 10:16 < lifeless> make partial index writes safe
56
# 10:16 < lifeless> implement 'knit.check()' like weave.check()
57
# 10:17 < lifeless> record known ghosts so we can detect when they are filled in rather than the current 'reweave
59
# move sha1 out of the content so that join is faster at verifying parents
60
# record content length ?
63
from cStringIO import StringIO
64
from itertools import izip, chain
69
from bzrlib.lazy_import import lazy_import
70
lazy_import(globals(), """
90
from bzrlib.errors import (
98
RevisionAlreadyPresent,
101
from bzrlib.osutils import (
108
from bzrlib.versionedfile import (
109
AbsentContentFactory,
113
ChunkedContentFactory,
119
# TODO: Split out code specific to this format into an associated object.
121
# TODO: Can we put in some kind of value to check that the index and data
122
# files belong together?
124
# TODO: accommodate binaries, perhaps by storing a byte count
126
# TODO: function to check whole file
128
# TODO: atomically append data, then measure backwards from the cursor
129
# position after writing to work out where it was located. we may need to
130
# bypass python file buffering.
132
DATA_SUFFIX = '.knit'
133
INDEX_SUFFIX = '.kndx'
136
class KnitAdapter(object):
137
"""Base class for knit record adaption."""
139
def __init__(self, basis_vf):
140
"""Create an adapter which accesses full texts from basis_vf.
142
:param basis_vf: A versioned file to access basis texts of deltas from.
143
May be None for adapters that do not need to access basis texts.
145
self._data = KnitVersionedFiles(None, None)
146
self._annotate_factory = KnitAnnotateFactory()
147
self._plain_factory = KnitPlainFactory()
148
self._basis_vf = basis_vf
151
class FTAnnotatedToUnannotated(KnitAdapter):
152
"""An adapter from FT annotated knits to unannotated ones."""
154
def get_bytes(self, factory):
155
annotated_compressed_bytes = factory._raw_record
157
self._data._parse_record_unchecked(annotated_compressed_bytes)
158
content = self._annotate_factory.parse_fulltext(contents, rec[1])
159
size, bytes = self._data._record_to_data((rec[1],), rec[3], content.text())
163
class DeltaAnnotatedToUnannotated(KnitAdapter):
164
"""An adapter for deltas from annotated to unannotated."""
166
def get_bytes(self, factory):
167
annotated_compressed_bytes = factory._raw_record
169
self._data._parse_record_unchecked(annotated_compressed_bytes)
170
delta = self._annotate_factory.parse_line_delta(contents, rec[1],
172
contents = self._plain_factory.lower_line_delta(delta)
173
size, bytes = self._data._record_to_data((rec[1],), rec[3], contents)
177
class FTAnnotatedToFullText(KnitAdapter):
178
"""An adapter from FT annotated knits to unannotated ones."""
180
def get_bytes(self, factory):
181
annotated_compressed_bytes = factory._raw_record
183
self._data._parse_record_unchecked(annotated_compressed_bytes)
184
content, delta = self._annotate_factory.parse_record(factory.key[-1],
185
contents, factory._build_details, None)
186
return ''.join(content.text())
189
class DeltaAnnotatedToFullText(KnitAdapter):
190
"""An adapter for deltas from annotated to unannotated."""
192
def get_bytes(self, factory):
193
annotated_compressed_bytes = factory._raw_record
195
self._data._parse_record_unchecked(annotated_compressed_bytes)
196
delta = self._annotate_factory.parse_line_delta(contents, rec[1],
198
compression_parent = factory.parents[0]
199
basis_entry = self._basis_vf.get_record_stream(
200
[compression_parent], 'unordered', True).next()
201
if basis_entry.storage_kind == 'absent':
202
raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
203
basis_chunks = basis_entry.get_bytes_as('chunked')
204
basis_lines = osutils.chunks_to_lines(basis_chunks)
205
# Manually apply the delta because we have one annotated content and
207
basis_content = PlainKnitContent(basis_lines, compression_parent)
208
basis_content.apply_delta(delta, rec[1])
209
basis_content._should_strip_eol = factory._build_details[1]
210
return ''.join(basis_content.text())
213
class FTPlainToFullText(KnitAdapter):
214
"""An adapter from FT plain knits to unannotated ones."""
216
def get_bytes(self, factory):
217
compressed_bytes = factory._raw_record
219
self._data._parse_record_unchecked(compressed_bytes)
220
content, delta = self._plain_factory.parse_record(factory.key[-1],
221
contents, factory._build_details, None)
222
return ''.join(content.text())
225
class DeltaPlainToFullText(KnitAdapter):
226
"""An adapter for deltas from annotated to unannotated."""
228
def get_bytes(self, factory):
229
compressed_bytes = factory._raw_record
231
self._data._parse_record_unchecked(compressed_bytes)
232
delta = self._plain_factory.parse_line_delta(contents, rec[1])
233
compression_parent = factory.parents[0]
234
# XXX: string splitting overhead.
235
basis_entry = self._basis_vf.get_record_stream(
236
[compression_parent], 'unordered', True).next()
237
if basis_entry.storage_kind == 'absent':
238
raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
239
basis_chunks = basis_entry.get_bytes_as('chunked')
240
basis_lines = osutils.chunks_to_lines(basis_chunks)
241
basis_content = PlainKnitContent(basis_lines, compression_parent)
242
# Manually apply the delta because we have one annotated content and
244
content, _ = self._plain_factory.parse_record(rec[1], contents,
245
factory._build_details, basis_content)
246
return ''.join(content.text())
249
class KnitContentFactory(ContentFactory):
250
"""Content factory for streaming from knits.
252
:seealso ContentFactory:
255
def __init__(self, key, parents, build_details, sha1, raw_record,
256
annotated, knit=None, network_bytes=None):
257
"""Create a KnitContentFactory for key.
260
:param parents: The parents.
261
:param build_details: The build details as returned from
263
:param sha1: The sha1 expected from the full text of this object.
264
:param raw_record: The bytes of the knit data from disk.
265
:param annotated: True if the raw data is annotated.
266
:param network_bytes: None to calculate the network bytes on demand,
267
not-none if they are already known.
269
ContentFactory.__init__(self)
272
self.parents = parents
273
if build_details[0] == 'line-delta':
278
annotated_kind = 'annotated-'
281
self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
282
self._raw_record = raw_record
283
self._network_bytes = network_bytes
284
self._build_details = build_details
287
def _create_network_bytes(self):
288
"""Create a fully serialised network version for transmission."""
289
# storage_kind, key, parents, Noeol, raw_record
290
key_bytes = '\x00'.join(self.key)
291
if self.parents is None:
292
parent_bytes = 'None:'
294
parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
295
if self._build_details[1]:
299
network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
300
parent_bytes, noeol, self._raw_record)
301
self._network_bytes = network_bytes
303
def get_bytes_as(self, storage_kind):
304
if storage_kind == self.storage_kind:
305
if self._network_bytes is None:
306
self._create_network_bytes()
307
return self._network_bytes
308
if self._knit is not None:
309
if storage_kind == 'chunked':
310
return self._knit.get_lines(self.key[0])
311
elif storage_kind == 'fulltext':
312
return self._knit.get_text(self.key[0])
313
raise errors.UnavailableRepresentation(self.key, storage_kind,
317
class LazyKnitContentFactory(ContentFactory):
318
"""A ContentFactory which can either generate full text or a wire form.
320
:seealso ContentFactory:
323
def __init__(self, key, parents, generator, first):
324
"""Create a LazyKnitContentFactory.
326
:param key: The key of the record.
327
:param parents: The parents of the record.
328
:param generator: A _ContentMapGenerator containing the record for this
330
:param first: Is this the first content object returned from generator?
331
if it is, its storage kind is knit-delta-closure, otherwise it is
332
knit-delta-closure-ref
335
self.parents = parents
337
self._generator = generator
338
self.storage_kind = "knit-delta-closure"
340
self.storage_kind = self.storage_kind + "-ref"
343
def get_bytes_as(self, storage_kind):
344
if storage_kind == self.storage_kind:
346
return self._generator._wire_bytes()
348
# all the keys etc are contained in the bytes returned in the
351
if storage_kind in ('chunked', 'fulltext'):
352
chunks = self._generator._get_one_work(self.key).text()
353
if storage_kind == 'chunked':
356
return ''.join(chunks)
357
raise errors.UnavailableRepresentation(self.key, storage_kind,
361
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
362
"""Convert a network record to a iterator over stream records.
364
:param storage_kind: The storage kind of the record.
365
Must be 'knit-delta-closure'.
366
:param bytes: The bytes of the record on the network.
368
generator = _NetworkContentMapGenerator(bytes, line_end)
369
return generator.get_record_stream()
372
def knit_network_to_record(storage_kind, bytes, line_end):
373
"""Convert a network record to a record object.
375
:param storage_kind: The storage kind of the record.
376
:param bytes: The bytes of the record on the network.
379
line_end = bytes.find('\n', start)
380
key = tuple(bytes[start:line_end].split('\x00'))
382
line_end = bytes.find('\n', start)
383
parent_line = bytes[start:line_end]
384
if parent_line == 'None:':
388
[tuple(segment.split('\x00')) for segment in parent_line.split('\t')
391
noeol = bytes[start] == 'N'
392
if 'ft' in storage_kind:
395
method = 'line-delta'
396
build_details = (method, noeol)
398
raw_record = bytes[start:]
399
annotated = 'annotated' in storage_kind
400
return [KnitContentFactory(key, parents, build_details, None, raw_record,
401
annotated, network_bytes=bytes)]
404
class KnitContent(object):
405
"""Content of a knit version to which deltas can be applied.
407
This is always stored in memory as a list of lines with \n at the end,
408
plus a flag saying if the final ending is really there or not, because that
409
corresponds to the on-disk knit representation.
413
self._should_strip_eol = False
415
def apply_delta(self, delta, new_version_id):
416
"""Apply delta to this object to become new_version_id."""
417
raise NotImplementedError(self.apply_delta)
419
def line_delta_iter(self, new_lines):
420
"""Generate line-based delta from this content to new_lines."""
421
new_texts = new_lines.text()
422
old_texts = self.text()
423
s = patiencediff.PatienceSequenceMatcher(None, old_texts, new_texts)
424
for tag, i1, i2, j1, j2 in s.get_opcodes():
427
# ofrom, oto, length, data
428
yield i1, i2, j2 - j1, new_lines._lines[j1:j2]
430
def line_delta(self, new_lines):
431
return list(self.line_delta_iter(new_lines))
434
def get_line_delta_blocks(knit_delta, source, target):
435
"""Extract SequenceMatcher.get_matching_blocks() from a knit delta"""
436
target_len = len(target)
439
for s_begin, s_end, t_len, new_text in knit_delta:
440
true_n = s_begin - s_pos
443
# knit deltas do not provide reliable info about whether the
444
# last line of a file matches, due to eol handling.
445
if source[s_pos + n -1] != target[t_pos + n -1]:
448
yield s_pos, t_pos, n
449
t_pos += t_len + true_n
451
n = target_len - t_pos
453
if source[s_pos + n -1] != target[t_pos + n -1]:
456
yield s_pos, t_pos, n
457
yield s_pos + (target_len - t_pos), target_len, 0
460
class AnnotatedKnitContent(KnitContent):
461
"""Annotated content."""
463
def __init__(self, lines):
464
KnitContent.__init__(self)
468
"""Return a list of (origin, text) for each content line."""
469
lines = self._lines[:]
470
if self._should_strip_eol:
471
origin, last_line = lines[-1]
472
lines[-1] = (origin, last_line.rstrip('\n'))
475
def apply_delta(self, delta, new_version_id):
476
"""Apply delta to this object to become new_version_id."""
479
for start, end, count, delta_lines in delta:
480
lines[offset+start:offset+end] = delta_lines
481
offset = offset + (start - end) + count
485
lines = [text for origin, text in self._lines]
486
except ValueError, e:
487
# most commonly (only?) caused by the internal form of the knit
488
# missing annotation information because of a bug - see thread
490
raise KnitCorrupt(self,
491
"line in annotated knit missing annotation information: %s"
493
if self._should_strip_eol:
494
lines[-1] = lines[-1].rstrip('\n')
498
return AnnotatedKnitContent(self._lines[:])
501
class PlainKnitContent(KnitContent):
502
"""Unannotated content.
504
When annotate[_iter] is called on this content, the same version is reported
505
for all lines. Generally, annotate[_iter] is not useful on PlainKnitContent
509
def __init__(self, lines, version_id):
510
KnitContent.__init__(self)
512
self._version_id = version_id
515
"""Return a list of (origin, text) for each content line."""
516
return [(self._version_id, line) for line in self._lines]
518
def apply_delta(self, delta, new_version_id):
519
"""Apply delta to this object to become new_version_id."""
522
for start, end, count, delta_lines in delta:
523
lines[offset+start:offset+end] = delta_lines
524
offset = offset + (start - end) + count
525
self._version_id = new_version_id
528
return PlainKnitContent(self._lines[:], self._version_id)
532
if self._should_strip_eol:
534
lines[-1] = lines[-1].rstrip('\n')
538
class _KnitFactory(object):
539
"""Base class for common Factory functions."""
541
def parse_record(self, version_id, record, record_details,
542
base_content, copy_base_content=True):
543
"""Parse a record into a full content object.
545
:param version_id: The official version id for this content
546
:param record: The data returned by read_records_iter()
547
:param record_details: Details about the record returned by
549
:param base_content: If get_build_details returns a compression_parent,
550
you must return a base_content here, else use None
551
:param copy_base_content: When building from the base_content, decide
552
you can either copy it and return a new object, or modify it in
554
:return: (content, delta) A Content object and possibly a line-delta,
557
method, noeol = record_details
558
if method == 'line-delta':
559
if copy_base_content:
560
content = base_content.copy()
562
content = base_content
563
delta = self.parse_line_delta(record, version_id)
564
content.apply_delta(delta, version_id)
566
content = self.parse_fulltext(record, version_id)
568
content._should_strip_eol = noeol
569
return (content, delta)
572
class KnitAnnotateFactory(_KnitFactory):
573
"""Factory for creating annotated Content objects."""
577
def make(self, lines, version_id):
578
num_lines = len(lines)
579
return AnnotatedKnitContent(zip([version_id] * num_lines, lines))
581
def parse_fulltext(self, content, version_id):
582
"""Convert fulltext to internal representation
584
fulltext content is of the format
585
revid(utf8) plaintext\n
586
internal representation is of the format:
589
# TODO: jam 20070209 The tests expect this to be returned as tuples,
590
# but the code itself doesn't really depend on that.
591
# Figure out a way to not require the overhead of turning the
592
# list back into tuples.
593
lines = [tuple(line.split(' ', 1)) for line in content]
594
return AnnotatedKnitContent(lines)
596
def parse_line_delta_iter(self, lines):
597
return iter(self.parse_line_delta(lines))
599
def parse_line_delta(self, lines, version_id, plain=False):
600
"""Convert a line based delta into internal representation.
602
line delta is in the form of:
603
intstart intend intcount
605
revid(utf8) newline\n
606
internal representation is
607
(start, end, count, [1..count tuples (revid, newline)])
609
:param plain: If True, the lines are returned as a plain
610
list without annotations, not as a list of (origin, content) tuples, i.e.
611
(start, end, count, [1..count newline])
618
def cache_and_return(line):
619
origin, text = line.split(' ', 1)
620
return cache.setdefault(origin, origin), text
622
# walk through the lines parsing.
623
# Note that the plain test is explicitly pulled out of the
624
# loop to minimise any performance impact
627
start, end, count = [int(n) for n in header.split(',')]
628
contents = [next().split(' ', 1)[1] for i in xrange(count)]
629
result.append((start, end, count, contents))
632
start, end, count = [int(n) for n in header.split(',')]
633
contents = [tuple(next().split(' ', 1)) for i in xrange(count)]
634
result.append((start, end, count, contents))
637
def get_fulltext_content(self, lines):
638
"""Extract just the content lines from a fulltext."""
639
return (line.split(' ', 1)[1] for line in lines)
641
def get_linedelta_content(self, lines):
642
"""Extract just the content from a line delta.
644
This doesn't return all of the extra information stored in a delta.
645
Only the actual content lines.
650
header = header.split(',')
651
count = int(header[2])
652
for i in xrange(count):
653
origin, text = next().split(' ', 1)
656
def lower_fulltext(self, content):
657
"""convert a fulltext content record into a serializable form.
659
see parse_fulltext which this inverts.
661
# TODO: jam 20070209 We only do the caching thing to make sure that
662
# the origin is a valid utf-8 line, eventually we could remove it
663
return ['%s %s' % (o, t) for o, t in content._lines]
665
def lower_line_delta(self, delta):
666
"""convert a delta into a serializable form.
668
See parse_line_delta which this inverts.
670
# TODO: jam 20070209 We only do the caching thing to make sure that
671
# the origin is a valid utf-8 line, eventually we could remove it
673
for start, end, c, lines in delta:
674
out.append('%d,%d,%d\n' % (start, end, c))
675
out.extend(origin + ' ' + text
676
for origin, text in lines)
679
def annotate(self, knit, key):
680
content = knit._get_content(key)
681
# adjust for the fact that serialised annotations are only key suffixes
683
if type(key) == tuple:
685
origins = content.annotate()
687
for origin, line in origins:
688
result.append((prefix + (origin,), line))
691
# XXX: This smells a bit. Why would key ever be a non-tuple here?
692
# Aren't keys defined to be tuples? -- spiv 20080618
693
return content.annotate()
696
class KnitPlainFactory(_KnitFactory):
697
"""Factory for creating plain Content objects."""
701
def make(self, lines, version_id):
702
return PlainKnitContent(lines, version_id)
704
def parse_fulltext(self, content, version_id):
705
"""This parses an unannotated fulltext.
707
Note that this is not a noop - the internal representation
708
has (versionid, line) - its just a constant versionid.
710
return self.make(content, version_id)
712
def parse_line_delta_iter(self, lines, version_id):
714
num_lines = len(lines)
715
while cur < num_lines:
718
start, end, c = [int(n) for n in header.split(',')]
719
yield start, end, c, lines[cur:cur+c]
722
def parse_line_delta(self, lines, version_id):
723
return list(self.parse_line_delta_iter(lines, version_id))
725
def get_fulltext_content(self, lines):
726
"""Extract just the content lines from a fulltext."""
729
def get_linedelta_content(self, lines):
730
"""Extract just the content from a line delta.
732
This doesn't return all of the extra information stored in a delta.
733
Only the actual content lines.
738
header = header.split(',')
739
count = int(header[2])
740
for i in xrange(count):
743
def lower_fulltext(self, content):
744
return content.text()
746
def lower_line_delta(self, delta):
748
for start, end, c, lines in delta:
749
out.append('%d,%d,%d\n' % (start, end, c))
753
def annotate(self, knit, key):
754
annotator = _KnitAnnotator(knit)
755
return annotator.annotate(key)
759
def make_file_factory(annotated, mapper):
760
"""Create a factory for creating a file based KnitVersionedFiles.
762
This is only functional enough to run interface tests, it doesn't try to
763
provide a full pack environment.
765
:param annotated: knit annotations are wanted.
766
:param mapper: The mapper from keys to paths.
768
def factory(transport):
769
index = _KndxIndex(transport, mapper, lambda:None, lambda:True, lambda:True)
770
access = _KnitKeyAccess(transport, mapper)
771
return KnitVersionedFiles(index, access, annotated=annotated)
775
def make_pack_factory(graph, delta, keylength):
776
"""Create a factory for creating a pack based VersionedFiles.
778
This is only functional enough to run interface tests, it doesn't try to
779
provide a full pack environment.
781
:param graph: Store a graph.
782
:param delta: Delta compress contents.
783
:param keylength: How long should keys be.
785
def factory(transport):
786
parents = graph or delta
792
max_delta_chain = 200
795
graph_index = _mod_index.InMemoryGraphIndex(reference_lists=ref_length,
796
key_elements=keylength)
797
stream = transport.open_write_stream('newpack')
798
writer = pack.ContainerWriter(stream.write)
800
index = _KnitGraphIndex(graph_index, lambda:True, parents=parents,
801
deltas=delta, add_callback=graph_index.add_nodes)
802
access = _DirectPackAccess({})
803
access.set_writer(writer, graph_index, (transport, 'newpack'))
804
result = KnitVersionedFiles(index, access,
805
max_delta_chain=max_delta_chain)
806
result.stream = stream
807
result.writer = writer
812
def cleanup_pack_knit(versioned_files):
813
versioned_files.stream.close()
814
versioned_files.writer.end()
817
class KnitVersionedFiles(VersionedFiles):
818
"""Storage for many versioned files using knit compression.
820
Backend storage is managed by indices and data objects.
822
:ivar _index: A _KnitGraphIndex or similar that can describe the
823
parents, graph, compression and data location of entries in this
824
KnitVersionedFiles. Note that this is only the index for
825
*this* vfs; if there are fallbacks they must be queried separately.
828
def __init__(self, index, data_access, max_delta_chain=200,
829
annotated=False, reload_func=None):
830
"""Create a KnitVersionedFiles with index and data_access.
832
:param index: The index for the knit data.
833
:param data_access: The access object to store and retrieve knit
835
:param max_delta_chain: The maximum number of deltas to permit during
836
insertion. Set to 0 to prohibit the use of deltas.
837
:param annotated: Set to True to cause annotations to be calculated and
838
stored during insertion.
839
:param reload_func: An function that can be called if we think we need
840
to reload the pack listing and try again. See
841
'bzrlib.repofmt.pack_repo.AggregateIndex' for the signature.
844
self._access = data_access
845
self._max_delta_chain = max_delta_chain
847
self._factory = KnitAnnotateFactory()
849
self._factory = KnitPlainFactory()
850
self._fallback_vfs = []
851
self._reload_func = reload_func
854
return "%s(%r, %r)" % (
855
self.__class__.__name__,
859
def add_fallback_versioned_files(self, a_versioned_files):
860
"""Add a source of texts for texts not present in this knit.
862
:param a_versioned_files: A VersionedFiles object.
864
self._fallback_vfs.append(a_versioned_files)
866
def add_lines(self, key, parents, lines, parent_texts=None,
867
left_matching_blocks=None, nostore_sha=None, random_id=False,
869
"""See VersionedFiles.add_lines()."""
870
self._index._check_write_ok()
871
self._check_add(key, lines, random_id, check_content)
873
# The caller might pass None if there is no graph data, but kndx
874
# indexes can't directly store that, so we give them
875
# an empty tuple instead.
877
return self._add(key, lines, parents,
878
parent_texts, left_matching_blocks, nostore_sha, random_id)
880
def _add(self, key, lines, parents, parent_texts,
881
left_matching_blocks, nostore_sha, random_id):
882
"""Add a set of lines on top of version specified by parents.
884
Any versions not present will be converted into ghosts.
886
# first thing, if the content is something we don't need to store, find
888
line_bytes = ''.join(lines)
889
digest = sha_string(line_bytes)
890
if nostore_sha == digest:
891
raise errors.ExistingContent
894
if parent_texts is None:
896
# Do a single query to ascertain parent presence; we only compress
897
# against parents in the same kvf.
898
present_parent_map = self._index.get_parent_map(parents)
899
for parent in parents:
900
if parent in present_parent_map:
901
present_parents.append(parent)
903
# Currently we can only compress against the left most present parent.
904
if (len(present_parents) == 0 or
905
present_parents[0] != parents[0]):
908
# To speed the extract of texts the delta chain is limited
909
# to a fixed number of deltas. This should minimize both
910
# I/O and the time spend applying deltas.
911
delta = self._check_should_delta(present_parents[0])
913
text_length = len(line_bytes)
916
if lines[-1][-1] != '\n':
917
# copy the contents of lines.
919
options.append('no-eol')
920
lines[-1] = lines[-1] + '\n'
924
if type(element) != str:
925
raise TypeError("key contains non-strings: %r" % (key,))
926
# Knit hunks are still last-element only
928
content = self._factory.make(lines, version_id)
929
if 'no-eol' in options:
930
# Hint to the content object that its text() call should strip the
932
content._should_strip_eol = True
933
if delta or (self._factory.annotated and len(present_parents) > 0):
934
# Merge annotations from parent texts if needed.
935
delta_hunks = self._merge_annotations(content, present_parents,
936
parent_texts, delta, self._factory.annotated,
937
left_matching_blocks)
940
options.append('line-delta')
941
store_lines = self._factory.lower_line_delta(delta_hunks)
942
size, bytes = self._record_to_data(key, digest,
945
options.append('fulltext')
946
# isinstance is slower and we have no hierarchy.
947
if self._factory.__class__ == KnitPlainFactory:
948
# Use the already joined bytes saving iteration time in
950
size, bytes = self._record_to_data(key, digest,
953
# get mixed annotation + content and feed it into the
955
store_lines = self._factory.lower_fulltext(content)
956
size, bytes = self._record_to_data(key, digest,
959
access_memo = self._access.add_raw_records([(key, size)], bytes)[0]
960
self._index.add_records(
961
((key, options, access_memo, parents),),
963
return digest, text_length, content
965
def annotate(self, key):
966
"""See VersionedFiles.annotate."""
967
return self._factory.annotate(self, key)
969
def check(self, progress_bar=None):
970
"""See VersionedFiles.check()."""
971
# This doesn't actually test extraction of everything, but that will
972
# impact 'bzr check' substantially, and needs to be integrated with
973
# care. However, it does check for the obvious problem of a delta with
975
keys = self._index.keys()
976
parent_map = self.get_parent_map(keys)
978
if self._index.get_method(key) != 'fulltext':
979
compression_parent = parent_map[key][0]
980
if compression_parent not in parent_map:
981
raise errors.KnitCorrupt(self,
982
"Missing basis parent %s for %s" % (
983
compression_parent, key))
984
for fallback_vfs in self._fallback_vfs:
987
def _check_add(self, key, lines, random_id, check_content):
988
"""check that version_id and lines are safe to add."""
990
if contains_whitespace(version_id):
991
raise InvalidRevisionId(version_id, self)
992
self.check_not_reserved_id(version_id)
993
# TODO: If random_id==False and the key is already present, we should
994
# probably check that the existing content is identical to what is
995
# being inserted, and otherwise raise an exception. This would make
996
# the bundle code simpler.
998
self._check_lines_not_unicode(lines)
999
self._check_lines_are_lines(lines)
1001
def _check_header(self, key, line):
1002
rec = self._split_header(line)
1003
self._check_header_version(rec, key[-1])
1006
def _check_header_version(self, rec, version_id):
1007
"""Checks the header version on original format knit records.
1009
These have the last component of the key embedded in the record.
1011
if rec[1] != version_id:
1012
raise KnitCorrupt(self,
1013
'unexpected version, wanted %r, got %r' % (version_id, rec[1]))
1015
def _check_should_delta(self, parent):
1016
"""Iterate back through the parent listing, looking for a fulltext.
1018
This is used when we want to decide whether to add a delta or a new
1019
fulltext. It searches for _max_delta_chain parents. When it finds a
1020
fulltext parent, it sees if the total size of the deltas leading up to
1021
it is large enough to indicate that we want a new full text anyway.
1023
Return True if we should create a new delta, False if we should use a
1027
fulltext_size = None
1028
for count in xrange(self._max_delta_chain):
1030
# Note that this only looks in the index of this particular
1031
# KnitVersionedFiles, not in the fallbacks. This ensures that
1032
# we won't store a delta spanning physical repository
1034
build_details = self._index.get_build_details([parent])
1035
parent_details = build_details[parent]
1036
except (RevisionNotPresent, KeyError), e:
1037
# Some basis is not locally present: always fulltext
1039
index_memo, compression_parent, _, _ = parent_details
1040
_, _, size = index_memo
1041
if compression_parent is None:
1042
fulltext_size = size
1045
# We don't explicitly check for presence because this is in an
1046
# inner loop, and if it's missing it'll fail anyhow.
1047
parent = compression_parent
1049
# We couldn't find a fulltext, so we must create a new one
1051
# Simple heuristic - if the total I/O wold be greater as a delta than
1052
# the originally installed fulltext, we create a new fulltext.
1053
return fulltext_size > delta_size
1055
def _build_details_to_components(self, build_details):
1056
"""Convert a build_details tuple to a position tuple."""
1057
# record_details, access_memo, compression_parent
1058
return build_details[3], build_details[0], build_details[1]
1060
def _get_components_positions(self, keys, allow_missing=False):
1061
"""Produce a map of position data for the components of keys.
1063
This data is intended to be used for retrieving the knit records.
1065
A dict of key to (record_details, index_memo, next, parents) is
1067
method is the way referenced data should be applied.
1068
index_memo is the handle to pass to the data access to actually get the
1070
next is the build-parent of the version, or None for fulltexts.
1071
parents is the version_ids of the parents of this version
1073
:param allow_missing: If True do not raise an error on a missing component,
1077
pending_components = keys
1078
while pending_components:
1079
build_details = self._index.get_build_details(pending_components)
1080
current_components = set(pending_components)
1081
pending_components = set()
1082
for key, details in build_details.iteritems():
1083
(index_memo, compression_parent, parents,
1084
record_details) = details
1085
method = record_details[0]
1086
if compression_parent is not None:
1087
pending_components.add(compression_parent)
1088
component_data[key] = self._build_details_to_components(details)
1089
missing = current_components.difference(build_details)
1090
if missing and not allow_missing:
1091
raise errors.RevisionNotPresent(missing.pop(), self)
1092
return component_data
1094
def _get_content(self, key, parent_texts={}):
1095
"""Returns a content object that makes up the specified
1097
cached_version = parent_texts.get(key, None)
1098
if cached_version is not None:
1099
# Ensure the cache dict is valid.
1100
if not self.get_parent_map([key]):
1101
raise RevisionNotPresent(key, self)
1102
return cached_version
1103
generator = _VFContentMapGenerator(self, [key])
1104
return generator._get_content(key)
1106
def get_parent_map(self, keys):
1107
"""Get a map of the graph parents of keys.
1109
:param keys: The keys to look up parents for.
1110
:return: A mapping from keys to parents. Absent keys are absent from
1113
return self._get_parent_map_with_sources(keys)[0]
1115
def _get_parent_map_with_sources(self, keys):
1116
"""Get a map of the parents of keys.
1118
:param keys: The keys to look up parents for.
1119
:return: A tuple. The first element is a mapping from keys to parents.
1120
Absent keys are absent from the mapping. The second element is a
1121
list with the locations each key was found in. The first element
1122
is the in-this-knit parents, the second the first fallback source,
1126
sources = [self._index] + self._fallback_vfs
1129
for source in sources:
1132
new_result = source.get_parent_map(missing)
1133
source_results.append(new_result)
1134
result.update(new_result)
1135
missing.difference_update(set(new_result))
1136
return result, source_results
1138
def _get_record_map(self, keys, allow_missing=False):
1139
"""Produce a dictionary of knit records.
1141
:return: {key:(record, record_details, digest, next)}
1143
data returned from read_records (a KnitContentobject)
1145
opaque information to pass to parse_record
1147
SHA1 digest of the full text after all steps are done
1149
build-parent of the version, i.e. the leftmost ancestor.
1150
Will be None if the record is not a delta.
1151
:param keys: The keys to build a map for
1152
:param allow_missing: If some records are missing, rather than
1153
error, just return the data that could be generated.
1155
raw_map = self._get_record_map_unparsed(keys,
1156
allow_missing=allow_missing)
1157
return self._raw_map_to_record_map(raw_map)
1159
def _raw_map_to_record_map(self, raw_map):
1160
"""Parse the contents of _get_record_map_unparsed.
1162
:return: see _get_record_map.
1166
data, record_details, next = raw_map[key]
1167
content, digest = self._parse_record(key[-1], data)
1168
result[key] = content, record_details, digest, next
1171
def _get_record_map_unparsed(self, keys, allow_missing=False):
1172
"""Get the raw data for reconstructing keys without parsing it.
1174
:return: A dict suitable for parsing via _raw_map_to_record_map.
1175
key-> raw_bytes, (method, noeol), compression_parent
1177
# This retries the whole request if anything fails. Potentially we
1178
# could be a bit more selective. We could track the keys whose records
1179
# we have successfully found, and then only request the new records
1180
# from there. However, _get_components_positions grabs the whole build
1181
# chain, which means we'll likely try to grab the same records again
1182
# anyway. Also, can the build chains change as part of a pack
1183
# operation? We wouldn't want to end up with a broken chain.
1186
position_map = self._get_components_positions(keys,
1187
allow_missing=allow_missing)
1188
# key = component_id, r = record_details, i_m = index_memo,
1190
records = [(key, i_m) for key, (r, i_m, n)
1191
in position_map.iteritems()]
1193
for key, data in self._read_records_iter_unchecked(records):
1194
(record_details, index_memo, next) = position_map[key]
1195
raw_record_map[key] = data, record_details, next
1196
return raw_record_map
1197
except errors.RetryWithNewPacks, e:
1198
self._access.reload_or_raise(e)
1200
def _split_by_prefix(self, keys):
1201
"""For the given keys, split them up based on their prefix.
1203
To keep memory pressure somewhat under control, split the
1204
requests back into per-file-id requests, otherwise "bzr co"
1205
extracts the full tree into memory before writing it to disk.
1206
This should be revisited if _get_content_maps() can ever cross
1209
:param keys: An iterable of key tuples
1210
:return: A dict of {prefix: [key_list]}
1212
split_by_prefix = {}
1215
split_by_prefix.setdefault('', []).append(key)
1217
split_by_prefix.setdefault(key[0], []).append(key)
1218
return split_by_prefix
1220
def get_record_stream(self, keys, ordering, include_delta_closure):
1221
"""Get a stream of records for keys.
1223
:param keys: The keys to include.
1224
:param ordering: Either 'unordered' or 'topological'. A topologically
1225
sorted stream has compression parents strictly before their
1227
:param include_delta_closure: If True then the closure across any
1228
compression parents will be included (in the opaque data).
1229
:return: An iterator of ContentFactory objects, each of which is only
1230
valid until the iterator is advanced.
1232
# keys might be a generator
1236
if not self._index.has_graph:
1237
# Cannot topological order when no graph has been stored.
1238
ordering = 'unordered'
1240
remaining_keys = keys
1243
keys = set(remaining_keys)
1244
for content_factory in self._get_remaining_record_stream(keys,
1245
ordering, include_delta_closure):
1246
remaining_keys.discard(content_factory.key)
1247
yield content_factory
1249
except errors.RetryWithNewPacks, e:
1250
self._access.reload_or_raise(e)
1252
def _get_remaining_record_stream(self, keys, ordering,
1253
include_delta_closure):
1254
"""This function is the 'retry' portion for get_record_stream."""
1255
if include_delta_closure:
1256
positions = self._get_components_positions(keys, allow_missing=True)
1258
build_details = self._index.get_build_details(keys)
1260
# (record_details, access_memo, compression_parent_key)
1261
positions = dict((key, self._build_details_to_components(details))
1262
for key, details in build_details.iteritems())
1263
absent_keys = keys.difference(set(positions))
1264
# There may be more absent keys : if we're missing the basis component
1265
# and are trying to include the delta closure.
1266
# XXX: We should not ever need to examine remote sources because we do
1267
# not permit deltas across versioned files boundaries.
1268
if include_delta_closure:
1269
needed_from_fallback = set()
1270
# Build up reconstructable_keys dict. key:True in this dict means
1271
# the key can be reconstructed.
1272
reconstructable_keys = {}
1276
chain = [key, positions[key][2]]
1278
needed_from_fallback.add(key)
1281
while chain[-1] is not None:
1282
if chain[-1] in reconstructable_keys:
1283
result = reconstructable_keys[chain[-1]]
1287
chain.append(positions[chain[-1]][2])
1289
# missing basis component
1290
needed_from_fallback.add(chain[-1])
1293
for chain_key in chain[:-1]:
1294
reconstructable_keys[chain_key] = result
1296
needed_from_fallback.add(key)
1297
# Double index lookups here : need a unified api ?
1298
global_map, parent_maps = self._get_parent_map_with_sources(keys)
1299
if ordering == 'topological':
1300
# Global topological sort
1301
present_keys = tsort.topo_sort(global_map)
1302
# Now group by source:
1304
current_source = None
1305
for key in present_keys:
1306
for parent_map in parent_maps:
1307
if key in parent_map:
1308
key_source = parent_map
1310
if current_source is not key_source:
1311
source_keys.append((key_source, []))
1312
current_source = key_source
1313
source_keys[-1][1].append(key)
1315
if ordering != 'unordered':
1316
raise AssertionError('valid values for ordering are:'
1317
' "unordered" or "topological" not: %r'
1319
# Just group by source; remote sources first.
1322
for parent_map in reversed(parent_maps):
1323
source_keys.append((parent_map, []))
1324
for key in parent_map:
1325
present_keys.append(key)
1326
source_keys[-1][1].append(key)
1327
# We have been requested to return these records in an order that
1328
# suits us. So we ask the index to give us an optimally sorted
1330
for source, sub_keys in source_keys:
1331
if source is parent_maps[0]:
1332
# Only sort the keys for this VF
1333
self._index._sort_keys_by_io(sub_keys, positions)
1334
absent_keys = keys - set(global_map)
1335
for key in absent_keys:
1336
yield AbsentContentFactory(key)
1337
# restrict our view to the keys we can answer.
1338
# XXX: Memory: TODO: batch data here to cap buffered data at (say) 1MB.
1339
# XXX: At that point we need to consider the impact of double reads by
1340
# utilising components multiple times.
1341
if include_delta_closure:
1342
# XXX: get_content_maps performs its own index queries; allow state
1344
non_local_keys = needed_from_fallback - absent_keys
1345
prefix_split_keys = self._split_by_prefix(present_keys)
1346
prefix_split_non_local_keys = self._split_by_prefix(non_local_keys)
1347
for prefix, keys in prefix_split_keys.iteritems():
1348
non_local = prefix_split_non_local_keys.get(prefix, [])
1349
non_local = set(non_local)
1350
generator = _VFContentMapGenerator(self, keys, non_local,
1352
for record in generator.get_record_stream():
1355
for source, keys in source_keys:
1356
if source is parent_maps[0]:
1357
# this KnitVersionedFiles
1358
records = [(key, positions[key][1]) for key in keys]
1359
for key, raw_data, sha1 in self._read_records_iter_raw(records):
1360
(record_details, index_memo, _) = positions[key]
1361
yield KnitContentFactory(key, global_map[key],
1362
record_details, sha1, raw_data, self._factory.annotated, None)
1364
vf = self._fallback_vfs[parent_maps.index(source) - 1]
1365
for record in vf.get_record_stream(keys, ordering,
1366
include_delta_closure):
1369
def get_sha1s(self, keys):
1370
"""See VersionedFiles.get_sha1s()."""
1372
record_map = self._get_record_map(missing, allow_missing=True)
1374
for key, details in record_map.iteritems():
1375
if key not in missing:
1377
# record entry 2 is the 'digest'.
1378
result[key] = details[2]
1379
missing.difference_update(set(result))
1380
for source in self._fallback_vfs:
1383
new_result = source.get_sha1s(missing)
1384
result.update(new_result)
1385
missing.difference_update(set(new_result))
1388
def insert_record_stream(self, stream):
1389
"""Insert a record stream into this container.
1391
:param stream: A stream of records to insert.
1393
:seealso VersionedFiles.get_record_stream:
1395
def get_adapter(adapter_key):
1397
return adapters[adapter_key]
1399
adapter_factory = adapter_registry.get(adapter_key)
1400
adapter = adapter_factory(self)
1401
adapters[adapter_key] = adapter
1404
if self._factory.annotated:
1405
# self is annotated, we need annotated knits to use directly.
1406
annotated = "annotated-"
1409
# self is not annotated, but we can strip annotations cheaply.
1411
convertibles = set(["knit-annotated-ft-gz"])
1412
if self._max_delta_chain:
1413
delta_types.add("knit-annotated-delta-gz")
1414
convertibles.add("knit-annotated-delta-gz")
1415
# The set of types we can cheaply adapt without needing basis texts.
1416
native_types = set()
1417
if self._max_delta_chain:
1418
native_types.add("knit-%sdelta-gz" % annotated)
1419
delta_types.add("knit-%sdelta-gz" % annotated)
1420
native_types.add("knit-%sft-gz" % annotated)
1421
knit_types = native_types.union(convertibles)
1423
# Buffer all index entries that we can't add immediately because their
1424
# basis parent is missing. We don't buffer all because generating
1425
# annotations may require access to some of the new records. However we
1426
# can't generate annotations from new deltas until their basis parent
1427
# is present anyway, so we get away with not needing an index that
1428
# includes the new keys.
1430
# See <http://launchpad.net/bugs/300177> about ordering of compression
1431
# parents in the records - to be conservative, we insist that all
1432
# parents must be present to avoid expanding to a fulltext.
1434
# key = basis_parent, value = index entry to add
1435
buffered_index_entries = {}
1436
for record in stream:
1437
parents = record.parents
1438
if record.storage_kind in delta_types:
1439
# TODO: eventually the record itself should track
1440
# compression_parent
1441
compression_parent = parents[0]
1443
compression_parent = None
1444
# Raise an error when a record is missing.
1445
if record.storage_kind == 'absent':
1446
raise RevisionNotPresent([record.key], self)
1447
elif ((record.storage_kind in knit_types)
1448
and (compression_parent is None
1449
or not self._fallback_vfs
1450
or self._index.has_key(compression_parent)
1451
or not self.has_key(compression_parent))):
1452
# we can insert the knit record literally if either it has no
1453
# compression parent OR we already have its basis in this kvf
1454
# OR the basis is not present even in the fallbacks. In the
1455
# last case it will either turn up later in the stream and all
1456
# will be well, or it won't turn up at all and we'll raise an
1459
# TODO: self.has_key is somewhat redundant with
1460
# self._index.has_key; we really want something that directly
1461
# asks if it's only present in the fallbacks. -- mbp 20081119
1462
if record.storage_kind not in native_types:
1464
adapter_key = (record.storage_kind, "knit-delta-gz")
1465
adapter = get_adapter(adapter_key)
1467
adapter_key = (record.storage_kind, "knit-ft-gz")
1468
adapter = get_adapter(adapter_key)
1469
bytes = adapter.get_bytes(record)
1471
# It's a knit record, it has a _raw_record field (even if
1472
# it was reconstituted from a network stream).
1473
bytes = record._raw_record
1474
options = [record._build_details[0]]
1475
if record._build_details[1]:
1476
options.append('no-eol')
1477
# Just blat it across.
1478
# Note: This does end up adding data on duplicate keys. As
1479
# modern repositories use atomic insertions this should not
1480
# lead to excessive growth in the event of interrupted fetches.
1481
# 'knit' repositories may suffer excessive growth, but as a
1482
# deprecated format this is tolerable. It can be fixed if
1483
# needed by in the kndx index support raising on a duplicate
1484
# add with identical parents and options.
1485
access_memo = self._access.add_raw_records(
1486
[(record.key, len(bytes))], bytes)[0]
1487
index_entry = (record.key, options, access_memo, parents)
1489
if 'fulltext' not in options:
1490
# Not a fulltext, so we need to make sure the compression
1491
# parent will also be present.
1492
# Note that pack backed knits don't need to buffer here
1493
# because they buffer all writes to the transaction level,
1494
# but we don't expose that difference at the index level. If
1495
# the query here has sufficient cost to show up in
1496
# profiling we should do that.
1498
# They're required to be physically in this
1499
# KnitVersionedFiles, not in a fallback.
1500
if not self._index.has_key(compression_parent):
1501
pending = buffered_index_entries.setdefault(
1502
compression_parent, [])
1503
pending.append(index_entry)
1506
self._index.add_records([index_entry])
1507
elif record.storage_kind == 'chunked':
1508
self.add_lines(record.key, parents,
1509
osutils.chunks_to_lines(record.get_bytes_as('chunked')))
1511
# Not suitable for direct insertion as a
1512
# delta, either because it's not the right format, or this
1513
# KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
1514
# 0) or because it depends on a base only present in the
1517
# Try getting a fulltext directly from the record.
1518
bytes = record.get_bytes_as('fulltext')
1519
except errors.UnavailableRepresentation:
1520
adapter_key = record.storage_kind, 'fulltext'
1521
adapter = get_adapter(adapter_key)
1522
bytes = adapter.get_bytes(record)
1523
lines = split_lines(bytes)
1525
self.add_lines(record.key, parents, lines)
1526
except errors.RevisionAlreadyPresent:
1528
# Add any records whose basis parent is now available.
1529
added_keys = [record.key]
1531
key = added_keys.pop(0)
1532
if key in buffered_index_entries:
1533
index_entries = buffered_index_entries[key]
1534
self._index.add_records(index_entries)
1536
[index_entry[0] for index_entry in index_entries])
1537
del buffered_index_entries[key]
1538
# If there were any deltas which had a missing basis parent, error.
1539
if buffered_index_entries:
1540
from pprint import pformat
1541
raise errors.BzrCheckError(
1542
"record_stream refers to compression parents not in %r:\n%s"
1543
% (self, pformat(sorted(buffered_index_entries.keys()))))
1545
def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1546
"""Iterate over the lines in the versioned files from keys.
1548
This may return lines from other keys. Each item the returned
1549
iterator yields is a tuple of a line and a text version that that line
1550
is present in (not introduced in).
1552
Ordering of results is in whatever order is most suitable for the
1553
underlying storage format.
1555
If a progress bar is supplied, it may be used to indicate progress.
1556
The caller is responsible for cleaning up progress bars (because this
1560
* Lines are normalised by the underlying store: they will all have \\n
1562
* Lines are returned in arbitrary order.
1563
* If a requested key did not change any lines (or didn't have any
1564
lines), it may not be mentioned at all in the result.
1566
:return: An iterator over (line, key).
1569
pb = progress.DummyProgress()
1575
# we don't care about inclusions, the caller cares.
1576
# but we need to setup a list of records to visit.
1577
# we need key, position, length
1579
build_details = self._index.get_build_details(keys)
1580
for key, details in build_details.iteritems():
1582
key_records.append((key, details[0]))
1583
records_iter = enumerate(self._read_records_iter(key_records))
1584
for (key_idx, (key, data, sha_value)) in records_iter:
1585
pb.update('Walking content.', key_idx, total)
1586
compression_parent = build_details[key][1]
1587
if compression_parent is None:
1589
line_iterator = self._factory.get_fulltext_content(data)
1592
line_iterator = self._factory.get_linedelta_content(data)
1593
# Now that we are yielding the data for this key, remove it
1596
# XXX: It might be more efficient to yield (key,
1597
# line_iterator) in the future. However for now, this is a
1598
# simpler change to integrate into the rest of the
1599
# codebase. RBC 20071110
1600
for line in line_iterator:
1603
except errors.RetryWithNewPacks, e:
1604
self._access.reload_or_raise(e)
1605
# If there are still keys we've not yet found, we look in the fallback
1606
# vfs, and hope to find them there. Note that if the keys are found
1607
# but had no changes or no content, the fallback may not return
1609
if keys and not self._fallback_vfs:
1610
# XXX: strictly the second parameter is meant to be the file id
1611
# but it's not easily accessible here.
1612
raise RevisionNotPresent(keys, repr(self))
1613
for source in self._fallback_vfs:
1617
for line, key in source.iter_lines_added_or_present_in_keys(keys):
1618
source_keys.add(key)
1620
keys.difference_update(source_keys)
1621
pb.update('Walking content.', total, total)
1623
def _make_line_delta(self, delta_seq, new_content):
1624
"""Generate a line delta from delta_seq and new_content."""
1626
for op in delta_seq.get_opcodes():
1627
if op[0] == 'equal':
1629
diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
1632
def _merge_annotations(self, content, parents, parent_texts={},
1633
delta=None, annotated=None,
1634
left_matching_blocks=None):
1635
"""Merge annotations for content and generate deltas.
1637
This is done by comparing the annotations based on changes to the text
1638
and generating a delta on the resulting full texts. If annotations are
1639
not being created then a simple delta is created.
1641
if left_matching_blocks is not None:
1642
delta_seq = diff._PrematchedMatcher(left_matching_blocks)
1646
for parent_key in parents:
1647
merge_content = self._get_content(parent_key, parent_texts)
1648
if (parent_key == parents[0] and delta_seq is not None):
1651
seq = patiencediff.PatienceSequenceMatcher(
1652
None, merge_content.text(), content.text())
1653
for i, j, n in seq.get_matching_blocks():
1656
# this copies (origin, text) pairs across to the new
1657
# content for any line that matches the last-checked
1659
content._lines[j:j+n] = merge_content._lines[i:i+n]
1660
# XXX: Robert says the following block is a workaround for a
1661
# now-fixed bug and it can probably be deleted. -- mbp 20080618
1662
if content._lines and content._lines[-1][1][-1] != '\n':
1663
# The copied annotation was from a line without a trailing EOL,
1664
# reinstate one for the content object, to ensure correct
1666
line = content._lines[-1][1] + '\n'
1667
content._lines[-1] = (content._lines[-1][0], line)
1669
if delta_seq is None:
1670
reference_content = self._get_content(parents[0], parent_texts)
1671
new_texts = content.text()
1672
old_texts = reference_content.text()
1673
delta_seq = patiencediff.PatienceSequenceMatcher(
1674
None, old_texts, new_texts)
1675
return self._make_line_delta(delta_seq, content)
1677
def _parse_record(self, version_id, data):
1678
"""Parse an original format knit record.
1680
These have the last element of the key only present in the stored data.
1682
rec, record_contents = self._parse_record_unchecked(data)
1683
self._check_header_version(rec, version_id)
1684
return record_contents, rec[3]
1686
def _parse_record_header(self, key, raw_data):
1687
"""Parse a record header for consistency.
1689
:return: the header and the decompressor stream.
1690
as (stream, header_record)
1692
df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
1695
rec = self._check_header(key, df.readline())
1696
except Exception, e:
1697
raise KnitCorrupt(self,
1698
"While reading {%s} got %s(%s)"
1699
% (key, e.__class__.__name__, str(e)))
1702
def _parse_record_unchecked(self, data):
1704
# 4168 calls in 2880 217 internal
1705
# 4168 calls to _parse_record_header in 2121
1706
# 4168 calls to readlines in 330
1707
df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(data))
1709
record_contents = df.readlines()
1710
except Exception, e:
1711
raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1712
(data, e.__class__.__name__, str(e)))
1713
header = record_contents.pop(0)
1714
rec = self._split_header(header)
1715
last_line = record_contents.pop()
1716
if len(record_contents) != int(rec[2]):
1717
raise KnitCorrupt(self,
1718
'incorrect number of lines %s != %s'
1719
' for version {%s} %s'
1720
% (len(record_contents), int(rec[2]),
1721
rec[1], record_contents))
1722
if last_line != 'end %s\n' % rec[1]:
1723
raise KnitCorrupt(self,
1724
'unexpected version end line %r, wanted %r'
1725
% (last_line, rec[1]))
1727
return rec, record_contents
1729
def _read_records_iter(self, records):
1730
"""Read text records from data file and yield result.
1732
The result will be returned in whatever is the fastest to read.
1733
Not by the order requested. Also, multiple requests for the same
1734
record will only yield 1 response.
1735
:param records: A list of (key, access_memo) entries
1736
:return: Yields (key, contents, digest) in the order
1737
read, not the order requested
1742
# XXX: This smells wrong, IO may not be getting ordered right.
1743
needed_records = sorted(set(records), key=operator.itemgetter(1))
1744
if not needed_records:
1747
# The transport optimizes the fetching as well
1748
# (ie, reads continuous ranges.)
1749
raw_data = self._access.get_raw_records(
1750
[index_memo for key, index_memo in needed_records])
1752
for (key, index_memo), data in \
1753
izip(iter(needed_records), raw_data):
1754
content, digest = self._parse_record(key[-1], data)
1755
yield key, content, digest
1757
def _read_records_iter_raw(self, records):
1758
"""Read text records from data file and yield raw data.
1760
This unpacks enough of the text record to validate the id is
1761
as expected but thats all.
1763
Each item the iterator yields is (key, bytes,
1764
expected_sha1_of_full_text).
1766
for key, data in self._read_records_iter_unchecked(records):
1767
# validate the header (note that we can only use the suffix in
1768
# current knit records).
1769
df, rec = self._parse_record_header(key, data)
1771
yield key, data, rec[3]
1773
def _read_records_iter_unchecked(self, records):
1774
"""Read text records from data file and yield raw data.
1776
No validation is done.
1778
Yields tuples of (key, data).
1780
# setup an iterator of the external records:
1781
# uses readv so nice and fast we hope.
1783
# grab the disk data needed.
1784
needed_offsets = [index_memo for key, index_memo
1786
raw_records = self._access.get_raw_records(needed_offsets)
1788
for key, index_memo in records:
1789
data = raw_records.next()
1792
def _record_to_data(self, key, digest, lines, dense_lines=None):
1793
"""Convert key, digest, lines into a raw data block.
1795
:param key: The key of the record. Currently keys are always serialised
1796
using just the trailing component.
1797
:param dense_lines: The bytes of lines but in a denser form. For
1798
instance, if lines is a list of 1000 bytestrings each ending in \n,
1799
dense_lines may be a list with one line in it, containing all the
1800
1000's lines and their \n's. Using dense_lines if it is already
1801
known is a win because the string join to create bytes in this
1802
function spends less time resizing the final string.
1803
:return: (len, a StringIO instance with the raw data ready to read.)
1805
# Note: using a string copy here increases memory pressure with e.g.
1806
# ISO's, but it is about 3 seconds faster on a 1.2Ghz intel machine
1807
# when doing the initial commit of a mozilla tree. RBC 20070921
1808
bytes = ''.join(chain(
1809
["version %s %d %s\n" % (key[-1],
1812
dense_lines or lines,
1813
["end %s\n" % key[-1]]))
1814
if type(bytes) != str:
1815
raise AssertionError(
1816
'data must be plain bytes was %s' % type(bytes))
1817
if lines and lines[-1][-1] != '\n':
1818
raise ValueError('corrupt lines value %r' % lines)
1819
compressed_bytes = tuned_gzip.bytes_to_gzip(bytes)
1820
return len(compressed_bytes), compressed_bytes
1822
def _split_header(self, line):
1825
raise KnitCorrupt(self,
1826
'unexpected number of elements in record header')
1830
"""See VersionedFiles.keys."""
1831
if 'evil' in debug.debug_flags:
1832
trace.mutter_callsite(2, "keys scales with size of history")
1833
sources = [self._index] + self._fallback_vfs
1835
for source in sources:
1836
result.update(source.keys())
1840
class _ContentMapGenerator(object):
1841
"""Generate texts or expose raw deltas for a set of texts."""
1843
def _get_content(self, key):
1844
"""Get the content object for key."""
1845
# Note that _get_content is only called when the _ContentMapGenerator
1846
# has been constructed with just one key requested for reconstruction.
1847
if key in self.nonlocal_keys:
1848
record = self.get_record_stream().next()
1849
# Create a content object on the fly
1850
lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
1851
return PlainKnitContent(lines, record.key)
1853
# local keys we can ask for directly
1854
return self._get_one_work(key)
1856
def get_record_stream(self):
1857
"""Get a record stream for the keys requested during __init__."""
1858
for record in self._work():
1862
"""Produce maps of text and KnitContents as dicts.
1864
:return: (text_map, content_map) where text_map contains the texts for
1865
the requested versions and content_map contains the KnitContents.
1867
# NB: By definition we never need to read remote sources unless texts
1868
# are requested from them: we don't delta across stores - and we
1869
# explicitly do not want to to prevent data loss situations.
1870
if self.global_map is None:
1871
self.global_map = self.vf.get_parent_map(self.keys)
1872
nonlocal_keys = self.nonlocal_keys
1874
missing_keys = set(nonlocal_keys)
1875
# Read from remote versioned file instances and provide to our caller.
1876
for source in self.vf._fallback_vfs:
1877
if not missing_keys:
1879
# Loop over fallback repositories asking them for texts - ignore
1880
# any missing from a particular fallback.
1881
for record in source.get_record_stream(missing_keys,
1883
if record.storage_kind == 'absent':
1884
# Not in thie particular stream, may be in one of the
1885
# other fallback vfs objects.
1887
missing_keys.remove(record.key)
1890
self._raw_record_map = self.vf._get_record_map_unparsed(self.keys,
1893
for key in self.keys:
1894
if key in self.nonlocal_keys:
1896
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
1899
def _get_one_work(self, requested_key):
1900
# Now, if we have calculated everything already, just return the
1902
if requested_key in self._contents_map:
1903
return self._contents_map[requested_key]
1904
# To simplify things, parse everything at once - code that wants one text
1905
# probably wants them all.
1906
# FUTURE: This function could be improved for the 'extract many' case
1907
# by tracking each component and only doing the copy when the number of
1908
# children than need to apply delta's to it is > 1 or it is part of the
1910
multiple_versions = len(self.keys) != 1
1911
if self._record_map is None:
1912
self._record_map = self.vf._raw_map_to_record_map(
1913
self._raw_record_map)
1914
record_map = self._record_map
1915
# raw_record_map is key:
1916
# Have read and parsed records at this point.
1917
for key in self.keys:
1918
if key in self.nonlocal_keys:
1923
while cursor is not None:
1925
record, record_details, digest, next = record_map[cursor]
1927
raise RevisionNotPresent(cursor, self)
1928
components.append((cursor, record, record_details, digest))
1930
if cursor in self._contents_map:
1931
# no need to plan further back
1932
components.append((cursor, None, None, None))
1936
for (component_id, record, record_details,
1937
digest) in reversed(components):
1938
if component_id in self._contents_map:
1939
content = self._contents_map[component_id]
1941
content, delta = self._factory.parse_record(key[-1],
1942
record, record_details, content,
1943
copy_base_content=multiple_versions)
1944
if multiple_versions:
1945
self._contents_map[component_id] = content
1947
# digest here is the digest from the last applied component.
1948
text = content.text()
1949
actual_sha = sha_strings(text)
1950
if actual_sha != digest:
1951
raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
1952
if multiple_versions:
1953
return self._contents_map[requested_key]
1957
def _wire_bytes(self):
1958
"""Get the bytes to put on the wire for 'key'.
1960
The first collection of bytes asked for returns the serialised
1961
raw_record_map and the additional details (key, parent) for key.
1962
Subsequent calls return just the additional details (key, parent).
1963
The wire storage_kind given for the first key is 'knit-delta-closure',
1964
For subsequent keys it is 'knit-delta-closure-ref'.
1966
:param key: A key from the content generator.
1967
:return: Bytes to put on the wire.
1970
# kind marker for dispatch on the far side,
1971
lines.append('knit-delta-closure')
1973
if self.vf._factory.annotated:
1974
lines.append('annotated')
1977
# then the list of keys
1978
lines.append('\t'.join(['\x00'.join(key) for key in self.keys
1979
if key not in self.nonlocal_keys]))
1980
# then the _raw_record_map in serialised form:
1982
# for each item in the map:
1984
# 1 line with parents if the key is to be yielded (None: for None, '' for ())
1985
# one line with method
1986
# one line with noeol
1987
# one line with next ('' for None)
1988
# one line with byte count of the record bytes
1990
for key, (record_bytes, (method, noeol), next) in \
1991
self._raw_record_map.iteritems():
1992
key_bytes = '\x00'.join(key)
1993
parents = self.global_map.get(key, None)
1995
parent_bytes = 'None:'
1997
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
1998
method_bytes = method
2004
next_bytes = '\x00'.join(next)
2007
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2008
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2009
len(record_bytes), record_bytes))
2010
map_bytes = ''.join(map_byte_list)
2011
lines.append(map_bytes)
2012
bytes = '\n'.join(lines)
2016
class _VFContentMapGenerator(_ContentMapGenerator):
2017
"""Content map generator reading from a VersionedFiles object."""
2019
def __init__(self, versioned_files, keys, nonlocal_keys=None,
2020
global_map=None, raw_record_map=None):
2021
"""Create a _ContentMapGenerator.
2023
:param versioned_files: The versioned files that the texts are being
2025
:param keys: The keys to produce content maps for.
2026
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2027
which are known to not be in this knit, but rather in one of the
2029
:param global_map: The result of get_parent_map(keys) (or a supermap).
2030
This is required if get_record_stream() is to be used.
2031
:param raw_record_map: A unparsed raw record map to use for answering
2034
# The vf to source data from
2035
self.vf = versioned_files
2037
self.keys = list(keys)
2038
# Keys known to be in fallback vfs objects
2039
if nonlocal_keys is None:
2040
self.nonlocal_keys = set()
2042
self.nonlocal_keys = frozenset(nonlocal_keys)
2043
# Parents data for keys to be returned in get_record_stream
2044
self.global_map = global_map
2045
# The chunked lists for self.keys in text form
2047
# A cache of KnitContent objects used in extracting texts.
2048
self._contents_map = {}
2049
# All the knit records needed to assemble the requested keys as full
2051
self._record_map = None
2052
if raw_record_map is None:
2053
self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2056
self._raw_record_map = raw_record_map
2057
# the factory for parsing records
2058
self._factory = self.vf._factory
2061
class _NetworkContentMapGenerator(_ContentMapGenerator):
2062
"""Content map generator sourced from a network stream."""
2064
def __init__(self, bytes, line_end):
2065
"""Construct a _NetworkContentMapGenerator from a bytes block."""
2067
self.global_map = {}
2068
self._raw_record_map = {}
2069
self._contents_map = {}
2070
self._record_map = None
2071
self.nonlocal_keys = []
2072
# Get access to record parsing facilities
2073
self.vf = KnitVersionedFiles(None, None)
2076
line_end = bytes.find('\n', start)
2077
line = bytes[start:line_end]
2078
start = line_end + 1
2079
if line == 'annotated':
2080
self._factory = KnitAnnotateFactory()
2082
self._factory = KnitPlainFactory()
2083
# list of keys to emit in get_record_stream
2084
line_end = bytes.find('\n', start)
2085
line = bytes[start:line_end]
2086
start = line_end + 1
2088
tuple(segment.split('\x00')) for segment in line.split('\t')
2090
# now a loop until the end. XXX: It would be nice if this was just a
2091
# bunch of the same records as get_record_stream(..., False) gives, but
2092
# there is a decent sized gap stopping that at the moment.
2096
line_end = bytes.find('\n', start)
2097
key = tuple(bytes[start:line_end].split('\x00'))
2098
start = line_end + 1
2099
# 1 line with parents (None: for None, '' for ())
2100
line_end = bytes.find('\n', start)
2101
line = bytes[start:line_end]
2106
[tuple(segment.split('\x00')) for segment in line.split('\t')
2108
self.global_map[key] = parents
2109
start = line_end + 1
2110
# one line with method
2111
line_end = bytes.find('\n', start)
2112
line = bytes[start:line_end]
2114
start = line_end + 1
2115
# one line with noeol
2116
line_end = bytes.find('\n', start)
2117
line = bytes[start:line_end]
2119
start = line_end + 1
2120
# one line with next ('' for None)
2121
line_end = bytes.find('\n', start)
2122
line = bytes[start:line_end]
2126
next = tuple(bytes[start:line_end].split('\x00'))
2127
start = line_end + 1
2128
# one line with byte count of the record bytes
2129
line_end = bytes.find('\n', start)
2130
line = bytes[start:line_end]
2132
start = line_end + 1
2134
record_bytes = bytes[start:start+count]
2135
start = start + count
2137
self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2139
def get_record_stream(self):
2140
"""Get a record stream for for keys requested by the bytestream."""
2142
for key in self.keys:
2143
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2146
def _wire_bytes(self):
2150
class _KndxIndex(object):
2151
"""Manages knit index files
2153
The index is kept in memory and read on startup, to enable
2154
fast lookups of revision information. The cursor of the index
2155
file is always pointing to the end, making it easy to append
2158
_cache is a cache for fast mapping from version id to a Index
2161
_history is a cache for fast mapping from indexes to version ids.
2163
The index data format is dictionary compressed when it comes to
2164
parent references; a index entry may only have parents that with a
2165
lover index number. As a result, the index is topological sorted.
2167
Duplicate entries may be written to the index for a single version id
2168
if this is done then the latter one completely replaces the former:
2169
this allows updates to correct version and parent information.
2170
Note that the two entries may share the delta, and that successive
2171
annotations and references MUST point to the first entry.
2173
The index file on disc contains a header, followed by one line per knit
2174
record. The same revision can be present in an index file more than once.
2175
The first occurrence gets assigned a sequence number starting from 0.
2177
The format of a single line is
2178
REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
2179
REVISION_ID is a utf8-encoded revision id
2180
FLAGS is a comma separated list of flags about the record. Values include
2181
no-eol, line-delta, fulltext.
2182
BYTE_OFFSET is the ascii representation of the byte offset in the data file
2183
that the the compressed data starts at.
2184
LENGTH is the ascii representation of the length of the data file.
2185
PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
2187
PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
2188
revision id already in the knit that is a parent of REVISION_ID.
2189
The ' :' marker is the end of record marker.
2192
when a write is interrupted to the index file, it will result in a line
2193
that does not end in ' :'. If the ' :' is not present at the end of a line,
2194
or at the end of the file, then the record that is missing it will be
2195
ignored by the parser.
2197
When writing new records to the index file, the data is preceded by '\n'
2198
to ensure that records always start on new lines even if the last write was
2199
interrupted. As a result its normal for the last line in the index to be
2200
missing a trailing newline. One can be added with no harmful effects.
2202
:ivar _kndx_cache: dict from prefix to the old state of KnitIndex objects,
2203
where prefix is e.g. the (fileid,) for .texts instances or () for
2204
constant-mapped things like .revisions, and the old state is
2205
tuple(history_vector, cache_dict). This is used to prevent having an
2206
ABI change with the C extension that reads .kndx files.
2209
HEADER = "# bzr knit index 8\n"
2211
def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
2212
"""Create a _KndxIndex on transport using mapper."""
2213
self._transport = transport
2214
self._mapper = mapper
2215
self._get_scope = get_scope
2216
self._allow_writes = allow_writes
2217
self._is_locked = is_locked
2219
self.has_graph = True
2221
def add_records(self, records, random_id=False):
2222
"""Add multiple records to the index.
2224
:param records: a list of tuples:
2225
(key, options, access_memo, parents).
2226
:param random_id: If True the ids being added were randomly generated
2227
and no check for existence will be performed.
2230
for record in records:
2233
path = self._mapper.map(key) + '.kndx'
2234
path_keys = paths.setdefault(path, (prefix, []))
2235
path_keys[1].append(record)
2236
for path in sorted(paths):
2237
prefix, path_keys = paths[path]
2238
self._load_prefixes([prefix])
2240
orig_history = self._kndx_cache[prefix][1][:]
2241
orig_cache = self._kndx_cache[prefix][0].copy()
2244
for key, options, (_, pos, size), parents in path_keys:
2246
# kndx indices cannot be parentless.
2248
line = "\n%s %s %s %s %s :" % (
2249
key[-1], ','.join(options), pos, size,
2250
self._dictionary_compress(parents))
2251
if type(line) != str:
2252
raise AssertionError(
2253
'data must be utf8 was %s' % type(line))
2255
self._cache_key(key, options, pos, size, parents)
2256
if len(orig_history):
2257
self._transport.append_bytes(path, ''.join(lines))
2259
self._init_index(path, lines)
2261
# If any problems happen, restore the original values and re-raise
2262
self._kndx_cache[prefix] = (orig_cache, orig_history)
2265
def scan_unvalidated_index(self, graph_index):
2266
"""See _KnitGraphIndex.scan_unvalidated_index."""
2267
# Because kndx files do not support atomic insertion via separate index
2268
# files, they do not support this method.
2269
raise NotImplementedError(self.scan_unvalidated_index)
2271
def get_missing_compression_parents(self):
2272
"""See _KnitGraphIndex.get_missing_compression_parents."""
2273
# Because kndx files do not support atomic insertion via separate index
2274
# files, they do not support this method.
2275
raise NotImplementedError(self.get_missing_compression_parents)
2277
def _cache_key(self, key, options, pos, size, parent_keys):
2278
"""Cache a version record in the history array and index cache.
2280
This is inlined into _load_data for performance. KEEP IN SYNC.
2281
(It saves 60ms, 25% of the __init__ overhead on local 4000 record
2285
version_id = key[-1]
2286
# last-element only for compatibilty with the C load_data.
2287
parents = tuple(parent[-1] for parent in parent_keys)
2288
for parent in parent_keys:
2289
if parent[:-1] != prefix:
2290
raise ValueError("mismatched prefixes for %r, %r" % (
2292
cache, history = self._kndx_cache[prefix]
2293
# only want the _history index to reference the 1st index entry
2295
if version_id not in cache:
2296
index = len(history)
2297
history.append(version_id)
2299
index = cache[version_id][5]
2300
cache[version_id] = (version_id,
2307
def check_header(self, fp):
2308
line = fp.readline()
2310
# An empty file can actually be treated as though the file doesn't
2312
raise errors.NoSuchFile(self)
2313
if line != self.HEADER:
2314
raise KnitHeaderError(badline=line, filename=self)
2316
def _check_read(self):
2317
if not self._is_locked():
2318
raise errors.ObjectNotLocked(self)
2319
if self._get_scope() != self._scope:
2322
def _check_write_ok(self):
2323
"""Assert if not writes are permitted."""
2324
if not self._is_locked():
2325
raise errors.ObjectNotLocked(self)
2326
if self._get_scope() != self._scope:
2328
if self._mode != 'w':
2329
raise errors.ReadOnlyObjectDirtiedError(self)
2331
def get_build_details(self, keys):
2332
"""Get the method, index_memo and compression parent for keys.
2334
Ghosts are omitted from the result.
2336
:param keys: An iterable of keys.
2337
:return: A dict of key:(index_memo, compression_parent, parents,
2340
opaque structure to pass to read_records to extract the raw
2343
Content that this record is built upon, may be None
2345
Logical parents of this node
2347
extra information about the content which needs to be passed to
2348
Factory.parse_record
2350
parent_map = self.get_parent_map(keys)
2353
if key not in parent_map:
2355
method = self.get_method(key)
2356
parents = parent_map[key]
2357
if method == 'fulltext':
2358
compression_parent = None
2360
compression_parent = parents[0]
2361
noeol = 'no-eol' in self.get_options(key)
2362
index_memo = self.get_position(key)
2363
result[key] = (index_memo, compression_parent,
2364
parents, (method, noeol))
2367
def get_method(self, key):
2368
"""Return compression method of specified key."""
2369
options = self.get_options(key)
2370
if 'fulltext' in options:
2372
elif 'line-delta' in options:
2375
raise errors.KnitIndexUnknownMethod(self, options)
2377
def get_options(self, key):
2378
"""Return a list representing options.
2382
prefix, suffix = self._split_key(key)
2383
self._load_prefixes([prefix])
2385
return self._kndx_cache[prefix][0][suffix][1]
2387
raise RevisionNotPresent(key, self)
2389
def get_parent_map(self, keys):
2390
"""Get a map of the parents of keys.
2392
:param keys: The keys to look up parents for.
2393
:return: A mapping from keys to parents. Absent keys are absent from
2396
# Parse what we need to up front, this potentially trades off I/O
2397
# locality (.kndx and .knit in the same block group for the same file
2398
# id) for less checking in inner loops.
2399
prefixes = set(key[:-1] for key in keys)
2400
self._load_prefixes(prefixes)
2405
suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
2409
result[key] = tuple(prefix + (suffix,) for
2410
suffix in suffix_parents)
2413
def get_position(self, key):
2414
"""Return details needed to access the version.
2416
:return: a tuple (key, data position, size) to hand to the access
2417
logic to get the record.
2419
prefix, suffix = self._split_key(key)
2420
self._load_prefixes([prefix])
2421
entry = self._kndx_cache[prefix][0][suffix]
2422
return key, entry[2], entry[3]
2424
has_key = _mod_index._has_key_from_parent_map
2426
def _init_index(self, path, extra_lines=[]):
2427
"""Initialize an index."""
2429
sio.write(self.HEADER)
2430
sio.writelines(extra_lines)
2432
self._transport.put_file_non_atomic(path, sio,
2433
create_parent_dir=True)
2434
# self._create_parent_dir)
2435
# mode=self._file_mode,
2436
# dir_mode=self._dir_mode)
2439
"""Get all the keys in the collection.
2441
The keys are not ordered.
2444
# Identify all key prefixes.
2445
# XXX: A bit hacky, needs polish.
2446
if type(self._mapper) == ConstantMapper:
2450
for quoted_relpath in self._transport.iter_files_recursive():
2451
path, ext = os.path.splitext(quoted_relpath)
2453
prefixes = [self._mapper.unmap(path) for path in relpaths]
2454
self._load_prefixes(prefixes)
2455
for prefix in prefixes:
2456
for suffix in self._kndx_cache[prefix][1]:
2457
result.add(prefix + (suffix,))
2460
def _load_prefixes(self, prefixes):
2461
"""Load the indices for prefixes."""
2463
for prefix in prefixes:
2464
if prefix not in self._kndx_cache:
2465
# the load_data interface writes to these variables.
2468
self._filename = prefix
2470
path = self._mapper.map(prefix) + '.kndx'
2471
fp = self._transport.get(path)
2473
# _load_data may raise NoSuchFile if the target knit is
2475
_load_data(self, fp)
2478
self._kndx_cache[prefix] = (self._cache, self._history)
2483
self._kndx_cache[prefix] = ({}, [])
2484
if type(self._mapper) == ConstantMapper:
2485
# preserve behaviour for revisions.kndx etc.
2486
self._init_index(path)
2491
missing_keys = _mod_index._missing_keys_from_parent_map
2493
def _partition_keys(self, keys):
2494
"""Turn keys into a dict of prefix:suffix_list."""
2497
prefix_keys = result.setdefault(key[:-1], [])
2498
prefix_keys.append(key[-1])
2501
def _dictionary_compress(self, keys):
2502
"""Dictionary compress keys.
2504
:param keys: The keys to generate references to.
2505
:return: A string representation of keys. keys which are present are
2506
dictionary compressed, and others are emitted as fulltext with a
2512
prefix = keys[0][:-1]
2513
cache = self._kndx_cache[prefix][0]
2515
if key[:-1] != prefix:
2516
# kndx indices cannot refer across partitioned storage.
2517
raise ValueError("mismatched prefixes for %r" % keys)
2518
if key[-1] in cache:
2519
# -- inlined lookup() --
2520
result_list.append(str(cache[key[-1]][5]))
2521
# -- end lookup () --
2523
result_list.append('.' + key[-1])
2524
return ' '.join(result_list)
2526
def _reset_cache(self):
2527
# Possibly this should be a LRU cache. A dictionary from key_prefix to
2528
# (cache_dict, history_vector) for parsed kndx files.
2529
self._kndx_cache = {}
2530
self._scope = self._get_scope()
2531
allow_writes = self._allow_writes()
2537
def _sort_keys_by_io(self, keys, positions):
2538
"""Figure out an optimal order to read the records for the given keys.
2540
Sort keys, grouped by index and sorted by position.
2542
:param keys: A list of keys whose records we want to read. This will be
2544
:param positions: A dict, such as the one returned by
2545
_get_components_positions()
2548
def get_sort_key(key):
2549
index_memo = positions[key][1]
2550
# Group by prefix and position. index_memo[0] is the key, so it is
2551
# (file_id, revision_id) and we don't want to sort on revision_id,
2552
# index_memo[1] is the position, and index_memo[2] is the size,
2553
# which doesn't matter for the sort
2554
return index_memo[0][:-1], index_memo[1]
2555
return keys.sort(key=get_sort_key)
2557
def _split_key(self, key):
2558
"""Split key into a prefix and suffix."""
2559
return key[:-1], key[-1]
2562
class _KnitGraphIndex(object):
2563
"""A KnitVersionedFiles index layered on GraphIndex."""
2565
def __init__(self, graph_index, is_locked, deltas=False, parents=True,
2567
"""Construct a KnitGraphIndex on a graph_index.
2569
:param graph_index: An implementation of bzrlib.index.GraphIndex.
2570
:param is_locked: A callback to check whether the object should answer
2572
:param deltas: Allow delta-compressed records.
2573
:param parents: If True, record knits parents, if not do not record
2575
:param add_callback: If not None, allow additions to the index and call
2576
this callback with a list of added GraphIndex nodes:
2577
[(node, value, node_refs), ...]
2578
:param is_locked: A callback, returns True if the index is locked and
2581
self._add_callback = add_callback
2582
self._graph_index = graph_index
2583
self._deltas = deltas
2584
self._parents = parents
2585
if deltas and not parents:
2586
# XXX: TODO: Delta tree and parent graph should be conceptually
2588
raise KnitCorrupt(self, "Cannot do delta compression without "
2590
self.has_graph = parents
2591
self._is_locked = is_locked
2592
self._missing_compression_parents = set()
2595
return "%s(%r)" % (self.__class__.__name__, self._graph_index)
2597
def add_records(self, records, random_id=False):
2598
"""Add multiple records to the index.
2600
This function does not insert data into the Immutable GraphIndex
2601
backing the KnitGraphIndex, instead it prepares data for insertion by
2602
the caller and checks that it is safe to insert then calls
2603
self._add_callback with the prepared GraphIndex nodes.
2605
:param records: a list of tuples:
2606
(key, options, access_memo, parents).
2607
:param random_id: If True the ids being added were randomly generated
2608
and no check for existence will be performed.
2610
if not self._add_callback:
2611
raise errors.ReadOnlyError(self)
2612
# we hope there are no repositories with inconsistent parentage
2616
for (key, options, access_memo, parents) in records:
2618
parents = tuple(parents)
2619
index, pos, size = access_memo
2620
if 'no-eol' in options:
2624
value += "%d %d" % (pos, size)
2625
if not self._deltas:
2626
if 'line-delta' in options:
2627
raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
2630
if 'line-delta' in options:
2631
node_refs = (parents, (parents[0],))
2633
node_refs = (parents, ())
2635
node_refs = (parents, )
2638
raise KnitCorrupt(self, "attempt to add node with parents "
2639
"in parentless index.")
2641
keys[key] = (value, node_refs)
2644
present_nodes = self._get_entries(keys)
2645
for (index, key, value, node_refs) in present_nodes:
2646
if (value[0] != keys[key][0][0] or
2647
node_refs[:1] != keys[key][1][:1]):
2648
raise KnitCorrupt(self, "inconsistent details in add_records"
2649
": %s %s" % ((value, node_refs), keys[key]))
2653
for key, (value, node_refs) in keys.iteritems():
2654
result.append((key, value, node_refs))
2656
for key, (value, node_refs) in keys.iteritems():
2657
result.append((key, value))
2658
self._add_callback(result)
2660
def scan_unvalidated_index(self, graph_index):
2661
"""Inform this _KnitGraphIndex that there is an unvalidated index.
2663
This allows this _KnitGraphIndex to keep track of any missing
2664
compression parents we may want to have filled in to make those
2667
:param graph_index: A GraphIndex
2670
new_missing = graph_index.external_references(ref_list_num=1)
2671
new_missing.difference_update(self.get_parent_map(new_missing))
2672
self._missing_compression_parents.update(new_missing)
2674
def get_missing_compression_parents(self):
2675
"""Return the keys of compression parents missing from unvalidated
2678
return frozenset(self._missing_compression_parents)
2680
def _check_read(self):
2681
"""raise if reads are not permitted."""
2682
if not self._is_locked():
2683
raise errors.ObjectNotLocked(self)
2685
def _check_write_ok(self):
2686
"""Assert if writes are not permitted."""
2687
if not self._is_locked():
2688
raise errors.ObjectNotLocked(self)
2690
def _compression_parent(self, an_entry):
2691
# return the key that an_entry is compressed against, or None
2692
# Grab the second parent list (as deltas implies parents currently)
2693
compression_parents = an_entry[3][1]
2694
if not compression_parents:
2696
if len(compression_parents) != 1:
2697
raise AssertionError(
2698
"Too many compression parents: %r" % compression_parents)
2699
return compression_parents[0]
2701
def get_build_details(self, keys):
2702
"""Get the method, index_memo and compression parent for version_ids.
2704
Ghosts are omitted from the result.
2706
:param keys: An iterable of keys.
2707
:return: A dict of key:
2708
(index_memo, compression_parent, parents, record_details).
2710
opaque structure to pass to read_records to extract the raw
2713
Content that this record is built upon, may be None
2715
Logical parents of this node
2717
extra information about the content which needs to be passed to
2718
Factory.parse_record
2722
entries = self._get_entries(keys, False)
2723
for entry in entries:
2725
if not self._parents:
2728
parents = entry[3][0]
2729
if not self._deltas:
2730
compression_parent_key = None
2732
compression_parent_key = self._compression_parent(entry)
2733
noeol = (entry[2][0] == 'N')
2734
if compression_parent_key:
2735
method = 'line-delta'
2738
result[key] = (self._node_to_position(entry),
2739
compression_parent_key, parents,
2743
def _get_entries(self, keys, check_present=False):
2744
"""Get the entries for keys.
2746
:param keys: An iterable of index key tuples.
2751
for node in self._graph_index.iter_entries(keys):
2753
found_keys.add(node[1])
2755
# adapt parentless index to the rest of the code.
2756
for node in self._graph_index.iter_entries(keys):
2757
yield node[0], node[1], node[2], ()
2758
found_keys.add(node[1])
2760
missing_keys = keys.difference(found_keys)
2762
raise RevisionNotPresent(missing_keys.pop(), self)
2764
def get_method(self, key):
2765
"""Return compression method of specified key."""
2766
return self._get_method(self._get_node(key))
2768
def _get_method(self, node):
2769
if not self._deltas:
2771
if self._compression_parent(node):
2776
def _get_node(self, key):
2778
return list(self._get_entries([key]))[0]
2780
raise RevisionNotPresent(key, self)
2782
def get_options(self, key):
2783
"""Return a list representing options.
2787
node = self._get_node(key)
2788
options = [self._get_method(node)]
2789
if node[2][0] == 'N':
2790
options.append('no-eol')
2793
def get_parent_map(self, keys):
2794
"""Get a map of the parents of keys.
2796
:param keys: The keys to look up parents for.
2797
:return: A mapping from keys to parents. Absent keys are absent from
2801
nodes = self._get_entries(keys)
2805
result[node[1]] = node[3][0]
2808
result[node[1]] = None
2811
def get_position(self, key):
2812
"""Return details needed to access the version.
2814
:return: a tuple (index, data position, size) to hand to the access
2815
logic to get the record.
2817
node = self._get_node(key)
2818
return self._node_to_position(node)
2820
has_key = _mod_index._has_key_from_parent_map
2823
"""Get all the keys in the collection.
2825
The keys are not ordered.
2828
return [node[1] for node in self._graph_index.iter_all_entries()]
2830
missing_keys = _mod_index._missing_keys_from_parent_map
2832
def _node_to_position(self, node):
2833
"""Convert an index value to position details."""
2834
bits = node[2][1:].split(' ')
2835
return node[0], int(bits[0]), int(bits[1])
2837
def _sort_keys_by_io(self, keys, positions):
2838
"""Figure out an optimal order to read the records for the given keys.
2840
Sort keys, grouped by index and sorted by position.
2842
:param keys: A list of keys whose records we want to read. This will be
2844
:param positions: A dict, such as the one returned by
2845
_get_components_positions()
2848
def get_index_memo(key):
2849
# index_memo is at offset [1]. It is made up of (GraphIndex,
2850
# position, size). GI is an object, which will be unique for each
2851
# pack file. This causes us to group by pack file, then sort by
2852
# position. Size doesn't matter, but it isn't worth breaking up the
2854
return positions[key][1]
2855
return keys.sort(key=get_index_memo)
2858
class _KnitKeyAccess(object):
2859
"""Access to records in .knit files."""
2861
def __init__(self, transport, mapper):
2862
"""Create a _KnitKeyAccess with transport and mapper.
2864
:param transport: The transport the access object is rooted at.
2865
:param mapper: The mapper used to map keys to .knit files.
2867
self._transport = transport
2868
self._mapper = mapper
2870
def add_raw_records(self, key_sizes, raw_data):
2871
"""Add raw knit bytes to a storage area.
2873
The data is spooled to the container writer in one bytes-record per
2876
:param sizes: An iterable of tuples containing the key and size of each
2878
:param raw_data: A bytestring containing the data.
2879
:return: A list of memos to retrieve the record later. Each memo is an
2880
opaque index memo. For _KnitKeyAccess the memo is (key, pos,
2881
length), where the key is the record key.
2883
if type(raw_data) != str:
2884
raise AssertionError(
2885
'data must be plain bytes was %s' % type(raw_data))
2888
# TODO: This can be tuned for writing to sftp and other servers where
2889
# append() is relatively expensive by grouping the writes to each key
2891
for key, size in key_sizes:
2892
path = self._mapper.map(key)
2894
base = self._transport.append_bytes(path + '.knit',
2895
raw_data[offset:offset+size])
2896
except errors.NoSuchFile:
2897
self._transport.mkdir(osutils.dirname(path))
2898
base = self._transport.append_bytes(path + '.knit',
2899
raw_data[offset:offset+size])
2903
result.append((key, base, size))
2906
def get_raw_records(self, memos_for_retrieval):
2907
"""Get the raw bytes for a records.
2909
:param memos_for_retrieval: An iterable containing the access memo for
2910
retrieving the bytes.
2911
:return: An iterator over the bytes of the records.
2913
# first pass, group into same-index request to minimise readv's issued.
2915
current_prefix = None
2916
for (key, offset, length) in memos_for_retrieval:
2917
if current_prefix == key[:-1]:
2918
current_list.append((offset, length))
2920
if current_prefix is not None:
2921
request_lists.append((current_prefix, current_list))
2922
current_prefix = key[:-1]
2923
current_list = [(offset, length)]
2924
# handle the last entry
2925
if current_prefix is not None:
2926
request_lists.append((current_prefix, current_list))
2927
for prefix, read_vector in request_lists:
2928
path = self._mapper.map(prefix) + '.knit'
2929
for pos, data in self._transport.readv(path, read_vector):
2933
class _DirectPackAccess(object):
2934
"""Access to data in one or more packs with less translation."""
2936
def __init__(self, index_to_packs, reload_func=None):
2937
"""Create a _DirectPackAccess object.
2939
:param index_to_packs: A dict mapping index objects to the transport
2940
and file names for obtaining data.
2941
:param reload_func: A function to call if we determine that the pack
2942
files have moved and we need to reload our caches. See
2943
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
2945
self._container_writer = None
2946
self._write_index = None
2947
self._indices = index_to_packs
2948
self._reload_func = reload_func
2950
def add_raw_records(self, key_sizes, raw_data):
2951
"""Add raw knit bytes to a storage area.
2953
The data is spooled to the container writer in one bytes-record per
2956
:param sizes: An iterable of tuples containing the key and size of each
2958
:param raw_data: A bytestring containing the data.
2959
:return: A list of memos to retrieve the record later. Each memo is an
2960
opaque index memo. For _DirectPackAccess the memo is (index, pos,
2961
length), where the index field is the write_index object supplied
2962
to the PackAccess object.
2964
if type(raw_data) != str:
2965
raise AssertionError(
2966
'data must be plain bytes was %s' % type(raw_data))
2969
for key, size in key_sizes:
2970
p_offset, p_length = self._container_writer.add_bytes_record(
2971
raw_data[offset:offset+size], [])
2973
result.append((self._write_index, p_offset, p_length))
2976
def get_raw_records(self, memos_for_retrieval):
2977
"""Get the raw bytes for a records.
2979
:param memos_for_retrieval: An iterable containing the (index, pos,
2980
length) memo for retrieving the bytes. The Pack access method
2981
looks up the pack to use for a given record in its index_to_pack
2983
:return: An iterator over the bytes of the records.
2985
# first pass, group into same-index requests
2987
current_index = None
2988
for (index, offset, length) in memos_for_retrieval:
2989
if current_index == index:
2990
current_list.append((offset, length))
2992
if current_index is not None:
2993
request_lists.append((current_index, current_list))
2994
current_index = index
2995
current_list = [(offset, length)]
2996
# handle the last entry
2997
if current_index is not None:
2998
request_lists.append((current_index, current_list))
2999
for index, offsets in request_lists:
3001
transport, path = self._indices[index]
3003
# A KeyError here indicates that someone has triggered an index
3004
# reload, and this index has gone missing, we need to start
3006
if self._reload_func is None:
3007
# If we don't have a _reload_func there is nothing that can
3010
raise errors.RetryWithNewPacks(index,
3011
reload_occurred=True,
3012
exc_info=sys.exc_info())
3014
reader = pack.make_readv_reader(transport, path, offsets)
3015
for names, read_func in reader.iter_records():
3016
yield read_func(None)
3017
except errors.NoSuchFile:
3018
# A NoSuchFile error indicates that a pack file has gone
3019
# missing on disk, we need to trigger a reload, and start over.
3020
if self._reload_func is None:
3022
raise errors.RetryWithNewPacks(transport.abspath(path),
3023
reload_occurred=False,
3024
exc_info=sys.exc_info())
3026
def set_writer(self, writer, index, transport_packname):
3027
"""Set a writer to use for adding data."""
3028
if index is not None:
3029
self._indices[index] = transport_packname
3030
self._container_writer = writer
3031
self._write_index = index
3033
def reload_or_raise(self, retry_exc):
3034
"""Try calling the reload function, or re-raise the original exception.
3036
This should be called after _DirectPackAccess raises a
3037
RetryWithNewPacks exception. This function will handle the common logic
3038
of determining when the error is fatal versus being temporary.
3039
It will also make sure that the original exception is raised, rather
3040
than the RetryWithNewPacks exception.
3042
If this function returns, then the calling function should retry
3043
whatever operation was being performed. Otherwise an exception will
3046
:param retry_exc: A RetryWithNewPacks exception.
3049
if self._reload_func is None:
3051
elif not self._reload_func():
3052
# The reload claimed that nothing changed
3053
if not retry_exc.reload_occurred:
3054
# If there wasn't an earlier reload, then we really were
3055
# expecting to find changes. We didn't find them, so this is a
3059
exc_class, exc_value, exc_traceback = retry_exc.exc_info
3060
raise exc_class, exc_value, exc_traceback
3063
# Deprecated, use PatienceSequenceMatcher instead
3064
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
3067
def annotate_knit(knit, revision_id):
3068
"""Annotate a knit with no cached annotations.
3070
This implementation is for knits with no cached annotations.
3071
It will work for knits with cached annotations, but this is not
3074
annotator = _KnitAnnotator(knit)
3075
return iter(annotator.annotate(revision_id))
3078
class _KnitAnnotator(object):
3079
"""Build up the annotations for a text."""
3081
def __init__(self, knit):
3084
# Content objects, differs from fulltexts because of how final newlines
3085
# are treated by knits. the content objects here will always have a
3087
self._fulltext_contents = {}
3089
# Annotated lines of specific revisions
3090
self._annotated_lines = {}
3092
# Track the raw data for nodes that we could not process yet.
3093
# This maps the revision_id of the base to a list of children that will
3094
# annotated from it.
3095
self._pending_children = {}
3097
# Nodes which cannot be extracted
3098
self._ghosts = set()
3100
# Track how many children this node has, so we know if we need to keep
3102
self._annotate_children = {}
3103
self._compression_children = {}
3105
self._all_build_details = {}
3106
# The children => parent revision_id graph
3107
self._revision_id_graph = {}
3109
self._heads_provider = None
3111
self._nodes_to_keep_annotations = set()
3112
self._generations_until_keep = 100
3114
def set_generations_until_keep(self, value):
3115
"""Set the number of generations before caching a node.
3117
Setting this to -1 will cache every merge node, setting this higher
3118
will cache fewer nodes.
3120
self._generations_until_keep = value
3122
def _add_fulltext_content(self, revision_id, content_obj):
3123
self._fulltext_contents[revision_id] = content_obj
3124
# TODO: jam 20080305 It might be good to check the sha1digest here
3125
return content_obj.text()
3127
def _check_parents(self, child, nodes_to_annotate):
3128
"""Check if all parents have been processed.
3130
:param child: A tuple of (rev_id, parents, raw_content)
3131
:param nodes_to_annotate: If child is ready, add it to
3132
nodes_to_annotate, otherwise put it back in self._pending_children
3134
for parent_id in child[1]:
3135
if (parent_id not in self._annotated_lines):
3136
# This parent is present, but another parent is missing
3137
self._pending_children.setdefault(parent_id,
3141
# This one is ready to be processed
3142
nodes_to_annotate.append(child)
3144
def _add_annotation(self, revision_id, fulltext, parent_ids,
3145
left_matching_blocks=None):
3146
"""Add an annotation entry.
3148
All parents should already have been annotated.
3149
:return: A list of children that now have their parents satisfied.
3151
a = self._annotated_lines
3152
annotated_parent_lines = [a[p] for p in parent_ids]
3153
annotated_lines = list(annotate.reannotate(annotated_parent_lines,
3154
fulltext, revision_id, left_matching_blocks,
3155
heads_provider=self._get_heads_provider()))
3156
self._annotated_lines[revision_id] = annotated_lines
3157
for p in parent_ids:
3158
ann_children = self._annotate_children[p]
3159
ann_children.remove(revision_id)
3160
if (not ann_children
3161
and p not in self._nodes_to_keep_annotations):
3162
del self._annotated_lines[p]
3163
del self._all_build_details[p]
3164
if p in self._fulltext_contents:
3165
del self._fulltext_contents[p]
3166
# Now that we've added this one, see if there are any pending
3167
# deltas to be done, certainly this parent is finished
3168
nodes_to_annotate = []
3169
for child in self._pending_children.pop(revision_id, []):
3170
self._check_parents(child, nodes_to_annotate)
3171
return nodes_to_annotate
3173
def _get_build_graph(self, key):
3174
"""Get the graphs for building texts and annotations.
3176
The data you need for creating a full text may be different than the
3177
data you need to annotate that text. (At a minimum, you need both
3178
parents to create an annotation, but only need 1 parent to generate the
3181
:return: A list of (key, index_memo) records, suitable for
3182
passing to read_records_iter to start reading in the raw data fro/
3185
if key in self._annotated_lines:
3188
pending = set([key])
3193
# get all pending nodes
3195
this_iteration = pending
3196
build_details = self._knit._index.get_build_details(this_iteration)
3197
self._all_build_details.update(build_details)
3198
# new_nodes = self._knit._index._get_entries(this_iteration)
3200
for key, details in build_details.iteritems():
3201
(index_memo, compression_parent, parents,
3202
record_details) = details
3203
self._revision_id_graph[key] = parents
3204
records.append((key, index_memo))
3205
# Do we actually need to check _annotated_lines?
3206
pending.update(p for p in parents
3207
if p not in self._all_build_details)
3208
if compression_parent:
3209
self._compression_children.setdefault(compression_parent,
3212
for parent in parents:
3213
self._annotate_children.setdefault(parent,
3215
num_gens = generation - kept_generation
3216
if ((num_gens >= self._generations_until_keep)
3217
and len(parents) > 1):
3218
kept_generation = generation
3219
self._nodes_to_keep_annotations.add(key)
3221
missing_versions = this_iteration.difference(build_details.keys())
3222
self._ghosts.update(missing_versions)
3223
for missing_version in missing_versions:
3224
# add a key, no parents
3225
self._revision_id_graph[missing_version] = ()
3226
pending.discard(missing_version) # don't look for it
3227
if self._ghosts.intersection(self._compression_children):
3229
"We cannot have nodes which have a ghost compression parent:\n"
3231
"compression children: %r"
3232
% (self._ghosts, self._compression_children))
3233
# Cleanout anything that depends on a ghost so that we don't wait for
3234
# the ghost to show up
3235
for node in self._ghosts:
3236
if node in self._annotate_children:
3237
# We won't be building this node
3238
del self._annotate_children[node]
3239
# Generally we will want to read the records in reverse order, because
3240
# we find the parent nodes after the children
3244
def _annotate_records(self, records):
3245
"""Build the annotations for the listed records."""
3246
# We iterate in the order read, rather than a strict order requested
3247
# However, process what we can, and put off to the side things that
3248
# still need parents, cleaning them up when those parents are
3250
for (rev_id, record,
3251
digest) in self._knit._read_records_iter(records):
3252
if rev_id in self._annotated_lines:
3254
parent_ids = self._revision_id_graph[rev_id]
3255
parent_ids = [p for p in parent_ids if p not in self._ghosts]
3256
details = self._all_build_details[rev_id]
3257
(index_memo, compression_parent, parents,
3258
record_details) = details
3259
nodes_to_annotate = []
3260
# TODO: Remove the punning between compression parents, and
3261
# parent_ids, we should be able to do this without assuming
3263
if len(parent_ids) == 0:
3264
# There are no parents for this node, so just add it
3265
# TODO: This probably needs to be decoupled
3266
fulltext_content, delta = self._knit._factory.parse_record(
3267
rev_id, record, record_details, None)
3268
fulltext = self._add_fulltext_content(rev_id, fulltext_content)
3269
nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
3270
parent_ids, left_matching_blocks=None))
3272
child = (rev_id, parent_ids, record)
3273
# Check if all the parents are present
3274
self._check_parents(child, nodes_to_annotate)
3275
while nodes_to_annotate:
3276
# Should we use a queue here instead of a stack?
3277
(rev_id, parent_ids, record) = nodes_to_annotate.pop()
3278
(index_memo, compression_parent, parents,
3279
record_details) = self._all_build_details[rev_id]
3281
if compression_parent is not None:
3282
comp_children = self._compression_children[compression_parent]
3283
if rev_id not in comp_children:
3284
raise AssertionError("%r not in compression children %r"
3285
% (rev_id, comp_children))
3286
# If there is only 1 child, it is safe to reuse this
3288
reuse_content = (len(comp_children) == 1
3289
and compression_parent not in
3290
self._nodes_to_keep_annotations)
3292
# Remove it from the cache since it will be changing
3293
parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
3294
# Make sure to copy the fulltext since it might be
3296
parent_fulltext = list(parent_fulltext_content.text())
3298
parent_fulltext_content = self._fulltext_contents[compression_parent]
3299
parent_fulltext = parent_fulltext_content.text()
3300
comp_children.remove(rev_id)
3301
fulltext_content, delta = self._knit._factory.parse_record(
3302
rev_id, record, record_details,
3303
parent_fulltext_content,
3304
copy_base_content=(not reuse_content))
3305
fulltext = self._add_fulltext_content(rev_id,
3307
if compression_parent == parent_ids[0]:
3308
# the compression_parent is the left parent, so we can
3310
blocks = KnitContent.get_line_delta_blocks(delta,
3311
parent_fulltext, fulltext)
3313
fulltext_content = self._knit._factory.parse_fulltext(
3315
fulltext = self._add_fulltext_content(rev_id,
3317
nodes_to_annotate.extend(
3318
self._add_annotation(rev_id, fulltext, parent_ids,
3319
left_matching_blocks=blocks))
3321
def _get_heads_provider(self):
3322
"""Create a heads provider for resolving ancestry issues."""
3323
if self._heads_provider is not None:
3324
return self._heads_provider
3325
parent_provider = _mod_graph.DictParentsProvider(
3326
self._revision_id_graph)
3327
graph_obj = _mod_graph.Graph(parent_provider)
3328
head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
3329
self._heads_provider = head_cache
3332
def annotate(self, key):
3333
"""Return the annotated fulltext at the given key.
3335
:param key: The key to annotate.
3337
if len(self._knit._fallback_vfs) > 0:
3338
# stacked knits can't use the fast path at present.
3339
return self._simple_annotate(key)
3342
records = self._get_build_graph(key)
3343
if key in self._ghosts:
3344
raise errors.RevisionNotPresent(key, self._knit)
3345
self._annotate_records(records)
3346
return self._annotated_lines[key]
3347
except errors.RetryWithNewPacks, e:
3348
self._knit._access.reload_or_raise(e)
3349
# The cached build_details are no longer valid
3350
self._all_build_details.clear()
3352
def _simple_annotate(self, key):
3353
"""Return annotated fulltext, rediffing from the full texts.
3355
This is slow but makes no assumptions about the repository
3356
being able to produce line deltas.
3358
# TODO: this code generates a parent maps of present ancestors; it
3359
# could be split out into a separate method, and probably should use
3360
# iter_ancestry instead. -- mbp and robertc 20080704
3361
graph = _mod_graph.Graph(self._knit)
3362
head_cache = _mod_graph.FrozenHeadsCache(graph)
3363
search = graph._make_breadth_first_searcher([key])
3367
present, ghosts = search.next_with_ghosts()
3368
except StopIteration:
3370
keys.update(present)
3371
parent_map = self._knit.get_parent_map(keys)
3373
reannotate = annotate.reannotate
3374
for record in self._knit.get_record_stream(keys, 'topological', True):
3376
fulltext = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
3377
parents = parent_map[key]
3378
if parents is not None:
3379
parent_lines = [parent_cache[parent] for parent in parent_map[key]]
3382
parent_cache[key] = list(
3383
reannotate(parent_lines, fulltext, key, None, head_cache))
3385
return parent_cache[key]
3387
raise errors.RevisionNotPresent(key, self._knit)
3391
from bzrlib._knit_load_data_c import _load_data_c as _load_data
3393
from bzrlib._knit_load_data_py import _load_data_py as _load_data