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 buffered_index_entries:
1539
# There were index entries buffered at the end of the stream,
1540
# So these need to be added (if the index supports holding such
1541
# entries for later insertion)
1542
for key in buffered_index_entries:
1543
index_entries = buffered_index_entries[key]
1544
self._index.add_records(index_entries,
1545
missing_compression_parents=True)
1547
def get_missing_compression_parent_keys(self):
1548
"""Return an iterable of keys of missing compression parents.
1550
Check this after calling insert_record_stream to find out if there are
1551
any missing compression parents. If there are, the records that
1552
depend on them are not able to be inserted safely. For atomic
1553
KnitVersionedFiles built on packs, the transaction should be aborted or
1554
suspended - commit will fail at this point. Nonatomic knits will error
1555
earlier because they have no staging area to put pending entries into.
1557
return self._index.get_missing_compression_parents()
1559
def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1560
"""Iterate over the lines in the versioned files from keys.
1562
This may return lines from other keys. Each item the returned
1563
iterator yields is a tuple of a line and a text version that that line
1564
is present in (not introduced in).
1566
Ordering of results is in whatever order is most suitable for the
1567
underlying storage format.
1569
If a progress bar is supplied, it may be used to indicate progress.
1570
The caller is responsible for cleaning up progress bars (because this
1574
* Lines are normalised by the underlying store: they will all have \\n
1576
* Lines are returned in arbitrary order.
1577
* If a requested key did not change any lines (or didn't have any
1578
lines), it may not be mentioned at all in the result.
1580
:return: An iterator over (line, key).
1583
pb = progress.DummyProgress()
1589
# we don't care about inclusions, the caller cares.
1590
# but we need to setup a list of records to visit.
1591
# we need key, position, length
1593
build_details = self._index.get_build_details(keys)
1594
for key, details in build_details.iteritems():
1596
key_records.append((key, details[0]))
1597
records_iter = enumerate(self._read_records_iter(key_records))
1598
for (key_idx, (key, data, sha_value)) in records_iter:
1599
pb.update('Walking content.', key_idx, total)
1600
compression_parent = build_details[key][1]
1601
if compression_parent is None:
1603
line_iterator = self._factory.get_fulltext_content(data)
1606
line_iterator = self._factory.get_linedelta_content(data)
1607
# Now that we are yielding the data for this key, remove it
1610
# XXX: It might be more efficient to yield (key,
1611
# line_iterator) in the future. However for now, this is a
1612
# simpler change to integrate into the rest of the
1613
# codebase. RBC 20071110
1614
for line in line_iterator:
1617
except errors.RetryWithNewPacks, e:
1618
self._access.reload_or_raise(e)
1619
# If there are still keys we've not yet found, we look in the fallback
1620
# vfs, and hope to find them there. Note that if the keys are found
1621
# but had no changes or no content, the fallback may not return
1623
if keys and not self._fallback_vfs:
1624
# XXX: strictly the second parameter is meant to be the file id
1625
# but it's not easily accessible here.
1626
raise RevisionNotPresent(keys, repr(self))
1627
for source in self._fallback_vfs:
1631
for line, key in source.iter_lines_added_or_present_in_keys(keys):
1632
source_keys.add(key)
1634
keys.difference_update(source_keys)
1635
pb.update('Walking content.', total, total)
1637
def _make_line_delta(self, delta_seq, new_content):
1638
"""Generate a line delta from delta_seq and new_content."""
1640
for op in delta_seq.get_opcodes():
1641
if op[0] == 'equal':
1643
diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
1646
def _merge_annotations(self, content, parents, parent_texts={},
1647
delta=None, annotated=None,
1648
left_matching_blocks=None):
1649
"""Merge annotations for content and generate deltas.
1651
This is done by comparing the annotations based on changes to the text
1652
and generating a delta on the resulting full texts. If annotations are
1653
not being created then a simple delta is created.
1655
if left_matching_blocks is not None:
1656
delta_seq = diff._PrematchedMatcher(left_matching_blocks)
1660
for parent_key in parents:
1661
merge_content = self._get_content(parent_key, parent_texts)
1662
if (parent_key == parents[0] and delta_seq is not None):
1665
seq = patiencediff.PatienceSequenceMatcher(
1666
None, merge_content.text(), content.text())
1667
for i, j, n in seq.get_matching_blocks():
1670
# this copies (origin, text) pairs across to the new
1671
# content for any line that matches the last-checked
1673
content._lines[j:j+n] = merge_content._lines[i:i+n]
1674
# XXX: Robert says the following block is a workaround for a
1675
# now-fixed bug and it can probably be deleted. -- mbp 20080618
1676
if content._lines and content._lines[-1][1][-1] != '\n':
1677
# The copied annotation was from a line without a trailing EOL,
1678
# reinstate one for the content object, to ensure correct
1680
line = content._lines[-1][1] + '\n'
1681
content._lines[-1] = (content._lines[-1][0], line)
1683
if delta_seq is None:
1684
reference_content = self._get_content(parents[0], parent_texts)
1685
new_texts = content.text()
1686
old_texts = reference_content.text()
1687
delta_seq = patiencediff.PatienceSequenceMatcher(
1688
None, old_texts, new_texts)
1689
return self._make_line_delta(delta_seq, content)
1691
def _parse_record(self, version_id, data):
1692
"""Parse an original format knit record.
1694
These have the last element of the key only present in the stored data.
1696
rec, record_contents = self._parse_record_unchecked(data)
1697
self._check_header_version(rec, version_id)
1698
return record_contents, rec[3]
1700
def _parse_record_header(self, key, raw_data):
1701
"""Parse a record header for consistency.
1703
:return: the header and the decompressor stream.
1704
as (stream, header_record)
1706
df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
1709
rec = self._check_header(key, df.readline())
1710
except Exception, e:
1711
raise KnitCorrupt(self,
1712
"While reading {%s} got %s(%s)"
1713
% (key, e.__class__.__name__, str(e)))
1716
def _parse_record_unchecked(self, data):
1718
# 4168 calls in 2880 217 internal
1719
# 4168 calls to _parse_record_header in 2121
1720
# 4168 calls to readlines in 330
1721
df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(data))
1723
record_contents = df.readlines()
1724
except Exception, e:
1725
raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1726
(data, e.__class__.__name__, str(e)))
1727
header = record_contents.pop(0)
1728
rec = self._split_header(header)
1729
last_line = record_contents.pop()
1730
if len(record_contents) != int(rec[2]):
1731
raise KnitCorrupt(self,
1732
'incorrect number of lines %s != %s'
1733
' for version {%s} %s'
1734
% (len(record_contents), int(rec[2]),
1735
rec[1], record_contents))
1736
if last_line != 'end %s\n' % rec[1]:
1737
raise KnitCorrupt(self,
1738
'unexpected version end line %r, wanted %r'
1739
% (last_line, rec[1]))
1741
return rec, record_contents
1743
def _read_records_iter(self, records):
1744
"""Read text records from data file and yield result.
1746
The result will be returned in whatever is the fastest to read.
1747
Not by the order requested. Also, multiple requests for the same
1748
record will only yield 1 response.
1749
:param records: A list of (key, access_memo) entries
1750
:return: Yields (key, contents, digest) in the order
1751
read, not the order requested
1756
# XXX: This smells wrong, IO may not be getting ordered right.
1757
needed_records = sorted(set(records), key=operator.itemgetter(1))
1758
if not needed_records:
1761
# The transport optimizes the fetching as well
1762
# (ie, reads continuous ranges.)
1763
raw_data = self._access.get_raw_records(
1764
[index_memo for key, index_memo in needed_records])
1766
for (key, index_memo), data in \
1767
izip(iter(needed_records), raw_data):
1768
content, digest = self._parse_record(key[-1], data)
1769
yield key, content, digest
1771
def _read_records_iter_raw(self, records):
1772
"""Read text records from data file and yield raw data.
1774
This unpacks enough of the text record to validate the id is
1775
as expected but thats all.
1777
Each item the iterator yields is (key, bytes,
1778
expected_sha1_of_full_text).
1780
for key, data in self._read_records_iter_unchecked(records):
1781
# validate the header (note that we can only use the suffix in
1782
# current knit records).
1783
df, rec = self._parse_record_header(key, data)
1785
yield key, data, rec[3]
1787
def _read_records_iter_unchecked(self, records):
1788
"""Read text records from data file and yield raw data.
1790
No validation is done.
1792
Yields tuples of (key, data).
1794
# setup an iterator of the external records:
1795
# uses readv so nice and fast we hope.
1797
# grab the disk data needed.
1798
needed_offsets = [index_memo for key, index_memo
1800
raw_records = self._access.get_raw_records(needed_offsets)
1802
for key, index_memo in records:
1803
data = raw_records.next()
1806
def _record_to_data(self, key, digest, lines, dense_lines=None):
1807
"""Convert key, digest, lines into a raw data block.
1809
:param key: The key of the record. Currently keys are always serialised
1810
using just the trailing component.
1811
:param dense_lines: The bytes of lines but in a denser form. For
1812
instance, if lines is a list of 1000 bytestrings each ending in \n,
1813
dense_lines may be a list with one line in it, containing all the
1814
1000's lines and their \n's. Using dense_lines if it is already
1815
known is a win because the string join to create bytes in this
1816
function spends less time resizing the final string.
1817
:return: (len, a StringIO instance with the raw data ready to read.)
1819
# Note: using a string copy here increases memory pressure with e.g.
1820
# ISO's, but it is about 3 seconds faster on a 1.2Ghz intel machine
1821
# when doing the initial commit of a mozilla tree. RBC 20070921
1822
bytes = ''.join(chain(
1823
["version %s %d %s\n" % (key[-1],
1826
dense_lines or lines,
1827
["end %s\n" % key[-1]]))
1828
if type(bytes) != str:
1829
raise AssertionError(
1830
'data must be plain bytes was %s' % type(bytes))
1831
if lines and lines[-1][-1] != '\n':
1832
raise ValueError('corrupt lines value %r' % lines)
1833
compressed_bytes = tuned_gzip.bytes_to_gzip(bytes)
1834
return len(compressed_bytes), compressed_bytes
1836
def _split_header(self, line):
1839
raise KnitCorrupt(self,
1840
'unexpected number of elements in record header')
1844
"""See VersionedFiles.keys."""
1845
if 'evil' in debug.debug_flags:
1846
trace.mutter_callsite(2, "keys scales with size of history")
1847
sources = [self._index] + self._fallback_vfs
1849
for source in sources:
1850
result.update(source.keys())
1854
class _ContentMapGenerator(object):
1855
"""Generate texts or expose raw deltas for a set of texts."""
1857
def _get_content(self, key):
1858
"""Get the content object for key."""
1859
# Note that _get_content is only called when the _ContentMapGenerator
1860
# has been constructed with just one key requested for reconstruction.
1861
if key in self.nonlocal_keys:
1862
record = self.get_record_stream().next()
1863
# Create a content object on the fly
1864
lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
1865
return PlainKnitContent(lines, record.key)
1867
# local keys we can ask for directly
1868
return self._get_one_work(key)
1870
def get_record_stream(self):
1871
"""Get a record stream for the keys requested during __init__."""
1872
for record in self._work():
1876
"""Produce maps of text and KnitContents as dicts.
1878
:return: (text_map, content_map) where text_map contains the texts for
1879
the requested versions and content_map contains the KnitContents.
1881
# NB: By definition we never need to read remote sources unless texts
1882
# are requested from them: we don't delta across stores - and we
1883
# explicitly do not want to to prevent data loss situations.
1884
if self.global_map is None:
1885
self.global_map = self.vf.get_parent_map(self.keys)
1886
nonlocal_keys = self.nonlocal_keys
1888
missing_keys = set(nonlocal_keys)
1889
# Read from remote versioned file instances and provide to our caller.
1890
for source in self.vf._fallback_vfs:
1891
if not missing_keys:
1893
# Loop over fallback repositories asking them for texts - ignore
1894
# any missing from a particular fallback.
1895
for record in source.get_record_stream(missing_keys,
1897
if record.storage_kind == 'absent':
1898
# Not in thie particular stream, may be in one of the
1899
# other fallback vfs objects.
1901
missing_keys.remove(record.key)
1904
self._raw_record_map = self.vf._get_record_map_unparsed(self.keys,
1907
for key in self.keys:
1908
if key in self.nonlocal_keys:
1910
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
1913
def _get_one_work(self, requested_key):
1914
# Now, if we have calculated everything already, just return the
1916
if requested_key in self._contents_map:
1917
return self._contents_map[requested_key]
1918
# To simplify things, parse everything at once - code that wants one text
1919
# probably wants them all.
1920
# FUTURE: This function could be improved for the 'extract many' case
1921
# by tracking each component and only doing the copy when the number of
1922
# children than need to apply delta's to it is > 1 or it is part of the
1924
multiple_versions = len(self.keys) != 1
1925
if self._record_map is None:
1926
self._record_map = self.vf._raw_map_to_record_map(
1927
self._raw_record_map)
1928
record_map = self._record_map
1929
# raw_record_map is key:
1930
# Have read and parsed records at this point.
1931
for key in self.keys:
1932
if key in self.nonlocal_keys:
1937
while cursor is not None:
1939
record, record_details, digest, next = record_map[cursor]
1941
raise RevisionNotPresent(cursor, self)
1942
components.append((cursor, record, record_details, digest))
1944
if cursor in self._contents_map:
1945
# no need to plan further back
1946
components.append((cursor, None, None, None))
1950
for (component_id, record, record_details,
1951
digest) in reversed(components):
1952
if component_id in self._contents_map:
1953
content = self._contents_map[component_id]
1955
content, delta = self._factory.parse_record(key[-1],
1956
record, record_details, content,
1957
copy_base_content=multiple_versions)
1958
if multiple_versions:
1959
self._contents_map[component_id] = content
1961
# digest here is the digest from the last applied component.
1962
text = content.text()
1963
actual_sha = sha_strings(text)
1964
if actual_sha != digest:
1965
raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
1966
if multiple_versions:
1967
return self._contents_map[requested_key]
1971
def _wire_bytes(self):
1972
"""Get the bytes to put on the wire for 'key'.
1974
The first collection of bytes asked for returns the serialised
1975
raw_record_map and the additional details (key, parent) for key.
1976
Subsequent calls return just the additional details (key, parent).
1977
The wire storage_kind given for the first key is 'knit-delta-closure',
1978
For subsequent keys it is 'knit-delta-closure-ref'.
1980
:param key: A key from the content generator.
1981
:return: Bytes to put on the wire.
1984
# kind marker for dispatch on the far side,
1985
lines.append('knit-delta-closure')
1987
if self.vf._factory.annotated:
1988
lines.append('annotated')
1991
# then the list of keys
1992
lines.append('\t'.join(['\x00'.join(key) for key in self.keys
1993
if key not in self.nonlocal_keys]))
1994
# then the _raw_record_map in serialised form:
1996
# for each item in the map:
1998
# 1 line with parents if the key is to be yielded (None: for None, '' for ())
1999
# one line with method
2000
# one line with noeol
2001
# one line with next ('' for None)
2002
# one line with byte count of the record bytes
2004
for key, (record_bytes, (method, noeol), next) in \
2005
self._raw_record_map.iteritems():
2006
key_bytes = '\x00'.join(key)
2007
parents = self.global_map.get(key, None)
2009
parent_bytes = 'None:'
2011
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2012
method_bytes = method
2018
next_bytes = '\x00'.join(next)
2021
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2022
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2023
len(record_bytes), record_bytes))
2024
map_bytes = ''.join(map_byte_list)
2025
lines.append(map_bytes)
2026
bytes = '\n'.join(lines)
2030
class _VFContentMapGenerator(_ContentMapGenerator):
2031
"""Content map generator reading from a VersionedFiles object."""
2033
def __init__(self, versioned_files, keys, nonlocal_keys=None,
2034
global_map=None, raw_record_map=None):
2035
"""Create a _ContentMapGenerator.
2037
:param versioned_files: The versioned files that the texts are being
2039
:param keys: The keys to produce content maps for.
2040
:param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2041
which are known to not be in this knit, but rather in one of the
2043
:param global_map: The result of get_parent_map(keys) (or a supermap).
2044
This is required if get_record_stream() is to be used.
2045
:param raw_record_map: A unparsed raw record map to use for answering
2048
# The vf to source data from
2049
self.vf = versioned_files
2051
self.keys = list(keys)
2052
# Keys known to be in fallback vfs objects
2053
if nonlocal_keys is None:
2054
self.nonlocal_keys = set()
2056
self.nonlocal_keys = frozenset(nonlocal_keys)
2057
# Parents data for keys to be returned in get_record_stream
2058
self.global_map = global_map
2059
# The chunked lists for self.keys in text form
2061
# A cache of KnitContent objects used in extracting texts.
2062
self._contents_map = {}
2063
# All the knit records needed to assemble the requested keys as full
2065
self._record_map = None
2066
if raw_record_map is None:
2067
self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2070
self._raw_record_map = raw_record_map
2071
# the factory for parsing records
2072
self._factory = self.vf._factory
2075
class _NetworkContentMapGenerator(_ContentMapGenerator):
2076
"""Content map generator sourced from a network stream."""
2078
def __init__(self, bytes, line_end):
2079
"""Construct a _NetworkContentMapGenerator from a bytes block."""
2081
self.global_map = {}
2082
self._raw_record_map = {}
2083
self._contents_map = {}
2084
self._record_map = None
2085
self.nonlocal_keys = []
2086
# Get access to record parsing facilities
2087
self.vf = KnitVersionedFiles(None, None)
2090
line_end = bytes.find('\n', start)
2091
line = bytes[start:line_end]
2092
start = line_end + 1
2093
if line == 'annotated':
2094
self._factory = KnitAnnotateFactory()
2096
self._factory = KnitPlainFactory()
2097
# list of keys to emit in get_record_stream
2098
line_end = bytes.find('\n', start)
2099
line = bytes[start:line_end]
2100
start = line_end + 1
2102
tuple(segment.split('\x00')) for segment in line.split('\t')
2104
# now a loop until the end. XXX: It would be nice if this was just a
2105
# bunch of the same records as get_record_stream(..., False) gives, but
2106
# there is a decent sized gap stopping that at the moment.
2110
line_end = bytes.find('\n', start)
2111
key = tuple(bytes[start:line_end].split('\x00'))
2112
start = line_end + 1
2113
# 1 line with parents (None: for None, '' for ())
2114
line_end = bytes.find('\n', start)
2115
line = bytes[start:line_end]
2120
[tuple(segment.split('\x00')) for segment in line.split('\t')
2122
self.global_map[key] = parents
2123
start = line_end + 1
2124
# one line with method
2125
line_end = bytes.find('\n', start)
2126
line = bytes[start:line_end]
2128
start = line_end + 1
2129
# one line with noeol
2130
line_end = bytes.find('\n', start)
2131
line = bytes[start:line_end]
2133
start = line_end + 1
2134
# one line with next ('' for None)
2135
line_end = bytes.find('\n', start)
2136
line = bytes[start:line_end]
2140
next = tuple(bytes[start:line_end].split('\x00'))
2141
start = line_end + 1
2142
# one line with byte count of the record bytes
2143
line_end = bytes.find('\n', start)
2144
line = bytes[start:line_end]
2146
start = line_end + 1
2148
record_bytes = bytes[start:start+count]
2149
start = start + count
2151
self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2153
def get_record_stream(self):
2154
"""Get a record stream for for keys requested by the bytestream."""
2156
for key in self.keys:
2157
yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2160
def _wire_bytes(self):
2164
class _KndxIndex(object):
2165
"""Manages knit index files
2167
The index is kept in memory and read on startup, to enable
2168
fast lookups of revision information. The cursor of the index
2169
file is always pointing to the end, making it easy to append
2172
_cache is a cache for fast mapping from version id to a Index
2175
_history is a cache for fast mapping from indexes to version ids.
2177
The index data format is dictionary compressed when it comes to
2178
parent references; a index entry may only have parents that with a
2179
lover index number. As a result, the index is topological sorted.
2181
Duplicate entries may be written to the index for a single version id
2182
if this is done then the latter one completely replaces the former:
2183
this allows updates to correct version and parent information.
2184
Note that the two entries may share the delta, and that successive
2185
annotations and references MUST point to the first entry.
2187
The index file on disc contains a header, followed by one line per knit
2188
record. The same revision can be present in an index file more than once.
2189
The first occurrence gets assigned a sequence number starting from 0.
2191
The format of a single line is
2192
REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
2193
REVISION_ID is a utf8-encoded revision id
2194
FLAGS is a comma separated list of flags about the record. Values include
2195
no-eol, line-delta, fulltext.
2196
BYTE_OFFSET is the ascii representation of the byte offset in the data file
2197
that the the compressed data starts at.
2198
LENGTH is the ascii representation of the length of the data file.
2199
PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
2201
PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
2202
revision id already in the knit that is a parent of REVISION_ID.
2203
The ' :' marker is the end of record marker.
2206
when a write is interrupted to the index file, it will result in a line
2207
that does not end in ' :'. If the ' :' is not present at the end of a line,
2208
or at the end of the file, then the record that is missing it will be
2209
ignored by the parser.
2211
When writing new records to the index file, the data is preceded by '\n'
2212
to ensure that records always start on new lines even if the last write was
2213
interrupted. As a result its normal for the last line in the index to be
2214
missing a trailing newline. One can be added with no harmful effects.
2216
:ivar _kndx_cache: dict from prefix to the old state of KnitIndex objects,
2217
where prefix is e.g. the (fileid,) for .texts instances or () for
2218
constant-mapped things like .revisions, and the old state is
2219
tuple(history_vector, cache_dict). This is used to prevent having an
2220
ABI change with the C extension that reads .kndx files.
2223
HEADER = "# bzr knit index 8\n"
2225
def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
2226
"""Create a _KndxIndex on transport using mapper."""
2227
self._transport = transport
2228
self._mapper = mapper
2229
self._get_scope = get_scope
2230
self._allow_writes = allow_writes
2231
self._is_locked = is_locked
2233
self.has_graph = True
2235
def add_records(self, records, random_id=False, missing_compression_parents=False):
2236
"""Add multiple records to the index.
2238
:param records: a list of tuples:
2239
(key, options, access_memo, parents).
2240
:param random_id: If True the ids being added were randomly generated
2241
and no check for existence will be performed.
2242
:param missing_compression_parents: If True the records being added are
2243
only compressed against texts already in the index (or inside
2244
records). If False the records all refer to unavailable texts (or
2245
texts inside records) as compression parents.
2247
if missing_compression_parents:
2248
# It might be nice to get the edge of the records. But keys isn't
2250
keys = sorted(record[0] for record in records)
2251
raise errors.RevisionNotPresent(keys, self)
2253
for record in records:
2256
path = self._mapper.map(key) + '.kndx'
2257
path_keys = paths.setdefault(path, (prefix, []))
2258
path_keys[1].append(record)
2259
for path in sorted(paths):
2260
prefix, path_keys = paths[path]
2261
self._load_prefixes([prefix])
2263
orig_history = self._kndx_cache[prefix][1][:]
2264
orig_cache = self._kndx_cache[prefix][0].copy()
2267
for key, options, (_, pos, size), parents in path_keys:
2269
# kndx indices cannot be parentless.
2271
line = "\n%s %s %s %s %s :" % (
2272
key[-1], ','.join(options), pos, size,
2273
self._dictionary_compress(parents))
2274
if type(line) != str:
2275
raise AssertionError(
2276
'data must be utf8 was %s' % type(line))
2278
self._cache_key(key, options, pos, size, parents)
2279
if len(orig_history):
2280
self._transport.append_bytes(path, ''.join(lines))
2282
self._init_index(path, lines)
2284
# If any problems happen, restore the original values and re-raise
2285
self._kndx_cache[prefix] = (orig_cache, orig_history)
2288
def scan_unvalidated_index(self, graph_index):
2289
"""See _KnitGraphIndex.scan_unvalidated_index."""
2290
# Because kndx files do not support atomic insertion via separate index
2291
# files, they do not support this method.
2292
raise NotImplementedError(self.scan_unvalidated_index)
2294
def get_missing_compression_parents(self):
2295
"""See _KnitGraphIndex.get_missing_compression_parents."""
2296
# Because kndx files do not support atomic insertion via separate index
2297
# files, they do not support this method.
2298
raise NotImplementedError(self.get_missing_compression_parents)
2300
def _cache_key(self, key, options, pos, size, parent_keys):
2301
"""Cache a version record in the history array and index cache.
2303
This is inlined into _load_data for performance. KEEP IN SYNC.
2304
(It saves 60ms, 25% of the __init__ overhead on local 4000 record
2308
version_id = key[-1]
2309
# last-element only for compatibilty with the C load_data.
2310
parents = tuple(parent[-1] for parent in parent_keys)
2311
for parent in parent_keys:
2312
if parent[:-1] != prefix:
2313
raise ValueError("mismatched prefixes for %r, %r" % (
2315
cache, history = self._kndx_cache[prefix]
2316
# only want the _history index to reference the 1st index entry
2318
if version_id not in cache:
2319
index = len(history)
2320
history.append(version_id)
2322
index = cache[version_id][5]
2323
cache[version_id] = (version_id,
2330
def check_header(self, fp):
2331
line = fp.readline()
2333
# An empty file can actually be treated as though the file doesn't
2335
raise errors.NoSuchFile(self)
2336
if line != self.HEADER:
2337
raise KnitHeaderError(badline=line, filename=self)
2339
def _check_read(self):
2340
if not self._is_locked():
2341
raise errors.ObjectNotLocked(self)
2342
if self._get_scope() != self._scope:
2345
def _check_write_ok(self):
2346
"""Assert if not writes are permitted."""
2347
if not self._is_locked():
2348
raise errors.ObjectNotLocked(self)
2349
if self._get_scope() != self._scope:
2351
if self._mode != 'w':
2352
raise errors.ReadOnlyObjectDirtiedError(self)
2354
def get_build_details(self, keys):
2355
"""Get the method, index_memo and compression parent for keys.
2357
Ghosts are omitted from the result.
2359
:param keys: An iterable of keys.
2360
:return: A dict of key:(index_memo, compression_parent, parents,
2363
opaque structure to pass to read_records to extract the raw
2366
Content that this record is built upon, may be None
2368
Logical parents of this node
2370
extra information about the content which needs to be passed to
2371
Factory.parse_record
2373
parent_map = self.get_parent_map(keys)
2376
if key not in parent_map:
2378
method = self.get_method(key)
2379
parents = parent_map[key]
2380
if method == 'fulltext':
2381
compression_parent = None
2383
compression_parent = parents[0]
2384
noeol = 'no-eol' in self.get_options(key)
2385
index_memo = self.get_position(key)
2386
result[key] = (index_memo, compression_parent,
2387
parents, (method, noeol))
2390
def get_method(self, key):
2391
"""Return compression method of specified key."""
2392
options = self.get_options(key)
2393
if 'fulltext' in options:
2395
elif 'line-delta' in options:
2398
raise errors.KnitIndexUnknownMethod(self, options)
2400
def get_options(self, key):
2401
"""Return a list representing options.
2405
prefix, suffix = self._split_key(key)
2406
self._load_prefixes([prefix])
2408
return self._kndx_cache[prefix][0][suffix][1]
2410
raise RevisionNotPresent(key, self)
2412
def get_parent_map(self, keys):
2413
"""Get a map of the parents of keys.
2415
:param keys: The keys to look up parents for.
2416
:return: A mapping from keys to parents. Absent keys are absent from
2419
# Parse what we need to up front, this potentially trades off I/O
2420
# locality (.kndx and .knit in the same block group for the same file
2421
# id) for less checking in inner loops.
2422
prefixes = set(key[:-1] for key in keys)
2423
self._load_prefixes(prefixes)
2428
suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
2432
result[key] = tuple(prefix + (suffix,) for
2433
suffix in suffix_parents)
2436
def get_position(self, key):
2437
"""Return details needed to access the version.
2439
:return: a tuple (key, data position, size) to hand to the access
2440
logic to get the record.
2442
prefix, suffix = self._split_key(key)
2443
self._load_prefixes([prefix])
2444
entry = self._kndx_cache[prefix][0][suffix]
2445
return key, entry[2], entry[3]
2447
has_key = _mod_index._has_key_from_parent_map
2449
def _init_index(self, path, extra_lines=[]):
2450
"""Initialize an index."""
2452
sio.write(self.HEADER)
2453
sio.writelines(extra_lines)
2455
self._transport.put_file_non_atomic(path, sio,
2456
create_parent_dir=True)
2457
# self._create_parent_dir)
2458
# mode=self._file_mode,
2459
# dir_mode=self._dir_mode)
2462
"""Get all the keys in the collection.
2464
The keys are not ordered.
2467
# Identify all key prefixes.
2468
# XXX: A bit hacky, needs polish.
2469
if type(self._mapper) == ConstantMapper:
2473
for quoted_relpath in self._transport.iter_files_recursive():
2474
path, ext = os.path.splitext(quoted_relpath)
2476
prefixes = [self._mapper.unmap(path) for path in relpaths]
2477
self._load_prefixes(prefixes)
2478
for prefix in prefixes:
2479
for suffix in self._kndx_cache[prefix][1]:
2480
result.add(prefix + (suffix,))
2483
def _load_prefixes(self, prefixes):
2484
"""Load the indices for prefixes."""
2486
for prefix in prefixes:
2487
if prefix not in self._kndx_cache:
2488
# the load_data interface writes to these variables.
2491
self._filename = prefix
2493
path = self._mapper.map(prefix) + '.kndx'
2494
fp = self._transport.get(path)
2496
# _load_data may raise NoSuchFile if the target knit is
2498
_load_data(self, fp)
2501
self._kndx_cache[prefix] = (self._cache, self._history)
2506
self._kndx_cache[prefix] = ({}, [])
2507
if type(self._mapper) == ConstantMapper:
2508
# preserve behaviour for revisions.kndx etc.
2509
self._init_index(path)
2514
missing_keys = _mod_index._missing_keys_from_parent_map
2516
def _partition_keys(self, keys):
2517
"""Turn keys into a dict of prefix:suffix_list."""
2520
prefix_keys = result.setdefault(key[:-1], [])
2521
prefix_keys.append(key[-1])
2524
def _dictionary_compress(self, keys):
2525
"""Dictionary compress keys.
2527
:param keys: The keys to generate references to.
2528
:return: A string representation of keys. keys which are present are
2529
dictionary compressed, and others are emitted as fulltext with a
2535
prefix = keys[0][:-1]
2536
cache = self._kndx_cache[prefix][0]
2538
if key[:-1] != prefix:
2539
# kndx indices cannot refer across partitioned storage.
2540
raise ValueError("mismatched prefixes for %r" % keys)
2541
if key[-1] in cache:
2542
# -- inlined lookup() --
2543
result_list.append(str(cache[key[-1]][5]))
2544
# -- end lookup () --
2546
result_list.append('.' + key[-1])
2547
return ' '.join(result_list)
2549
def _reset_cache(self):
2550
# Possibly this should be a LRU cache. A dictionary from key_prefix to
2551
# (cache_dict, history_vector) for parsed kndx files.
2552
self._kndx_cache = {}
2553
self._scope = self._get_scope()
2554
allow_writes = self._allow_writes()
2560
def _sort_keys_by_io(self, keys, positions):
2561
"""Figure out an optimal order to read the records for the given keys.
2563
Sort keys, grouped by index and sorted by position.
2565
:param keys: A list of keys whose records we want to read. This will be
2567
:param positions: A dict, such as the one returned by
2568
_get_components_positions()
2571
def get_sort_key(key):
2572
index_memo = positions[key][1]
2573
# Group by prefix and position. index_memo[0] is the key, so it is
2574
# (file_id, revision_id) and we don't want to sort on revision_id,
2575
# index_memo[1] is the position, and index_memo[2] is the size,
2576
# which doesn't matter for the sort
2577
return index_memo[0][:-1], index_memo[1]
2578
return keys.sort(key=get_sort_key)
2580
def _split_key(self, key):
2581
"""Split key into a prefix and suffix."""
2582
return key[:-1], key[-1]
2585
class _KnitGraphIndex(object):
2586
"""A KnitVersionedFiles index layered on GraphIndex."""
2588
def __init__(self, graph_index, is_locked, deltas=False, parents=True,
2590
"""Construct a KnitGraphIndex on a graph_index.
2592
:param graph_index: An implementation of bzrlib.index.GraphIndex.
2593
:param is_locked: A callback to check whether the object should answer
2595
:param deltas: Allow delta-compressed records.
2596
:param parents: If True, record knits parents, if not do not record
2598
:param add_callback: If not None, allow additions to the index and call
2599
this callback with a list of added GraphIndex nodes:
2600
[(node, value, node_refs), ...]
2601
:param is_locked: A callback, returns True if the index is locked and
2604
self._add_callback = add_callback
2605
self._graph_index = graph_index
2606
self._deltas = deltas
2607
self._parents = parents
2608
if deltas and not parents:
2609
# XXX: TODO: Delta tree and parent graph should be conceptually
2611
raise KnitCorrupt(self, "Cannot do delta compression without "
2613
self.has_graph = parents
2614
self._is_locked = is_locked
2615
self._missing_compression_parents = set()
2618
return "%s(%r)" % (self.__class__.__name__, self._graph_index)
2620
def add_records(self, records, random_id=False,
2621
missing_compression_parents=False):
2622
"""Add multiple records to the index.
2624
This function does not insert data into the Immutable GraphIndex
2625
backing the KnitGraphIndex, instead it prepares data for insertion by
2626
the caller and checks that it is safe to insert then calls
2627
self._add_callback with the prepared GraphIndex nodes.
2629
:param records: a list of tuples:
2630
(key, options, access_memo, parents).
2631
:param random_id: If True the ids being added were randomly generated
2632
and no check for existence will be performed.
2633
:param missing_compression_parents: If True the records being added are
2634
only compressed against texts already in the index (or inside
2635
records). If False the records all refer to unavailable texts (or
2636
texts inside records) as compression parents.
2638
if not self._add_callback:
2639
raise errors.ReadOnlyError(self)
2640
# we hope there are no repositories with inconsistent parentage
2644
compression_parents = set()
2645
for (key, options, access_memo, parents) in records:
2647
parents = tuple(parents)
2648
index, pos, size = access_memo
2649
if 'no-eol' in options:
2653
value += "%d %d" % (pos, size)
2654
if not self._deltas:
2655
if 'line-delta' in options:
2656
raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
2659
if 'line-delta' in options:
2660
node_refs = (parents, (parents[0],))
2661
if missing_compression_parents:
2662
compression_parents.add(parents[0])
2664
node_refs = (parents, ())
2666
node_refs = (parents, )
2669
raise KnitCorrupt(self, "attempt to add node with parents "
2670
"in parentless index.")
2672
keys[key] = (value, node_refs)
2675
present_nodes = self._get_entries(keys)
2676
for (index, key, value, node_refs) in present_nodes:
2677
if (value[0] != keys[key][0][0] or
2678
node_refs[:1] != keys[key][1][:1]):
2679
raise KnitCorrupt(self, "inconsistent details in add_records"
2680
": %s %s" % ((value, node_refs), keys[key]))
2684
for key, (value, node_refs) in keys.iteritems():
2685
result.append((key, value, node_refs))
2687
for key, (value, node_refs) in keys.iteritems():
2688
result.append((key, value))
2689
self._add_callback(result)
2690
if missing_compression_parents:
2691
# This may appear to be incorrect (it does not check for
2692
# compression parents that are in the existing graph index),
2693
# but such records won't have been buffered, so this is
2694
# actually correct: every entry when
2695
# missing_compression_parents==True either has a missing parent, or
2696
# a parent that is one of the keys in records.
2697
compression_parents.difference_update(keys)
2698
self._missing_compression_parents.update(compression_parents)
2699
# Adding records may have satisfied missing compression parents.
2700
self._missing_compression_parents.difference_update(keys)
2702
def scan_unvalidated_index(self, graph_index):
2703
"""Inform this _KnitGraphIndex that there is an unvalidated index.
2705
This allows this _KnitGraphIndex to keep track of any missing
2706
compression parents we may want to have filled in to make those
2709
:param graph_index: A GraphIndex
2712
new_missing = graph_index.external_references(ref_list_num=1)
2713
new_missing.difference_update(self.get_parent_map(new_missing))
2714
self._missing_compression_parents.update(new_missing)
2716
def get_missing_compression_parents(self):
2717
"""Return the keys of missing compression parents.
2719
Missing compression parents occur when a record stream was missing
2720
basis texts, or a index was scanned that had missing basis texts.
2722
return frozenset(self._missing_compression_parents)
2724
def _check_read(self):
2725
"""raise if reads are not permitted."""
2726
if not self._is_locked():
2727
raise errors.ObjectNotLocked(self)
2729
def _check_write_ok(self):
2730
"""Assert if writes are not permitted."""
2731
if not self._is_locked():
2732
raise errors.ObjectNotLocked(self)
2734
def _compression_parent(self, an_entry):
2735
# return the key that an_entry is compressed against, or None
2736
# Grab the second parent list (as deltas implies parents currently)
2737
compression_parents = an_entry[3][1]
2738
if not compression_parents:
2740
if len(compression_parents) != 1:
2741
raise AssertionError(
2742
"Too many compression parents: %r" % compression_parents)
2743
return compression_parents[0]
2745
def get_build_details(self, keys):
2746
"""Get the method, index_memo and compression parent for version_ids.
2748
Ghosts are omitted from the result.
2750
:param keys: An iterable of keys.
2751
:return: A dict of key:
2752
(index_memo, compression_parent, parents, record_details).
2754
opaque structure to pass to read_records to extract the raw
2757
Content that this record is built upon, may be None
2759
Logical parents of this node
2761
extra information about the content which needs to be passed to
2762
Factory.parse_record
2766
entries = self._get_entries(keys, False)
2767
for entry in entries:
2769
if not self._parents:
2772
parents = entry[3][0]
2773
if not self._deltas:
2774
compression_parent_key = None
2776
compression_parent_key = self._compression_parent(entry)
2777
noeol = (entry[2][0] == 'N')
2778
if compression_parent_key:
2779
method = 'line-delta'
2782
result[key] = (self._node_to_position(entry),
2783
compression_parent_key, parents,
2787
def _get_entries(self, keys, check_present=False):
2788
"""Get the entries for keys.
2790
:param keys: An iterable of index key tuples.
2795
for node in self._graph_index.iter_entries(keys):
2797
found_keys.add(node[1])
2799
# adapt parentless index to the rest of the code.
2800
for node in self._graph_index.iter_entries(keys):
2801
yield node[0], node[1], node[2], ()
2802
found_keys.add(node[1])
2804
missing_keys = keys.difference(found_keys)
2806
raise RevisionNotPresent(missing_keys.pop(), self)
2808
def get_method(self, key):
2809
"""Return compression method of specified key."""
2810
return self._get_method(self._get_node(key))
2812
def _get_method(self, node):
2813
if not self._deltas:
2815
if self._compression_parent(node):
2820
def _get_node(self, key):
2822
return list(self._get_entries([key]))[0]
2824
raise RevisionNotPresent(key, self)
2826
def get_options(self, key):
2827
"""Return a list representing options.
2831
node = self._get_node(key)
2832
options = [self._get_method(node)]
2833
if node[2][0] == 'N':
2834
options.append('no-eol')
2837
def get_parent_map(self, keys):
2838
"""Get a map of the parents of keys.
2840
:param keys: The keys to look up parents for.
2841
:return: A mapping from keys to parents. Absent keys are absent from
2845
nodes = self._get_entries(keys)
2849
result[node[1]] = node[3][0]
2852
result[node[1]] = None
2855
def get_position(self, key):
2856
"""Return details needed to access the version.
2858
:return: a tuple (index, data position, size) to hand to the access
2859
logic to get the record.
2861
node = self._get_node(key)
2862
return self._node_to_position(node)
2864
has_key = _mod_index._has_key_from_parent_map
2867
"""Get all the keys in the collection.
2869
The keys are not ordered.
2872
return [node[1] for node in self._graph_index.iter_all_entries()]
2874
missing_keys = _mod_index._missing_keys_from_parent_map
2876
def _node_to_position(self, node):
2877
"""Convert an index value to position details."""
2878
bits = node[2][1:].split(' ')
2879
return node[0], int(bits[0]), int(bits[1])
2881
def _sort_keys_by_io(self, keys, positions):
2882
"""Figure out an optimal order to read the records for the given keys.
2884
Sort keys, grouped by index and sorted by position.
2886
:param keys: A list of keys whose records we want to read. This will be
2888
:param positions: A dict, such as the one returned by
2889
_get_components_positions()
2892
def get_index_memo(key):
2893
# index_memo is at offset [1]. It is made up of (GraphIndex,
2894
# position, size). GI is an object, which will be unique for each
2895
# pack file. This causes us to group by pack file, then sort by
2896
# position. Size doesn't matter, but it isn't worth breaking up the
2898
return positions[key][1]
2899
return keys.sort(key=get_index_memo)
2902
class _KnitKeyAccess(object):
2903
"""Access to records in .knit files."""
2905
def __init__(self, transport, mapper):
2906
"""Create a _KnitKeyAccess with transport and mapper.
2908
:param transport: The transport the access object is rooted at.
2909
:param mapper: The mapper used to map keys to .knit files.
2911
self._transport = transport
2912
self._mapper = mapper
2914
def add_raw_records(self, key_sizes, raw_data):
2915
"""Add raw knit bytes to a storage area.
2917
The data is spooled to the container writer in one bytes-record per
2920
:param sizes: An iterable of tuples containing the key and size of each
2922
:param raw_data: A bytestring containing the data.
2923
:return: A list of memos to retrieve the record later. Each memo is an
2924
opaque index memo. For _KnitKeyAccess the memo is (key, pos,
2925
length), where the key is the record key.
2927
if type(raw_data) != str:
2928
raise AssertionError(
2929
'data must be plain bytes was %s' % type(raw_data))
2932
# TODO: This can be tuned for writing to sftp and other servers where
2933
# append() is relatively expensive by grouping the writes to each key
2935
for key, size in key_sizes:
2936
path = self._mapper.map(key)
2938
base = self._transport.append_bytes(path + '.knit',
2939
raw_data[offset:offset+size])
2940
except errors.NoSuchFile:
2941
self._transport.mkdir(osutils.dirname(path))
2942
base = self._transport.append_bytes(path + '.knit',
2943
raw_data[offset:offset+size])
2947
result.append((key, base, size))
2950
def get_raw_records(self, memos_for_retrieval):
2951
"""Get the raw bytes for a records.
2953
:param memos_for_retrieval: An iterable containing the access memo for
2954
retrieving the bytes.
2955
:return: An iterator over the bytes of the records.
2957
# first pass, group into same-index request to minimise readv's issued.
2959
current_prefix = None
2960
for (key, offset, length) in memos_for_retrieval:
2961
if current_prefix == key[:-1]:
2962
current_list.append((offset, length))
2964
if current_prefix is not None:
2965
request_lists.append((current_prefix, current_list))
2966
current_prefix = key[:-1]
2967
current_list = [(offset, length)]
2968
# handle the last entry
2969
if current_prefix is not None:
2970
request_lists.append((current_prefix, current_list))
2971
for prefix, read_vector in request_lists:
2972
path = self._mapper.map(prefix) + '.knit'
2973
for pos, data in self._transport.readv(path, read_vector):
2977
class _DirectPackAccess(object):
2978
"""Access to data in one or more packs with less translation."""
2980
def __init__(self, index_to_packs, reload_func=None):
2981
"""Create a _DirectPackAccess object.
2983
:param index_to_packs: A dict mapping index objects to the transport
2984
and file names for obtaining data.
2985
:param reload_func: A function to call if we determine that the pack
2986
files have moved and we need to reload our caches. See
2987
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
2989
self._container_writer = None
2990
self._write_index = None
2991
self._indices = index_to_packs
2992
self._reload_func = reload_func
2994
def add_raw_records(self, key_sizes, raw_data):
2995
"""Add raw knit bytes to a storage area.
2997
The data is spooled to the container writer in one bytes-record per
3000
:param sizes: An iterable of tuples containing the key and size of each
3002
:param raw_data: A bytestring containing the data.
3003
:return: A list of memos to retrieve the record later. Each memo is an
3004
opaque index memo. For _DirectPackAccess the memo is (index, pos,
3005
length), where the index field is the write_index object supplied
3006
to the PackAccess object.
3008
if type(raw_data) != str:
3009
raise AssertionError(
3010
'data must be plain bytes was %s' % type(raw_data))
3013
for key, size in key_sizes:
3014
p_offset, p_length = self._container_writer.add_bytes_record(
3015
raw_data[offset:offset+size], [])
3017
result.append((self._write_index, p_offset, p_length))
3020
def get_raw_records(self, memos_for_retrieval):
3021
"""Get the raw bytes for a records.
3023
:param memos_for_retrieval: An iterable containing the (index, pos,
3024
length) memo for retrieving the bytes. The Pack access method
3025
looks up the pack to use for a given record in its index_to_pack
3027
:return: An iterator over the bytes of the records.
3029
# first pass, group into same-index requests
3031
current_index = None
3032
for (index, offset, length) in memos_for_retrieval:
3033
if current_index == index:
3034
current_list.append((offset, length))
3036
if current_index is not None:
3037
request_lists.append((current_index, current_list))
3038
current_index = index
3039
current_list = [(offset, length)]
3040
# handle the last entry
3041
if current_index is not None:
3042
request_lists.append((current_index, current_list))
3043
for index, offsets in request_lists:
3045
transport, path = self._indices[index]
3047
# A KeyError here indicates that someone has triggered an index
3048
# reload, and this index has gone missing, we need to start
3050
if self._reload_func is None:
3051
# If we don't have a _reload_func there is nothing that can
3054
raise errors.RetryWithNewPacks(index,
3055
reload_occurred=True,
3056
exc_info=sys.exc_info())
3058
reader = pack.make_readv_reader(transport, path, offsets)
3059
for names, read_func in reader.iter_records():
3060
yield read_func(None)
3061
except errors.NoSuchFile:
3062
# A NoSuchFile error indicates that a pack file has gone
3063
# missing on disk, we need to trigger a reload, and start over.
3064
if self._reload_func is None:
3066
raise errors.RetryWithNewPacks(transport.abspath(path),
3067
reload_occurred=False,
3068
exc_info=sys.exc_info())
3070
def set_writer(self, writer, index, transport_packname):
3071
"""Set a writer to use for adding data."""
3072
if index is not None:
3073
self._indices[index] = transport_packname
3074
self._container_writer = writer
3075
self._write_index = index
3077
def reload_or_raise(self, retry_exc):
3078
"""Try calling the reload function, or re-raise the original exception.
3080
This should be called after _DirectPackAccess raises a
3081
RetryWithNewPacks exception. This function will handle the common logic
3082
of determining when the error is fatal versus being temporary.
3083
It will also make sure that the original exception is raised, rather
3084
than the RetryWithNewPacks exception.
3086
If this function returns, then the calling function should retry
3087
whatever operation was being performed. Otherwise an exception will
3090
:param retry_exc: A RetryWithNewPacks exception.
3093
if self._reload_func is None:
3095
elif not self._reload_func():
3096
# The reload claimed that nothing changed
3097
if not retry_exc.reload_occurred:
3098
# If there wasn't an earlier reload, then we really were
3099
# expecting to find changes. We didn't find them, so this is a
3103
exc_class, exc_value, exc_traceback = retry_exc.exc_info
3104
raise exc_class, exc_value, exc_traceback
3107
# Deprecated, use PatienceSequenceMatcher instead
3108
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
3111
def annotate_knit(knit, revision_id):
3112
"""Annotate a knit with no cached annotations.
3114
This implementation is for knits with no cached annotations.
3115
It will work for knits with cached annotations, but this is not
3118
annotator = _KnitAnnotator(knit)
3119
return iter(annotator.annotate(revision_id))
3122
class _KnitAnnotator(object):
3123
"""Build up the annotations for a text."""
3125
def __init__(self, knit):
3128
# Content objects, differs from fulltexts because of how final newlines
3129
# are treated by knits. the content objects here will always have a
3131
self._fulltext_contents = {}
3133
# Annotated lines of specific revisions
3134
self._annotated_lines = {}
3136
# Track the raw data for nodes that we could not process yet.
3137
# This maps the revision_id of the base to a list of children that will
3138
# annotated from it.
3139
self._pending_children = {}
3141
# Nodes which cannot be extracted
3142
self._ghosts = set()
3144
# Track how many children this node has, so we know if we need to keep
3146
self._annotate_children = {}
3147
self._compression_children = {}
3149
self._all_build_details = {}
3150
# The children => parent revision_id graph
3151
self._revision_id_graph = {}
3153
self._heads_provider = None
3155
self._nodes_to_keep_annotations = set()
3156
self._generations_until_keep = 100
3158
def set_generations_until_keep(self, value):
3159
"""Set the number of generations before caching a node.
3161
Setting this to -1 will cache every merge node, setting this higher
3162
will cache fewer nodes.
3164
self._generations_until_keep = value
3166
def _add_fulltext_content(self, revision_id, content_obj):
3167
self._fulltext_contents[revision_id] = content_obj
3168
# TODO: jam 20080305 It might be good to check the sha1digest here
3169
return content_obj.text()
3171
def _check_parents(self, child, nodes_to_annotate):
3172
"""Check if all parents have been processed.
3174
:param child: A tuple of (rev_id, parents, raw_content)
3175
:param nodes_to_annotate: If child is ready, add it to
3176
nodes_to_annotate, otherwise put it back in self._pending_children
3178
for parent_id in child[1]:
3179
if (parent_id not in self._annotated_lines):
3180
# This parent is present, but another parent is missing
3181
self._pending_children.setdefault(parent_id,
3185
# This one is ready to be processed
3186
nodes_to_annotate.append(child)
3188
def _add_annotation(self, revision_id, fulltext, parent_ids,
3189
left_matching_blocks=None):
3190
"""Add an annotation entry.
3192
All parents should already have been annotated.
3193
:return: A list of children that now have their parents satisfied.
3195
a = self._annotated_lines
3196
annotated_parent_lines = [a[p] for p in parent_ids]
3197
annotated_lines = list(annotate.reannotate(annotated_parent_lines,
3198
fulltext, revision_id, left_matching_blocks,
3199
heads_provider=self._get_heads_provider()))
3200
self._annotated_lines[revision_id] = annotated_lines
3201
for p in parent_ids:
3202
ann_children = self._annotate_children[p]
3203
ann_children.remove(revision_id)
3204
if (not ann_children
3205
and p not in self._nodes_to_keep_annotations):
3206
del self._annotated_lines[p]
3207
del self._all_build_details[p]
3208
if p in self._fulltext_contents:
3209
del self._fulltext_contents[p]
3210
# Now that we've added this one, see if there are any pending
3211
# deltas to be done, certainly this parent is finished
3212
nodes_to_annotate = []
3213
for child in self._pending_children.pop(revision_id, []):
3214
self._check_parents(child, nodes_to_annotate)
3215
return nodes_to_annotate
3217
def _get_build_graph(self, key):
3218
"""Get the graphs for building texts and annotations.
3220
The data you need for creating a full text may be different than the
3221
data you need to annotate that text. (At a minimum, you need both
3222
parents to create an annotation, but only need 1 parent to generate the
3225
:return: A list of (key, index_memo) records, suitable for
3226
passing to read_records_iter to start reading in the raw data fro/
3229
if key in self._annotated_lines:
3232
pending = set([key])
3237
# get all pending nodes
3239
this_iteration = pending
3240
build_details = self._knit._index.get_build_details(this_iteration)
3241
self._all_build_details.update(build_details)
3242
# new_nodes = self._knit._index._get_entries(this_iteration)
3244
for key, details in build_details.iteritems():
3245
(index_memo, compression_parent, parents,
3246
record_details) = details
3247
self._revision_id_graph[key] = parents
3248
records.append((key, index_memo))
3249
# Do we actually need to check _annotated_lines?
3250
pending.update(p for p in parents
3251
if p not in self._all_build_details)
3252
if compression_parent:
3253
self._compression_children.setdefault(compression_parent,
3256
for parent in parents:
3257
self._annotate_children.setdefault(parent,
3259
num_gens = generation - kept_generation
3260
if ((num_gens >= self._generations_until_keep)
3261
and len(parents) > 1):
3262
kept_generation = generation
3263
self._nodes_to_keep_annotations.add(key)
3265
missing_versions = this_iteration.difference(build_details.keys())
3266
self._ghosts.update(missing_versions)
3267
for missing_version in missing_versions:
3268
# add a key, no parents
3269
self._revision_id_graph[missing_version] = ()
3270
pending.discard(missing_version) # don't look for it
3271
if self._ghosts.intersection(self._compression_children):
3273
"We cannot have nodes which have a ghost compression parent:\n"
3275
"compression children: %r"
3276
% (self._ghosts, self._compression_children))
3277
# Cleanout anything that depends on a ghost so that we don't wait for
3278
# the ghost to show up
3279
for node in self._ghosts:
3280
if node in self._annotate_children:
3281
# We won't be building this node
3282
del self._annotate_children[node]
3283
# Generally we will want to read the records in reverse order, because
3284
# we find the parent nodes after the children
3288
def _annotate_records(self, records):
3289
"""Build the annotations for the listed records."""
3290
# We iterate in the order read, rather than a strict order requested
3291
# However, process what we can, and put off to the side things that
3292
# still need parents, cleaning them up when those parents are
3294
for (rev_id, record,
3295
digest) in self._knit._read_records_iter(records):
3296
if rev_id in self._annotated_lines:
3298
parent_ids = self._revision_id_graph[rev_id]
3299
parent_ids = [p for p in parent_ids if p not in self._ghosts]
3300
details = self._all_build_details[rev_id]
3301
(index_memo, compression_parent, parents,
3302
record_details) = details
3303
nodes_to_annotate = []
3304
# TODO: Remove the punning between compression parents, and
3305
# parent_ids, we should be able to do this without assuming
3307
if len(parent_ids) == 0:
3308
# There are no parents for this node, so just add it
3309
# TODO: This probably needs to be decoupled
3310
fulltext_content, delta = self._knit._factory.parse_record(
3311
rev_id, record, record_details, None)
3312
fulltext = self._add_fulltext_content(rev_id, fulltext_content)
3313
nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
3314
parent_ids, left_matching_blocks=None))
3316
child = (rev_id, parent_ids, record)
3317
# Check if all the parents are present
3318
self._check_parents(child, nodes_to_annotate)
3319
while nodes_to_annotate:
3320
# Should we use a queue here instead of a stack?
3321
(rev_id, parent_ids, record) = nodes_to_annotate.pop()
3322
(index_memo, compression_parent, parents,
3323
record_details) = self._all_build_details[rev_id]
3325
if compression_parent is not None:
3326
comp_children = self._compression_children[compression_parent]
3327
if rev_id not in comp_children:
3328
raise AssertionError("%r not in compression children %r"
3329
% (rev_id, comp_children))
3330
# If there is only 1 child, it is safe to reuse this
3332
reuse_content = (len(comp_children) == 1
3333
and compression_parent not in
3334
self._nodes_to_keep_annotations)
3336
# Remove it from the cache since it will be changing
3337
parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
3338
# Make sure to copy the fulltext since it might be
3340
parent_fulltext = list(parent_fulltext_content.text())
3342
parent_fulltext_content = self._fulltext_contents[compression_parent]
3343
parent_fulltext = parent_fulltext_content.text()
3344
comp_children.remove(rev_id)
3345
fulltext_content, delta = self._knit._factory.parse_record(
3346
rev_id, record, record_details,
3347
parent_fulltext_content,
3348
copy_base_content=(not reuse_content))
3349
fulltext = self._add_fulltext_content(rev_id,
3351
if compression_parent == parent_ids[0]:
3352
# the compression_parent is the left parent, so we can
3354
blocks = KnitContent.get_line_delta_blocks(delta,
3355
parent_fulltext, fulltext)
3357
fulltext_content = self._knit._factory.parse_fulltext(
3359
fulltext = self._add_fulltext_content(rev_id,
3361
nodes_to_annotate.extend(
3362
self._add_annotation(rev_id, fulltext, parent_ids,
3363
left_matching_blocks=blocks))
3365
def _get_heads_provider(self):
3366
"""Create a heads provider for resolving ancestry issues."""
3367
if self._heads_provider is not None:
3368
return self._heads_provider
3369
parent_provider = _mod_graph.DictParentsProvider(
3370
self._revision_id_graph)
3371
graph_obj = _mod_graph.Graph(parent_provider)
3372
head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
3373
self._heads_provider = head_cache
3376
def annotate(self, key):
3377
"""Return the annotated fulltext at the given key.
3379
:param key: The key to annotate.
3381
if len(self._knit._fallback_vfs) > 0:
3382
# stacked knits can't use the fast path at present.
3383
return self._simple_annotate(key)
3386
records = self._get_build_graph(key)
3387
if key in self._ghosts:
3388
raise errors.RevisionNotPresent(key, self._knit)
3389
self._annotate_records(records)
3390
return self._annotated_lines[key]
3391
except errors.RetryWithNewPacks, e:
3392
self._knit._access.reload_or_raise(e)
3393
# The cached build_details are no longer valid
3394
self._all_build_details.clear()
3396
def _simple_annotate(self, key):
3397
"""Return annotated fulltext, rediffing from the full texts.
3399
This is slow but makes no assumptions about the repository
3400
being able to produce line deltas.
3402
# TODO: this code generates a parent maps of present ancestors; it
3403
# could be split out into a separate method, and probably should use
3404
# iter_ancestry instead. -- mbp and robertc 20080704
3405
graph = _mod_graph.Graph(self._knit)
3406
head_cache = _mod_graph.FrozenHeadsCache(graph)
3407
search = graph._make_breadth_first_searcher([key])
3411
present, ghosts = search.next_with_ghosts()
3412
except StopIteration:
3414
keys.update(present)
3415
parent_map = self._knit.get_parent_map(keys)
3417
reannotate = annotate.reannotate
3418
for record in self._knit.get_record_stream(keys, 'topological', True):
3420
fulltext = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
3421
parents = parent_map[key]
3422
if parents is not None:
3423
parent_lines = [parent_cache[parent] for parent in parent_map[key]]
3426
parent_cache[key] = list(
3427
reannotate(parent_lines, fulltext, key, None, head_cache))
3429
return parent_cache[key]
3431
raise errors.RevisionNotPresent(key, self._knit)
3435
from bzrlib._knit_load_data_c import _load_data_c as _load_data
3437
from bzrlib._knit_load_data_py import _load_data_py as _load_data