1
# Copyright (C) 2005, 2006, 2007 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 ?
64
from cStringIO import StringIO
66
from itertools import izip, chain
83
from bzrlib.errors import (
91
RevisionAlreadyPresent,
93
from bzrlib.tuned_gzip import GzipFile
94
from bzrlib.trace import mutter
95
from bzrlib.osutils import (
100
from bzrlib.symbol_versioning import DEPRECATED_PARAMETER, deprecated_passed
101
from bzrlib.tsort import topo_sort
104
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
107
# TODO: Split out code specific to this format into an associated object.
109
# TODO: Can we put in some kind of value to check that the index and data
110
# files belong together?
112
# TODO: accommodate binaries, perhaps by storing a byte count
114
# TODO: function to check whole file
116
# TODO: atomically append data, then measure backwards from the cursor
117
# position after writing to work out where it was located. we may need to
118
# bypass python file buffering.
120
DATA_SUFFIX = '.knit'
121
INDEX_SUFFIX = '.kndx'
124
class KnitContent(object):
125
"""Content of a knit version to which deltas can be applied."""
127
def __init__(self, lines):
130
def annotate_iter(self):
131
"""Yield tuples of (origin, text) for each content line."""
132
return iter(self._lines)
135
"""Return a list of (origin, text) tuples."""
136
return list(self.annotate_iter())
138
def line_delta_iter(self, new_lines):
139
"""Generate line-based delta from this content to new_lines."""
140
new_texts = new_lines.text()
141
old_texts = self.text()
142
s = KnitSequenceMatcher(None, old_texts, new_texts)
143
for tag, i1, i2, j1, j2 in s.get_opcodes():
146
# ofrom, oto, length, data
147
yield i1, i2, j2 - j1, new_lines._lines[j1:j2]
149
def line_delta(self, new_lines):
150
return list(self.line_delta_iter(new_lines))
153
return [text for origin, text in self._lines]
156
return KnitContent(self._lines[:])
159
def get_line_delta_blocks(knit_delta, source, target):
160
"""Extract SequenceMatcher.get_matching_blocks() from a knit delta"""
161
target_len = len(target)
164
for s_begin, s_end, t_len, new_text in knit_delta:
165
true_n = s_begin - s_pos
168
# knit deltas do not provide reliable info about whether the
169
# last line of a file matches, due to eol handling.
170
if source[s_pos + n -1] != target[t_pos + n -1]:
173
yield s_pos, t_pos, n
174
t_pos += t_len + true_n
176
n = target_len - t_pos
178
if source[s_pos + n -1] != target[t_pos + n -1]:
181
yield s_pos, t_pos, n
182
yield s_pos + (target_len - t_pos), target_len, 0
185
class _KnitFactory(object):
186
"""Base factory for creating content objects."""
188
def make(self, lines, version_id):
189
num_lines = len(lines)
190
return KnitContent(zip([version_id] * num_lines, lines))
193
class KnitAnnotateFactory(_KnitFactory):
194
"""Factory for creating annotated Content objects."""
198
def parse_fulltext(self, content, version_id):
199
"""Convert fulltext to internal representation
201
fulltext content is of the format
202
revid(utf8) plaintext\n
203
internal representation is of the format:
206
# TODO: jam 20070209 The tests expect this to be returned as tuples,
207
# but the code itself doesn't really depend on that.
208
# Figure out a way to not require the overhead of turning the
209
# list back into tuples.
210
lines = [tuple(line.split(' ', 1)) for line in content]
211
return KnitContent(lines)
213
def parse_line_delta_iter(self, lines):
214
return iter(self.parse_line_delta(lines))
216
def parse_line_delta(self, lines, version_id):
217
"""Convert a line based delta into internal representation.
219
line delta is in the form of:
220
intstart intend intcount
222
revid(utf8) newline\n
223
internal representation is
224
(start, end, count, [1..count tuples (revid, newline)])
231
def cache_and_return(line):
232
origin, text = line.split(' ', 1)
233
return cache.setdefault(origin, origin), text
235
# walk through the lines parsing.
237
start, end, count = [int(n) for n in header.split(',')]
238
contents = [tuple(next().split(' ', 1)) for i in xrange(count)]
239
result.append((start, end, count, contents))
242
def get_fulltext_content(self, lines):
243
"""Extract just the content lines from a fulltext."""
244
return (line.split(' ', 1)[1] for line in lines)
246
def get_linedelta_content(self, lines):
247
"""Extract just the content from a line delta.
249
This doesn't return all of the extra information stored in a delta.
250
Only the actual content lines.
255
header = header.split(',')
256
count = int(header[2])
257
for i in xrange(count):
258
origin, text = next().split(' ', 1)
261
def lower_fulltext(self, content):
262
"""convert a fulltext content record into a serializable form.
264
see parse_fulltext which this inverts.
266
# TODO: jam 20070209 We only do the caching thing to make sure that
267
# the origin is a valid utf-8 line, eventually we could remove it
268
return ['%s %s' % (o, t) for o, t in content._lines]
270
def lower_line_delta(self, delta):
271
"""convert a delta into a serializable form.
273
See parse_line_delta which this inverts.
275
# TODO: jam 20070209 We only do the caching thing to make sure that
276
# the origin is a valid utf-8 line, eventually we could remove it
278
for start, end, c, lines in delta:
279
out.append('%d,%d,%d\n' % (start, end, c))
280
out.extend(origin + ' ' + text
281
for origin, text in lines)
285
class KnitPlainFactory(_KnitFactory):
286
"""Factory for creating plain Content objects."""
290
def parse_fulltext(self, content, version_id):
291
"""This parses an unannotated fulltext.
293
Note that this is not a noop - the internal representation
294
has (versionid, line) - its just a constant versionid.
296
return self.make(content, version_id)
298
def parse_line_delta_iter(self, lines, version_id):
300
num_lines = len(lines)
301
while cur < num_lines:
304
start, end, c = [int(n) for n in header.split(',')]
305
yield start, end, c, zip([version_id] * c, lines[cur:cur+c])
308
def parse_line_delta(self, lines, version_id):
309
return list(self.parse_line_delta_iter(lines, version_id))
311
def get_fulltext_content(self, lines):
312
"""Extract just the content lines from a fulltext."""
315
def get_linedelta_content(self, lines):
316
"""Extract just the content from a line delta.
318
This doesn't return all of the extra information stored in a delta.
319
Only the actual content lines.
324
header = header.split(',')
325
count = int(header[2])
326
for i in xrange(count):
329
def lower_fulltext(self, content):
330
return content.text()
332
def lower_line_delta(self, delta):
334
for start, end, c, lines in delta:
335
out.append('%d,%d,%d\n' % (start, end, c))
336
out.extend([text for origin, text in lines])
340
def make_empty_knit(transport, relpath):
341
"""Construct a empty knit at the specified location."""
342
k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
346
class KnitVersionedFile(VersionedFile):
347
"""Weave-like structure with faster random access.
349
A knit stores a number of texts and a summary of the relationships
350
between them. Texts are identified by a string version-id. Texts
351
are normally stored and retrieved as a series of lines, but can
352
also be passed as single strings.
354
Lines are stored with the trailing newline (if any) included, to
355
avoid special cases for files with no final newline. Lines are
356
composed of 8-bit characters, not unicode. The combination of
357
these approaches should mean any 'binary' file can be safely
358
stored and retrieved.
361
def __init__(self, relpath, transport, file_mode=None, access_mode=None,
362
factory=None, basis_knit=DEPRECATED_PARAMETER, delta=True,
363
create=False, create_parent_dir=False, delay_create=False,
365
"""Construct a knit at location specified by relpath.
367
:param create: If not True, only open an existing knit.
368
:param create_parent_dir: If True, create the parent directory if
369
creating the file fails. (This is used for stores with
370
hash-prefixes that may not exist yet)
371
:param delay_create: The calling code is aware that the knit won't
372
actually be created until the first data is stored.
374
if deprecated_passed(basis_knit):
375
warnings.warn("KnitVersionedFile.__(): The basis_knit parameter is"
376
" deprecated as of bzr 0.9.",
377
DeprecationWarning, stacklevel=2)
378
if access_mode is None:
380
super(KnitVersionedFile, self).__init__(access_mode)
381
assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
382
self.transport = transport
383
self.filename = relpath
384
self.factory = factory or KnitAnnotateFactory()
385
self.writable = (access_mode == 'w')
388
self._max_delta_chain = 200
390
self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
391
access_mode, create=create, file_mode=file_mode,
392
create_parent_dir=create_parent_dir, delay_create=delay_create,
394
self._data = _KnitData(transport, relpath + DATA_SUFFIX,
395
access_mode, create=create and not len(self), file_mode=file_mode,
396
create_parent_dir=create_parent_dir, delay_create=delay_create,
400
return '%s(%s)' % (self.__class__.__name__,
401
self.transport.abspath(self.filename))
403
def _check_should_delta(self, first_parents):
404
"""Iterate back through the parent listing, looking for a fulltext.
406
This is used when we want to decide whether to add a delta or a new
407
fulltext. It searches for _max_delta_chain parents. When it finds a
408
fulltext parent, it sees if the total size of the deltas leading up to
409
it is large enough to indicate that we want a new full text anyway.
411
Return True if we should create a new delta, False if we should use a
416
delta_parents = first_parents
417
for count in xrange(self._max_delta_chain):
418
parent = delta_parents[0]
419
method = self._index.get_method(parent)
420
pos, size = self._index.get_position(parent)
421
if method == 'fulltext':
425
delta_parents = self._index.get_parents(parent)
427
# We couldn't find a fulltext, so we must create a new one
430
return fulltext_size > delta_size
432
def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
433
"""See VersionedFile._add_delta()."""
434
self._check_add(version_id, []) # should we check the lines ?
435
self._check_versions_present(parents)
439
for parent in parents:
440
if not self.has_version(parent):
441
ghosts.append(parent)
443
present_parents.append(parent)
445
if delta_parent is None:
446
# reconstitute as full text.
447
assert len(delta) == 1 or len(delta) == 0
449
assert delta[0][0] == 0
450
assert delta[0][1] == 0, delta[0][1]
451
return super(KnitVersionedFile, self)._add_delta(version_id,
462
options.append('no-eol')
464
if delta_parent is not None:
465
# determine the current delta chain length.
466
# To speed the extract of texts the delta chain is limited
467
# to a fixed number of deltas. This should minimize both
468
# I/O and the time spend applying deltas.
469
# The window was changed to a maximum of 200 deltas, but also added
470
# was a check that the total compressed size of the deltas is
471
# smaller than the compressed size of the fulltext.
472
if not self._check_should_delta([delta_parent]):
473
# We don't want a delta here, just do a normal insertion.
474
return super(KnitVersionedFile, self)._add_delta(version_id,
481
options.append('line-delta')
482
store_lines = self.factory.lower_line_delta(delta)
484
where, size = self._data.add_record(version_id, digest, store_lines)
485
self._index.add_version(version_id, options, where, size, parents)
487
def _add_raw_records(self, records, data):
488
"""Add all the records 'records' with data pre-joined in 'data'.
490
:param records: A list of tuples(version_id, options, parents, size).
491
:param data: The data for the records. When it is written, the records
492
are adjusted to have pos pointing into data by the sum of
493
the preceding records sizes.
496
pos = self._data.add_raw_record(data)
499
for (version_id, options, parents, size) in records:
500
index_entries.append((version_id, options, pos+offset,
502
if self._data._do_cache:
503
self._data._cache[version_id] = data[offset:offset+size]
505
self._index.add_versions(index_entries)
507
def enable_cache(self):
508
"""Start caching data for this knit"""
509
self._data.enable_cache()
511
def clear_cache(self):
512
"""Clear the data cache only."""
513
self._data.clear_cache()
515
def copy_to(self, name, transport):
516
"""See VersionedFile.copy_to()."""
517
# copy the current index to a temp index to avoid racing with local
519
transport.put_file_non_atomic(name + INDEX_SUFFIX + '.tmp',
520
self.transport.get(self._index._filename))
522
f = self._data._open_file()
524
transport.put_file(name + DATA_SUFFIX, f)
527
# move the copied index into place
528
transport.move(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
530
def create_empty(self, name, transport, mode=None):
531
return KnitVersionedFile(name, transport, factory=self.factory,
532
delta=self.delta, create=True)
534
def _fix_parents(self, version_id, new_parents):
535
"""Fix the parents list for version.
537
This is done by appending a new version to the index
538
with identical data except for the parents list.
539
the parents list must be a superset of the current
542
current_values = self._index._cache[version_id]
543
assert set(current_values[4]).difference(set(new_parents)) == set()
544
self._index.add_version(version_id,
550
def _extract_blocks(self, version_id, source, target):
551
if self._index.get_method(version_id) != 'line-delta':
553
parent, sha1, noeol, delta = self.get_delta(version_id)
554
return KnitContent.get_line_delta_blocks(delta, source, target)
556
def get_delta(self, version_id):
557
"""Get a delta for constructing version from some other version."""
558
version_id = osutils.safe_revision_id(version_id)
559
self.check_not_reserved_id(version_id)
560
if not self.has_version(version_id):
561
raise RevisionNotPresent(version_id, self.filename)
563
parents = self.get_parents(version_id)
568
data_pos, data_size = self._index.get_position(version_id)
569
data, sha1 = self._data.read_records(((version_id, data_pos, data_size),))[version_id]
570
noeol = 'no-eol' in self._index.get_options(version_id)
571
if 'fulltext' == self._index.get_method(version_id):
572
new_content = self.factory.parse_fulltext(data, version_id)
573
if parent is not None:
574
reference_content = self._get_content(parent)
575
old_texts = reference_content.text()
578
new_texts = new_content.text()
579
delta_seq = KnitSequenceMatcher(None, old_texts, new_texts)
580
return parent, sha1, noeol, self._make_line_delta(delta_seq, new_content)
582
delta = self.factory.parse_line_delta(data, version_id)
583
return parent, sha1, noeol, delta
585
def get_graph_with_ghosts(self):
586
"""See VersionedFile.get_graph_with_ghosts()."""
587
graph_items = self._index.get_graph()
588
return dict(graph_items)
590
def get_sha1(self, version_id):
591
return self.get_sha1s([version_id])[0]
593
def get_sha1s(self, version_ids):
594
"""See VersionedFile.get_sha1()."""
595
version_ids = [osutils.safe_revision_id(v) for v in version_ids]
596
record_map = self._get_record_map(version_ids)
597
# record entry 2 is the 'digest'.
598
return [record_map[v][2] for v in version_ids]
602
"""See VersionedFile.get_suffixes()."""
603
return [DATA_SUFFIX, INDEX_SUFFIX]
605
def has_ghost(self, version_id):
606
"""True if there is a ghost reference in the file to version_id."""
607
version_id = osutils.safe_revision_id(version_id)
609
if self.has_version(version_id):
611
# optimisable if needed by memoising the _ghosts set.
612
items = self._index.get_graph()
613
for node, parents in items:
614
for parent in parents:
615
if parent not in self._index._cache:
616
if parent == version_id:
621
"""See VersionedFile.versions."""
622
return self._index.get_versions()
624
def has_version(self, version_id):
625
"""See VersionedFile.has_version."""
626
version_id = osutils.safe_revision_id(version_id)
627
return self._index.has_version(version_id)
629
__contains__ = has_version
631
def _merge_annotations(self, content, parents, parent_texts={},
632
delta=None, annotated=None,
633
left_matching_blocks=None):
634
"""Merge annotations for content. This is done by comparing
635
the annotations based on changed to the text.
639
for parent_id in parents:
640
merge_content = self._get_content(parent_id, parent_texts)
641
if (parent_id == parents[0] and
642
left_matching_blocks is not None):
643
seq = diff._PrematchedMatcher(left_matching_blocks)
645
seq = patiencediff.PatienceSequenceMatcher(
646
None, merge_content.text(), content.text())
647
if delta_seq is None:
648
# setup a delta seq to reuse.
650
for i, j, n in seq.get_matching_blocks():
653
# this appears to copy (origin, text) pairs across to the new
654
# content for any line that matches the last-checked parent.
655
# FIXME: save the sequence control data for delta compression
656
# against the most relevant parent rather than rediffing.
657
content._lines[j:j+n] = merge_content._lines[i:i+n]
660
reference_content = self._get_content(parents[0], parent_texts)
661
new_texts = content.text()
662
old_texts = reference_content.text()
663
delta_seq = patiencediff.PatienceSequenceMatcher(
664
None, old_texts, new_texts)
665
return self._make_line_delta(delta_seq, content)
667
def _make_line_delta(self, delta_seq, new_content):
668
"""Generate a line delta from delta_seq and new_content."""
670
for op in delta_seq.get_opcodes():
673
diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
676
def _get_components_positions(self, version_ids):
677
"""Produce a map of position data for the components of versions.
679
This data is intended to be used for retrieving the knit records.
681
A dict of version_id to (method, data_pos, data_size, next) is
683
method is the way referenced data should be applied.
684
data_pos is the position of the data in the knit.
685
data_size is the size of the data in the knit.
686
next is the build-parent of the version, or None for fulltexts.
689
for version_id in version_ids:
692
while cursor is not None and cursor not in component_data:
693
method = self._index.get_method(cursor)
694
if method == 'fulltext':
697
next = self.get_parents(cursor)[0]
698
data_pos, data_size = self._index.get_position(cursor)
699
component_data[cursor] = (method, data_pos, data_size, next)
701
return component_data
703
def _get_content(self, version_id, parent_texts={}):
704
"""Returns a content object that makes up the specified
706
if not self.has_version(version_id):
707
raise RevisionNotPresent(version_id, self.filename)
709
cached_version = parent_texts.get(version_id, None)
710
if cached_version is not None:
711
return cached_version
713
text_map, contents_map = self._get_content_maps([version_id])
714
return contents_map[version_id]
716
def _check_versions_present(self, version_ids):
717
"""Check that all specified versions are present."""
718
self._index.check_versions_present(version_ids)
720
def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
721
"""See VersionedFile.add_lines_with_ghosts()."""
722
self._check_add(version_id, lines)
723
return self._add(version_id, lines[:], parents, self.delta, parent_texts)
725
def _add_lines(self, version_id, parents, lines, parent_texts,
726
left_matching_blocks=None):
727
"""See VersionedFile.add_lines."""
728
self._check_add(version_id, lines)
729
self._check_versions_present(parents)
730
return self._add(version_id, lines[:], parents, self.delta,
731
parent_texts, left_matching_blocks)
733
def _check_add(self, version_id, lines):
734
"""check that version_id and lines are safe to add."""
735
assert self.writable, "knit is not opened for write"
736
### FIXME escape. RBC 20060228
737
if contains_whitespace(version_id):
738
raise InvalidRevisionId(version_id, self.filename)
739
self.check_not_reserved_id(version_id)
740
if self.has_version(version_id):
741
raise RevisionAlreadyPresent(version_id, self.filename)
742
self._check_lines_not_unicode(lines)
743
self._check_lines_are_lines(lines)
745
def _add(self, version_id, lines, parents, delta, parent_texts,
746
left_matching_blocks=None):
747
"""Add a set of lines on top of version specified by parents.
749
If delta is true, compress the text as a line-delta against
752
Any versions not present will be converted into ghosts.
754
# 461 0 6546.0390 43.9100 bzrlib.knit:489(_add)
755
# +400 0 889.4890 418.9790 +bzrlib.knit:192(lower_fulltext)
756
# +461 0 1364.8070 108.8030 +bzrlib.knit:996(add_record)
757
# +461 0 193.3940 41.5720 +bzrlib.knit:898(add_version)
758
# +461 0 134.0590 18.3810 +bzrlib.osutils:361(sha_strings)
759
# +461 0 36.3420 15.4540 +bzrlib.knit:146(make)
760
# +1383 0 8.0370 8.0370 +<len>
761
# +61 0 13.5770 7.9190 +bzrlib.knit:199(lower_line_delta)
762
# +61 0 963.3470 7.8740 +bzrlib.knit:427(_get_content)
763
# +61 0 973.9950 5.2950 +bzrlib.knit:136(line_delta)
764
# +61 0 1918.1800 5.2640 +bzrlib.knit:359(_merge_annotations)
768
if parent_texts is None:
770
for parent in parents:
771
if not self.has_version(parent):
772
ghosts.append(parent)
774
present_parents.append(parent)
776
if delta and not len(present_parents):
779
digest = sha_strings(lines)
782
if lines[-1][-1] != '\n':
783
options.append('no-eol')
784
lines[-1] = lines[-1] + '\n'
786
if len(present_parents) and delta:
787
# To speed the extract of texts the delta chain is limited
788
# to a fixed number of deltas. This should minimize both
789
# I/O and the time spend applying deltas.
790
delta = self._check_should_delta(present_parents)
792
assert isinstance(version_id, str)
793
lines = self.factory.make(lines, version_id)
794
if delta or (self.factory.annotated and len(present_parents) > 0):
795
# Merge annotations from parent texts if so is needed.
796
delta_hunks = self._merge_annotations(lines, present_parents,
797
parent_texts, delta, self.factory.annotated,
798
left_matching_blocks)
801
options.append('line-delta')
802
store_lines = self.factory.lower_line_delta(delta_hunks)
804
options.append('fulltext')
805
store_lines = self.factory.lower_fulltext(lines)
807
where, size = self._data.add_record(version_id, digest, store_lines)
808
self._index.add_version(version_id, options, where, size, parents)
811
def check(self, progress_bar=None):
812
"""See VersionedFile.check()."""
814
def _clone_text(self, new_version_id, old_version_id, parents):
815
"""See VersionedFile.clone_text()."""
816
# FIXME RBC 20060228 make fast by only inserting an index with null
818
self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
820
def get_lines(self, version_id):
821
"""See VersionedFile.get_lines()."""
822
return self.get_line_list([version_id])[0]
824
def _get_record_map(self, version_ids):
825
"""Produce a dictionary of knit records.
827
The keys are version_ids, the values are tuples of (method, content,
829
method is the way the content should be applied.
830
content is a KnitContent object.
831
digest is the SHA1 digest of this version id after all steps are done
832
next is the build-parent of the version, i.e. the leftmost ancestor.
833
If the method is fulltext, next will be None.
835
position_map = self._get_components_positions(version_ids)
836
# c = component_id, m = method, p = position, s = size, n = next
837
records = [(c, p, s) for c, (m, p, s, n) in position_map.iteritems()]
839
for component_id, content, digest in \
840
self._data.read_records_iter(records):
841
method, position, size, next = position_map[component_id]
842
record_map[component_id] = method, content, digest, next
846
def get_text(self, version_id):
847
"""See VersionedFile.get_text"""
848
return self.get_texts([version_id])[0]
850
def get_texts(self, version_ids):
851
return [''.join(l) for l in self.get_line_list(version_ids)]
853
def get_line_list(self, version_ids):
854
"""Return the texts of listed versions as a list of strings."""
855
version_ids = [osutils.safe_revision_id(v) for v in version_ids]
856
for version_id in version_ids:
857
self.check_not_reserved_id(version_id)
858
text_map, content_map = self._get_content_maps(version_ids)
859
return [text_map[v] for v in version_ids]
861
_get_lf_split_line_list = get_line_list
863
def _get_content_maps(self, version_ids):
864
"""Produce maps of text and KnitContents
866
:return: (text_map, content_map) where text_map contains the texts for
867
the requested versions and content_map contains the KnitContents.
868
Both dicts take version_ids as their keys.
870
for version_id in version_ids:
871
if not self.has_version(version_id):
872
raise RevisionNotPresent(version_id, self.filename)
873
record_map = self._get_record_map(version_ids)
878
for version_id in version_ids:
881
while cursor is not None:
882
method, data, digest, next = record_map[cursor]
883
components.append((cursor, method, data, digest))
884
if cursor in content_map:
889
for component_id, method, data, digest in reversed(components):
890
if component_id in content_map:
891
content = content_map[component_id]
893
if method == 'fulltext':
894
assert content is None
895
content = self.factory.parse_fulltext(data, version_id)
896
elif method == 'line-delta':
897
delta = self.factory.parse_line_delta(data, version_id)
898
content = content.copy()
899
content._lines = self._apply_delta(content._lines,
901
content_map[component_id] = content
903
if 'no-eol' in self._index.get_options(version_id):
904
content = content.copy()
905
line = content._lines[-1][1].rstrip('\n')
906
content._lines[-1] = (content._lines[-1][0], line)
907
final_content[version_id] = content
909
# digest here is the digest from the last applied component.
910
text = content.text()
911
if sha_strings(text) != digest:
912
raise KnitCorrupt(self.filename,
913
'sha-1 does not match %s' % version_id)
915
text_map[version_id] = text
916
return text_map, final_content
918
def iter_lines_added_or_present_in_versions(self, version_ids=None,
920
"""See VersionedFile.iter_lines_added_or_present_in_versions()."""
921
if version_ids is None:
922
version_ids = self.versions()
924
version_ids = [osutils.safe_revision_id(v) for v in version_ids]
926
pb = progress.DummyProgress()
927
# we don't care about inclusions, the caller cares.
928
# but we need to setup a list of records to visit.
929
# we need version_id, position, length
930
version_id_records = []
931
requested_versions = set(version_ids)
932
# filter for available versions
933
for version_id in requested_versions:
934
if not self.has_version(version_id):
935
raise RevisionNotPresent(version_id, self.filename)
936
# get a in-component-order queue:
937
for version_id in self.versions():
938
if version_id in requested_versions:
939
data_pos, length = self._index.get_position(version_id)
940
version_id_records.append((version_id, data_pos, length))
942
total = len(version_id_records)
943
for version_idx, (version_id, data, sha_value) in \
944
enumerate(self._data.read_records_iter(version_id_records)):
945
pb.update('Walking content.', version_idx, total)
946
method = self._index.get_method(version_id)
948
assert method in ('fulltext', 'line-delta')
949
if method == 'fulltext':
950
line_iterator = self.factory.get_fulltext_content(data)
952
line_iterator = self.factory.get_linedelta_content(data)
953
for line in line_iterator:
956
pb.update('Walking content.', total, total)
958
def num_versions(self):
959
"""See VersionedFile.num_versions()."""
960
return self._index.num_versions()
962
__len__ = num_versions
964
def annotate_iter(self, version_id):
965
"""See VersionedFile.annotate_iter."""
966
version_id = osutils.safe_revision_id(version_id)
967
content = self._get_content(version_id)
968
for origin, text in content.annotate_iter():
971
def get_parents(self, version_id):
972
"""See VersionedFile.get_parents."""
975
# 52554 calls in 1264 872 internal down from 3674
976
version_id = osutils.safe_revision_id(version_id)
978
return self._index.get_parents(version_id)
980
raise RevisionNotPresent(version_id, self.filename)
982
def get_parents_with_ghosts(self, version_id):
983
"""See VersionedFile.get_parents."""
984
version_id = osutils.safe_revision_id(version_id)
986
return self._index.get_parents_with_ghosts(version_id)
988
raise RevisionNotPresent(version_id, self.filename)
990
def get_ancestry(self, versions, topo_sorted=True):
991
"""See VersionedFile.get_ancestry."""
992
if isinstance(versions, basestring):
993
versions = [versions]
996
versions = [osutils.safe_revision_id(v) for v in versions]
997
return self._index.get_ancestry(versions, topo_sorted)
999
def get_ancestry_with_ghosts(self, versions):
1000
"""See VersionedFile.get_ancestry_with_ghosts."""
1001
if isinstance(versions, basestring):
1002
versions = [versions]
1005
versions = [osutils.safe_revision_id(v) for v in versions]
1006
return self._index.get_ancestry_with_ghosts(versions)
1008
#@deprecated_method(zero_eight)
1009
def walk(self, version_ids):
1010
"""See VersionedFile.walk."""
1011
# We take the short path here, and extract all relevant texts
1012
# and put them in a weave and let that do all the work. Far
1013
# from optimal, but is much simpler.
1014
# FIXME RB 20060228 this really is inefficient!
1015
from bzrlib.weave import Weave
1017
w = Weave(self.filename)
1018
ancestry = set(self.get_ancestry(version_ids, topo_sorted=False))
1019
sorted_graph = topo_sort(self._index.get_graph())
1020
version_list = [vid for vid in sorted_graph if vid in ancestry]
1022
for version_id in version_list:
1023
lines = self.get_lines(version_id)
1024
w.add_lines(version_id, self.get_parents(version_id), lines)
1026
for lineno, insert_id, dset, line in w.walk(version_ids):
1027
yield lineno, insert_id, dset, line
1029
def plan_merge(self, ver_a, ver_b):
1030
"""See VersionedFile.plan_merge."""
1031
ver_a = osutils.safe_revision_id(ver_a)
1032
ver_b = osutils.safe_revision_id(ver_b)
1033
ancestors_b = set(self.get_ancestry(ver_b, topo_sorted=False))
1035
ancestors_a = set(self.get_ancestry(ver_a, topo_sorted=False))
1036
annotated_a = self.annotate(ver_a)
1037
annotated_b = self.annotate(ver_b)
1038
return merge._plan_annotate_merge(annotated_a, annotated_b,
1039
ancestors_a, ancestors_b)
1042
class _KnitComponentFile(object):
1043
"""One of the files used to implement a knit database"""
1045
def __init__(self, transport, filename, mode, file_mode=None,
1046
create_parent_dir=False, dir_mode=None):
1047
self._transport = transport
1048
self._filename = filename
1050
self._file_mode = file_mode
1051
self._dir_mode = dir_mode
1052
self._create_parent_dir = create_parent_dir
1053
self._need_to_create = False
1055
def _full_path(self):
1056
"""Return the full path to this file."""
1057
return self._transport.base + self._filename
1059
def check_header(self, fp):
1060
line = fp.readline()
1062
# An empty file can actually be treated as though the file doesn't
1064
raise errors.NoSuchFile(self._full_path())
1065
if line != self.HEADER:
1066
raise KnitHeaderError(badline=line,
1067
filename=self._transport.abspath(self._filename))
1070
"""Commit is a nop."""
1073
return '%s(%s)' % (self.__class__.__name__, self._filename)
1076
class _KnitIndex(_KnitComponentFile):
1077
"""Manages knit index file.
1079
The index is already kept in memory and read on startup, to enable
1080
fast lookups of revision information. The cursor of the index
1081
file is always pointing to the end, making it easy to append
1084
_cache is a cache for fast mapping from version id to a Index
1087
_history is a cache for fast mapping from indexes to version ids.
1089
The index data format is dictionary compressed when it comes to
1090
parent references; a index entry may only have parents that with a
1091
lover index number. As a result, the index is topological sorted.
1093
Duplicate entries may be written to the index for a single version id
1094
if this is done then the latter one completely replaces the former:
1095
this allows updates to correct version and parent information.
1096
Note that the two entries may share the delta, and that successive
1097
annotations and references MUST point to the first entry.
1099
The index file on disc contains a header, followed by one line per knit
1100
record. The same revision can be present in an index file more than once.
1101
The first occurrence gets assigned a sequence number starting from 0.
1103
The format of a single line is
1104
REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
1105
REVISION_ID is a utf8-encoded revision id
1106
FLAGS is a comma separated list of flags about the record. Values include
1107
no-eol, line-delta, fulltext.
1108
BYTE_OFFSET is the ascii representation of the byte offset in the data file
1109
that the the compressed data starts at.
1110
LENGTH is the ascii representation of the length of the data file.
1111
PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
1113
PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
1114
revision id already in the knit that is a parent of REVISION_ID.
1115
The ' :' marker is the end of record marker.
1118
when a write is interrupted to the index file, it will result in a line
1119
that does not end in ' :'. If the ' :' is not present at the end of a line,
1120
or at the end of the file, then the record that is missing it will be
1121
ignored by the parser.
1123
When writing new records to the index file, the data is preceded by '\n'
1124
to ensure that records always start on new lines even if the last write was
1125
interrupted. As a result its normal for the last line in the index to be
1126
missing a trailing newline. One can be added with no harmful effects.
1129
HEADER = "# bzr knit index 8\n"
1131
# speed of knit parsing went from 280 ms to 280 ms with slots addition.
1132
# __slots__ = ['_cache', '_history', '_transport', '_filename']
1134
def _cache_version(self, version_id, options, pos, size, parents):
1135
"""Cache a version record in the history array and index cache.
1137
This is inlined into _load_data for performance. KEEP IN SYNC.
1138
(It saves 60ms, 25% of the __init__ overhead on local 4000 record
1141
# only want the _history index to reference the 1st index entry
1143
if version_id not in self._cache:
1144
index = len(self._history)
1145
self._history.append(version_id)
1147
index = self._cache[version_id][5]
1148
self._cache[version_id] = (version_id,
1155
def __init__(self, transport, filename, mode, create=False, file_mode=None,
1156
create_parent_dir=False, delay_create=False, dir_mode=None):
1157
_KnitComponentFile.__init__(self, transport, filename, mode,
1158
file_mode=file_mode,
1159
create_parent_dir=create_parent_dir,
1162
# position in _history is the 'official' index for a revision
1163
# but the values may have come from a newer entry.
1164
# so - wc -l of a knit index is != the number of unique names
1168
fp = self._transport.get(self._filename)
1170
# _load_data may raise NoSuchFile if the target knit is
1172
_load_data(self, fp)
1176
if mode != 'w' or not create:
1179
self._need_to_create = True
1181
self._transport.put_bytes_non_atomic(
1182
self._filename, self.HEADER, mode=self._file_mode)
1184
def get_graph(self):
1185
return [(vid, idx[4]) for vid, idx in self._cache.iteritems()]
1187
def get_ancestry(self, versions, topo_sorted=True):
1188
"""See VersionedFile.get_ancestry."""
1189
# get a graph of all the mentioned versions:
1191
pending = set(versions)
1194
version = pending.pop()
1197
parents = [p for p in cache[version][4] if p in cache]
1199
raise RevisionNotPresent(version, self._filename)
1200
# if not completed and not a ghost
1201
pending.update([p for p in parents if p not in graph])
1202
graph[version] = parents
1205
return topo_sort(graph.items())
1207
def get_ancestry_with_ghosts(self, versions):
1208
"""See VersionedFile.get_ancestry_with_ghosts."""
1209
# get a graph of all the mentioned versions:
1210
self.check_versions_present(versions)
1213
pending = set(versions)
1215
version = pending.pop()
1217
parents = cache[version][4]
1223
pending.update([p for p in parents if p not in graph])
1224
graph[version] = parents
1225
return topo_sort(graph.items())
1227
def num_versions(self):
1228
return len(self._history)
1230
__len__ = num_versions
1232
def get_versions(self):
1233
return self._history
1235
def idx_to_name(self, idx):
1236
return self._history[idx]
1238
def lookup(self, version_id):
1239
assert version_id in self._cache
1240
return self._cache[version_id][5]
1242
def _version_list_to_index(self, versions):
1245
for version in versions:
1246
if version in cache:
1247
# -- inlined lookup() --
1248
result_list.append(str(cache[version][5]))
1249
# -- end lookup () --
1251
result_list.append('.' + version)
1252
return ' '.join(result_list)
1254
def add_version(self, version_id, options, pos, size, parents):
1255
"""Add a version record to the index."""
1256
self.add_versions(((version_id, options, pos, size, parents),))
1258
def add_versions(self, versions):
1259
"""Add multiple versions to the index.
1261
:param versions: a list of tuples:
1262
(version_id, options, pos, size, parents).
1265
orig_history = self._history[:]
1266
orig_cache = self._cache.copy()
1269
for version_id, options, pos, size, parents in versions:
1270
line = "\n%s %s %s %s %s :" % (version_id,
1274
self._version_list_to_index(parents))
1275
assert isinstance(line, str), \
1276
'content must be utf-8 encoded: %r' % (line,)
1278
self._cache_version(version_id, options, pos, size, parents)
1279
if not self._need_to_create:
1280
self._transport.append_bytes(self._filename, ''.join(lines))
1283
sio.write(self.HEADER)
1284
sio.writelines(lines)
1286
self._transport.put_file_non_atomic(self._filename, sio,
1287
create_parent_dir=self._create_parent_dir,
1288
mode=self._file_mode,
1289
dir_mode=self._dir_mode)
1290
self._need_to_create = False
1292
# If any problems happen, restore the original values and re-raise
1293
self._history = orig_history
1294
self._cache = orig_cache
1297
def has_version(self, version_id):
1298
"""True if the version is in the index."""
1299
return version_id in self._cache
1301
def get_position(self, version_id):
1302
"""Return data position and size of specified version."""
1303
entry = self._cache[version_id]
1304
return entry[2], entry[3]
1306
def get_method(self, version_id):
1307
"""Return compression method of specified version."""
1308
options = self._cache[version_id][1]
1309
if 'fulltext' in options:
1312
if 'line-delta' not in options:
1313
raise errors.KnitIndexUnknownMethod(self._full_path(), options)
1316
def get_options(self, version_id):
1317
return self._cache[version_id][1]
1319
def get_parents(self, version_id):
1320
"""Return parents of specified version ignoring ghosts."""
1321
return [parent for parent in self._cache[version_id][4]
1322
if parent in self._cache]
1324
def get_parents_with_ghosts(self, version_id):
1325
"""Return parents of specified version with ghosts."""
1326
return self._cache[version_id][4]
1328
def check_versions_present(self, version_ids):
1329
"""Check that all specified versions are present."""
1331
for version_id in version_ids:
1332
if version_id not in cache:
1333
raise RevisionNotPresent(version_id, self._filename)
1336
class _KnitData(_KnitComponentFile):
1337
"""Contents of the knit data file"""
1339
def __init__(self, transport, filename, mode, create=False, file_mode=None,
1340
create_parent_dir=False, delay_create=False,
1342
_KnitComponentFile.__init__(self, transport, filename, mode,
1343
file_mode=file_mode,
1344
create_parent_dir=create_parent_dir,
1346
self._checked = False
1347
# TODO: jam 20060713 conceptually, this could spill to disk
1348
# if the cached size gets larger than a certain amount
1349
# but it complicates the model a bit, so for now just use
1350
# a simple dictionary
1352
self._do_cache = False
1355
self._need_to_create = create
1357
self._transport.put_bytes_non_atomic(self._filename, '',
1358
mode=self._file_mode)
1360
def enable_cache(self):
1361
"""Enable caching of reads."""
1362
self._do_cache = True
1364
def clear_cache(self):
1365
"""Clear the record cache."""
1366
self._do_cache = False
1369
def _open_file(self):
1371
return self._transport.get(self._filename)
1376
def _record_to_data(self, version_id, digest, lines):
1377
"""Convert version_id, digest, lines into a raw data block.
1379
:return: (len, a StringIO instance with the raw data ready to read.)
1382
data_file = GzipFile(None, mode='wb', fileobj=sio)
1384
assert isinstance(version_id, str)
1385
data_file.writelines(chain(
1386
["version %s %d %s\n" % (version_id,
1390
["end %s\n" % version_id]))
1397
def add_raw_record(self, raw_data):
1398
"""Append a prepared record to the data file.
1400
:return: the offset in the data file raw_data was written.
1402
assert isinstance(raw_data, str), 'data must be plain bytes'
1403
if not self._need_to_create:
1404
return self._transport.append_bytes(self._filename, raw_data)
1406
self._transport.put_bytes_non_atomic(self._filename, raw_data,
1407
create_parent_dir=self._create_parent_dir,
1408
mode=self._file_mode,
1409
dir_mode=self._dir_mode)
1410
self._need_to_create = False
1413
def add_record(self, version_id, digest, lines):
1414
"""Write new text record to disk. Returns the position in the
1415
file where it was written."""
1416
size, sio = self._record_to_data(version_id, digest, lines)
1418
if not self._need_to_create:
1419
start_pos = self._transport.append_file(self._filename, sio)
1421
self._transport.put_file_non_atomic(self._filename, sio,
1422
create_parent_dir=self._create_parent_dir,
1423
mode=self._file_mode,
1424
dir_mode=self._dir_mode)
1425
self._need_to_create = False
1428
self._cache[version_id] = sio.getvalue()
1429
return start_pos, size
1431
def _parse_record_header(self, version_id, raw_data):
1432
"""Parse a record header for consistency.
1434
:return: the header and the decompressor stream.
1435
as (stream, header_record)
1437
df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
1439
rec = self._check_header(version_id, df.readline())
1440
except Exception, e:
1441
raise KnitCorrupt(self._filename,
1442
"While reading {%s} got %s(%s)"
1443
% (version_id, e.__class__.__name__, str(e)))
1446
def _check_header(self, version_id, line):
1449
raise KnitCorrupt(self._filename,
1450
'unexpected number of elements in record header')
1451
if rec[1] != version_id:
1452
raise KnitCorrupt(self._filename,
1453
'unexpected version, wanted %r, got %r'
1454
% (version_id, rec[1]))
1457
def _parse_record(self, version_id, data):
1459
# 4168 calls in 2880 217 internal
1460
# 4168 calls to _parse_record_header in 2121
1461
# 4168 calls to readlines in 330
1462
df = GzipFile(mode='rb', fileobj=StringIO(data))
1465
record_contents = df.readlines()
1466
except Exception, e:
1467
raise KnitCorrupt(self._filename,
1468
"While reading {%s} got %s(%s)"
1469
% (version_id, e.__class__.__name__, str(e)))
1470
header = record_contents.pop(0)
1471
rec = self._check_header(version_id, header)
1473
last_line = record_contents.pop()
1474
if len(record_contents) != int(rec[2]):
1475
raise KnitCorrupt(self._filename,
1476
'incorrect number of lines %s != %s'
1478
% (len(record_contents), int(rec[2]),
1480
if last_line != 'end %s\n' % rec[1]:
1481
raise KnitCorrupt(self._filename,
1482
'unexpected version end line %r, wanted %r'
1483
% (last_line, version_id))
1485
return record_contents, rec[3]
1487
def read_records_iter_raw(self, records):
1488
"""Read text records from data file and yield raw data.
1490
This unpacks enough of the text record to validate the id is
1491
as expected but thats all.
1493
# setup an iterator of the external records:
1494
# uses readv so nice and fast we hope.
1496
# grab the disk data needed.
1498
# Don't check _cache if it is empty
1499
needed_offsets = [(pos, size) for version_id, pos, size
1501
if version_id not in self._cache]
1503
needed_offsets = [(pos, size) for version_id, pos, size
1506
raw_records = self._transport.readv(self._filename, needed_offsets)
1508
for version_id, pos, size in records:
1509
if version_id in self._cache:
1510
# This data has already been validated
1511
data = self._cache[version_id]
1513
pos, data = raw_records.next()
1515
self._cache[version_id] = data
1517
# validate the header
1518
df, rec = self._parse_record_header(version_id, data)
1520
yield version_id, data
1522
def read_records_iter(self, records):
1523
"""Read text records from data file and yield result.
1525
The result will be returned in whatever is the fastest to read.
1526
Not by the order requested. Also, multiple requests for the same
1527
record will only yield 1 response.
1528
:param records: A list of (version_id, pos, len) entries
1529
:return: Yields (version_id, contents, digest) in the order
1530
read, not the order requested
1536
# Skip records we have alread seen
1537
yielded_records = set()
1538
needed_records = set()
1539
for record in records:
1540
if record[0] in self._cache:
1541
if record[0] in yielded_records:
1543
yielded_records.add(record[0])
1544
data = self._cache[record[0]]
1545
content, digest = self._parse_record(record[0], data)
1546
yield (record[0], content, digest)
1548
needed_records.add(record)
1549
needed_records = sorted(needed_records, key=operator.itemgetter(1))
1551
needed_records = sorted(set(records), key=operator.itemgetter(1))
1553
if not needed_records:
1556
# The transport optimizes the fetching as well
1557
# (ie, reads continuous ranges.)
1558
readv_response = self._transport.readv(self._filename,
1559
[(pos, size) for version_id, pos, size in needed_records])
1561
for (version_id, pos, size), (pos, data) in \
1562
izip(iter(needed_records), readv_response):
1563
content, digest = self._parse_record(version_id, data)
1565
self._cache[version_id] = data
1566
yield version_id, content, digest
1568
def read_records(self, records):
1569
"""Read records into a dictionary."""
1571
for record_id, content, digest in \
1572
self.read_records_iter(records):
1573
components[record_id] = (content, digest)
1577
class InterKnit(InterVersionedFile):
1578
"""Optimised code paths for knit to knit operations."""
1580
_matching_file_from_factory = KnitVersionedFile
1581
_matching_file_to_factory = KnitVersionedFile
1584
def is_compatible(source, target):
1585
"""Be compatible with knits. """
1587
return (isinstance(source, KnitVersionedFile) and
1588
isinstance(target, KnitVersionedFile))
1589
except AttributeError:
1592
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1593
"""See InterVersionedFile.join."""
1594
assert isinstance(self.source, KnitVersionedFile)
1595
assert isinstance(self.target, KnitVersionedFile)
1597
version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1602
pb = ui.ui_factory.nested_progress_bar()
1604
version_ids = list(version_ids)
1605
if None in version_ids:
1606
version_ids.remove(None)
1608
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1609
this_versions = set(self.target._index.get_versions())
1610
needed_versions = self.source_ancestry - this_versions
1611
cross_check_versions = self.source_ancestry.intersection(this_versions)
1612
mismatched_versions = set()
1613
for version in cross_check_versions:
1614
# scan to include needed parents.
1615
n1 = set(self.target.get_parents_with_ghosts(version))
1616
n2 = set(self.source.get_parents_with_ghosts(version))
1618
# FIXME TEST this check for cycles being introduced works
1619
# the logic is we have a cycle if in our graph we are an
1620
# ancestor of any of the n2 revisions.
1626
parent_ancestors = self.source.get_ancestry(parent)
1627
if version in parent_ancestors:
1628
raise errors.GraphCycleError([parent, version])
1629
# ensure this parent will be available later.
1630
new_parents = n2.difference(n1)
1631
needed_versions.update(new_parents.difference(this_versions))
1632
mismatched_versions.add(version)
1634
if not needed_versions and not mismatched_versions:
1636
full_list = topo_sort(self.source.get_graph())
1638
version_list = [i for i in full_list if (not self.target.has_version(i)
1639
and i in needed_versions)]
1643
copy_queue_records = []
1645
for version_id in version_list:
1646
options = self.source._index.get_options(version_id)
1647
parents = self.source._index.get_parents_with_ghosts(version_id)
1648
# check that its will be a consistent copy:
1649
for parent in parents:
1650
# if source has the parent, we must :
1651
# * already have it or
1652
# * have it scheduled already
1653
# otherwise we don't care
1654
assert (self.target.has_version(parent) or
1655
parent in copy_set or
1656
not self.source.has_version(parent))
1657
data_pos, data_size = self.source._index.get_position(version_id)
1658
copy_queue_records.append((version_id, data_pos, data_size))
1659
copy_queue.append((version_id, options, parents))
1660
copy_set.add(version_id)
1662
# data suck the join:
1664
total = len(version_list)
1667
for (version_id, raw_data), \
1668
(version_id2, options, parents) in \
1669
izip(self.source._data.read_records_iter_raw(copy_queue_records),
1671
assert version_id == version_id2, 'logic error, inconsistent results'
1673
pb.update("Joining knit", count, total)
1674
raw_records.append((version_id, options, parents, len(raw_data)))
1675
raw_datum.append(raw_data)
1676
self.target._add_raw_records(raw_records, ''.join(raw_datum))
1678
for version in mismatched_versions:
1679
# FIXME RBC 20060309 is this needed?
1680
n1 = set(self.target.get_parents_with_ghosts(version))
1681
n2 = set(self.source.get_parents_with_ghosts(version))
1682
# write a combined record to our history preserving the current
1683
# parents as first in the list
1684
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1685
self.target.fix_parents(version, new_parents)
1691
InterVersionedFile.register_optimiser(InterKnit)
1694
class WeaveToKnit(InterVersionedFile):
1695
"""Optimised code paths for weave to knit operations."""
1697
_matching_file_from_factory = bzrlib.weave.WeaveFile
1698
_matching_file_to_factory = KnitVersionedFile
1701
def is_compatible(source, target):
1702
"""Be compatible with weaves to knits."""
1704
return (isinstance(source, bzrlib.weave.Weave) and
1705
isinstance(target, KnitVersionedFile))
1706
except AttributeError:
1709
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1710
"""See InterVersionedFile.join."""
1711
assert isinstance(self.source, bzrlib.weave.Weave)
1712
assert isinstance(self.target, KnitVersionedFile)
1714
version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1719
pb = ui.ui_factory.nested_progress_bar()
1721
version_ids = list(version_ids)
1723
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1724
this_versions = set(self.target._index.get_versions())
1725
needed_versions = self.source_ancestry - this_versions
1726
cross_check_versions = self.source_ancestry.intersection(this_versions)
1727
mismatched_versions = set()
1728
for version in cross_check_versions:
1729
# scan to include needed parents.
1730
n1 = set(self.target.get_parents_with_ghosts(version))
1731
n2 = set(self.source.get_parents(version))
1732
# if all of n2's parents are in n1, then its fine.
1733
if n2.difference(n1):
1734
# FIXME TEST this check for cycles being introduced works
1735
# the logic is we have a cycle if in our graph we are an
1736
# ancestor of any of the n2 revisions.
1742
parent_ancestors = self.source.get_ancestry(parent)
1743
if version in parent_ancestors:
1744
raise errors.GraphCycleError([parent, version])
1745
# ensure this parent will be available later.
1746
new_parents = n2.difference(n1)
1747
needed_versions.update(new_parents.difference(this_versions))
1748
mismatched_versions.add(version)
1750
if not needed_versions and not mismatched_versions:
1752
full_list = topo_sort(self.source.get_graph())
1754
version_list = [i for i in full_list if (not self.target.has_version(i)
1755
and i in needed_versions)]
1759
total = len(version_list)
1760
for version_id in version_list:
1761
pb.update("Converting to knit", count, total)
1762
parents = self.source.get_parents(version_id)
1763
# check that its will be a consistent copy:
1764
for parent in parents:
1765
# if source has the parent, we must already have it
1766
assert (self.target.has_version(parent))
1767
self.target.add_lines(
1768
version_id, parents, self.source.get_lines(version_id))
1771
for version in mismatched_versions:
1772
# FIXME RBC 20060309 is this needed?
1773
n1 = set(self.target.get_parents_with_ghosts(version))
1774
n2 = set(self.source.get_parents(version))
1775
# write a combined record to our history preserving the current
1776
# parents as first in the list
1777
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1778
self.target.fix_parents(version, new_parents)
1784
InterVersionedFile.register_optimiser(WeaveToKnit)
1787
class KnitSequenceMatcher(difflib.SequenceMatcher):
1788
"""Knit tuned sequence matcher.
1790
This is based on profiling of difflib which indicated some improvements
1791
for our usage pattern.
1794
def find_longest_match(self, alo, ahi, blo, bhi):
1795
"""Find longest matching block in a[alo:ahi] and b[blo:bhi].
1797
If isjunk is not defined:
1799
Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
1800
alo <= i <= i+k <= ahi
1801
blo <= j <= j+k <= bhi
1802
and for all (i',j',k') meeting those conditions,
1805
and if i == i', j <= j'
1807
In other words, of all maximal matching blocks, return one that
1808
starts earliest in a, and of all those maximal matching blocks that
1809
start earliest in a, return the one that starts earliest in b.
1811
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
1812
>>> s.find_longest_match(0, 5, 0, 9)
1815
If isjunk is defined, first the longest matching block is
1816
determined as above, but with the additional restriction that no
1817
junk element appears in the block. Then that block is extended as
1818
far as possible by matching (only) junk elements on both sides. So
1819
the resulting block never matches on junk except as identical junk
1820
happens to be adjacent to an "interesting" match.
1822
Here's the same example as before, but considering blanks to be
1823
junk. That prevents " abcd" from matching the " abcd" at the tail
1824
end of the second sequence directly. Instead only the "abcd" can
1825
match, and matches the leftmost "abcd" in the second sequence:
1827
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
1828
>>> s.find_longest_match(0, 5, 0, 9)
1831
If no blocks match, return (alo, blo, 0).
1833
>>> s = SequenceMatcher(None, "ab", "c")
1834
>>> s.find_longest_match(0, 2, 0, 1)
1838
# CAUTION: stripping common prefix or suffix would be incorrect.
1842
# Longest matching block is "ab", but if common prefix is
1843
# stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
1844
# strip, so ends up claiming that ab is changed to acab by
1845
# inserting "ca" in the middle. That's minimal but unintuitive:
1846
# "it's obvious" that someone inserted "ac" at the front.
1847
# Windiff ends up at the same place as diff, but by pairing up
1848
# the unique 'b's and then matching the first two 'a's.
1850
a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
1851
besti, bestj, bestsize = alo, blo, 0
1852
# find longest junk-free match
1853
# during an iteration of the loop, j2len[j] = length of longest
1854
# junk-free match ending with a[i-1] and b[j]
1858
for i in xrange(alo, ahi):
1859
# look at all instances of a[i] in b; note that because
1860
# b2j has no junk keys, the loop is skipped if a[i] is junk
1861
j2lenget = j2len.get
1864
# changing b2j.get(a[i], nothing) to a try:KeyError pair produced the
1865
# following improvement
1866
# 704 0 4650.5320 2620.7410 bzrlib.knit:1336(find_longest_match)
1867
# +326674 0 1655.1210 1655.1210 +<method 'get' of 'dict' objects>
1868
# +76519 0 374.6700 374.6700 +<method 'has_key' of 'dict' objects>
1870
# 704 0 3733.2820 2209.6520 bzrlib.knit:1336(find_longest_match)
1871
# +211400 0 1147.3520 1147.3520 +<method 'get' of 'dict' objects>
1872
# +76519 0 376.2780 376.2780 +<method 'has_key' of 'dict' objects>
1884
k = newj2len[j] = 1 + j2lenget(-1 + j, 0)
1886
besti, bestj, bestsize = 1 + i-k, 1 + j-k, k
1889
# Extend the best by non-junk elements on each end. In particular,
1890
# "popular" non-junk elements aren't in b2j, which greatly speeds
1891
# the inner loop above, but also means "the best" match so far
1892
# doesn't contain any junk *or* popular non-junk elements.
1893
while besti > alo and bestj > blo and \
1894
not isbjunk(b[bestj-1]) and \
1895
a[besti-1] == b[bestj-1]:
1896
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1897
while besti+bestsize < ahi and bestj+bestsize < bhi and \
1898
not isbjunk(b[bestj+bestsize]) and \
1899
a[besti+bestsize] == b[bestj+bestsize]:
1902
# Now that we have a wholly interesting match (albeit possibly
1903
# empty!), we may as well suck up the matching junk on each
1904
# side of it too. Can't think of a good reason not to, and it
1905
# saves post-processing the (possibly considerable) expense of
1906
# figuring out what to do with it. In the case of an empty
1907
# interesting match, this is clearly the right thing to do,
1908
# because no other kind of match is possible in the regions.
1909
while besti > alo and bestj > blo and \
1910
isbjunk(b[bestj-1]) and \
1911
a[besti-1] == b[bestj-1]:
1912
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1913
while besti+bestsize < ahi and bestj+bestsize < bhi and \
1914
isbjunk(b[bestj+bestsize]) and \
1915
a[besti+bestsize] == b[bestj+bestsize]:
1916
bestsize = bestsize + 1
1918
return besti, bestj, bestsize
1922
from bzrlib._knit_load_data_c import _load_data_c as _load_data
1924
from bzrlib._knit_load_data_py import _load_data_py as _load_data