1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
# Written by Martin Pool.
3
# Modified by Johan Rydberg <jrydberg@gnu.org>
4
# Modified by Robert Collins <robert.collins@canonical.com>
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
# GNU General Public License for more details.
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
"""Knit versionedfile implementation.
22
A knit is a versioned file implementation that supports efficient append only
26
lifeless: the data file is made up of "delta records". each delta record has a delta header
27
that contains; (1) a version id, (2) the size of the delta (in lines), and (3) the digest of
28
the -expanded data- (ie, the delta applied to the parent). the delta also ends with a
29
end-marker; simply "end VERSION"
31
delta can be line or full contents.a
32
... the 8's there are the index number of the annotation.
33
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
37
8 e.set('executable', 'yes')
39
8 if elt.get('executable') == 'yes':
40
8 ie.executable = True
41
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad
45
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
46
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
47
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
48
09:33 < lifeless> right
49
09:33 < jrydberg> lifeless: the position and size is the range in the data file
52
so the index sequence is the dictionary compressed sequence number used
53
in the deltas to provide line annotation
58
# 10:16 < lifeless> make partial index writes safe
59
# 10:16 < lifeless> implement 'knit.check()' like weave.check()
60
# 10:17 < lifeless> record known ghosts so we can detect when they are filled in rather than the current 'reweave
62
# move sha1 out of the content so that join is faster at verifying parents
63
# record content length ?
67
from cStringIO import StringIO
69
from itertools import izip, chain
74
import bzrlib.errors as errors
75
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
76
InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
77
RevisionNotPresent, RevisionAlreadyPresent
78
from bzrlib.tuned_gzip import *
79
from bzrlib.trace import mutter
80
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
82
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
83
from bzrlib.tsort import topo_sort
87
# TODO: Split out code specific to this format into an associated object.
89
# TODO: Can we put in some kind of value to check that the index and data
90
# files belong together?
92
# TODO: accomodate binaries, perhaps by storing a byte count
94
# TODO: function to check whole file
96
# TODO: atomically append data, then measure backwards from the cursor
97
# position after writing to work out where it was located. we may need to
98
# bypass python file buffering.
100
DATA_SUFFIX = '.knit'
101
INDEX_SUFFIX = '.kndx'
104
class KnitContent(object):
105
"""Content of a knit version to which deltas can be applied."""
107
def __init__(self, lines):
110
def annotate_iter(self):
111
"""Yield tuples of (origin, text) for each content line."""
112
for origin, text in self._lines:
116
"""Return a list of (origin, text) tuples."""
117
return list(self.annotate_iter())
119
def line_delta_iter(self, new_lines):
120
"""Generate line-based delta from this content to new_lines."""
121
new_texts = [text for origin, text in new_lines._lines]
122
old_texts = [text for origin, text in self._lines]
123
s = SequenceMatcher(None, old_texts, new_texts)
124
for op in s.get_opcodes():
127
# ofrom oto length data
128
yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
130
def line_delta(self, new_lines):
131
return list(self.line_delta_iter(new_lines))
134
return [text for origin, text in self._lines]
137
class _KnitFactory(object):
138
"""Base factory for creating content objects."""
140
def make(self, lines, version):
141
num_lines = len(lines)
142
return KnitContent(zip([version] * num_lines, lines))
145
class KnitAnnotateFactory(_KnitFactory):
146
"""Factory for creating annotated Content objects."""
150
def parse_fulltext(self, content, version):
151
"""Convert fulltext to internal representation
153
fulltext content is of the format
154
revid(utf8) plaintext\n
155
internal representation is of the format:
160
origin, text = line.split(' ', 1)
161
lines.append((origin.decode('utf-8'), text))
162
return KnitContent(lines)
164
def parse_line_delta_iter(self, lines):
165
for result_item in self.parse_line_delta[lines]:
168
def parse_line_delta(self, lines, version):
169
"""Convert a line based delta into internal representation.
171
line delta is in the form of:
172
intstart intend intcount
174
revid(utf8) newline\n
175
internal represnetation is
176
(start, end, count, [1..count tuples (revid, newline)])
181
# walk through the lines parsing.
183
start, end, count = [int(n) for n in header.split(',')]
187
origin, text = next().split(' ', 1)
189
contents.append((origin.decode('utf-8'), text))
190
result.append((start, end, count, contents))
193
def lower_fulltext(self, content):
194
"""convert a fulltext content record into a serializable form.
196
see parse_fulltext which this inverts.
198
return ['%s %s' % (o.encode('utf-8'), t) for o, t in content._lines]
200
def lower_line_delta(self, delta):
201
"""convert a delta into a serializable form.
203
See parse_line_delta which this inverts.
206
for start, end, c, lines in delta:
207
out.append('%d,%d,%d\n' % (start, end, c))
208
for origin, text in lines:
209
out.append('%s %s' % (origin.encode('utf-8'), text))
213
class KnitPlainFactory(_KnitFactory):
214
"""Factory for creating plain Content objects."""
218
def parse_fulltext(self, content, version):
219
"""This parses an unannotated fulltext.
221
Note that this is not a noop - the internal representation
222
has (versionid, line) - its just a constant versionid.
224
return self.make(content, version)
226
def parse_line_delta_iter(self, lines, version):
228
header = lines.pop(0)
229
start, end, c = [int(n) for n in header.split(',')]
230
yield start, end, c, zip([version] * c, lines[:c])
233
def parse_line_delta(self, lines, version):
234
return list(self.parse_line_delta_iter(lines, version))
236
def lower_fulltext(self, content):
237
return content.text()
239
def lower_line_delta(self, delta):
241
for start, end, c, lines in delta:
242
out.append('%d,%d,%d\n' % (start, end, c))
243
out.extend([text for origin, text in lines])
247
def make_empty_knit(transport, relpath):
248
"""Construct a empty knit at the specified location."""
249
k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
253
class KnitVersionedFile(VersionedFile):
254
"""Weave-like structure with faster random access.
256
A knit stores a number of texts and a summary of the relationships
257
between them. Texts are identified by a string version-id. Texts
258
are normally stored and retrieved as a series of lines, but can
259
also be passed as single strings.
261
Lines are stored with the trailing newline (if any) included, to
262
avoid special cases for files with no final newline. Lines are
263
composed of 8-bit characters, not unicode. The combination of
264
these approaches should mean any 'binary' file can be safely
265
stored and retrieved.
268
def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
269
basis_knit=None, delta=True, create=False):
270
"""Construct a knit at location specified by relpath.
272
:param create: If not True, only open an existing knit.
274
if access_mode is None:
276
super(KnitVersionedFile, self).__init__(access_mode)
277
assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
278
assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
281
self.transport = transport
282
self.filename = relpath
283
self.basis_knit = basis_knit
284
self.factory = factory or KnitAnnotateFactory()
285
self.writable = (access_mode == 'w')
288
self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
289
access_mode, create=create, file_mode=file_mode)
290
self._data = _KnitData(transport, relpath + DATA_SUFFIX,
291
access_mode, create=create and not len(self), file_mode=file_mode)
294
return '%s(%s)' % (self.__class__.__name__,
295
self.transport.abspath(self.filename))
297
def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
298
"""See VersionedFile._add_delta()."""
299
self._check_add(version_id, []) # should we check the lines ?
300
self._check_versions_present(parents)
304
for parent in parents:
305
if not self.has_version(parent):
306
ghosts.append(parent)
308
present_parents.append(parent)
310
if delta_parent is None:
311
# reconstitute as full text.
312
assert len(delta) == 1 or len(delta) == 0
314
assert delta[0][0] == 0
315
assert delta[0][1] == 0, delta[0][1]
316
return super(KnitVersionedFile, self)._add_delta(version_id,
327
options.append('no-eol')
329
if delta_parent is not None:
330
# determine the current delta chain length.
331
# To speed the extract of texts the delta chain is limited
332
# to a fixed number of deltas. This should minimize both
333
# I/O and the time spend applying deltas.
335
delta_parents = [delta_parent]
337
parent = delta_parents[0]
338
method = self._index.get_method(parent)
339
if method == 'fulltext':
341
delta_parents = self._index.get_parents(parent)
343
if method == 'line-delta':
344
# did not find a fulltext in the delta limit.
345
# just do a normal insertion.
346
return super(KnitVersionedFile, self)._add_delta(version_id,
353
options.append('line-delta')
354
store_lines = self.factory.lower_line_delta(delta)
356
where, size = self._data.add_record(version_id, digest, store_lines)
357
self._index.add_version(version_id, options, where, size, parents)
359
def _add_raw_records(self, records, data):
360
"""Add all the records 'records' with data pre-joined in 'data'.
362
:param records: A list of tuples(version_id, options, parents, size).
363
:param data: The data for the records. When it is written, the records
364
are adjusted to have pos pointing into data by the sum of
365
the preceeding records sizes.
368
pos = self._data.add_raw_record(data)
370
for (version_id, options, parents, size) in records:
371
index_entries.append((version_id, options, pos, size, parents))
373
self._index.add_versions(index_entries)
375
def clear_cache(self):
376
"""Clear the data cache only."""
377
self._data.clear_cache()
379
def copy_to(self, name, transport):
380
"""See VersionedFile.copy_to()."""
381
# copy the current index to a temp index to avoid racing with local
383
transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename),)
385
transport.put(name + DATA_SUFFIX, self._data._open_file())
386
# rename the copied index into place
387
transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
389
def create_empty(self, name, transport, mode=None):
390
return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
392
def _fix_parents(self, version, new_parents):
393
"""Fix the parents list for version.
395
This is done by appending a new version to the index
396
with identical data except for the parents list.
397
the parents list must be a superset of the current
400
current_values = self._index._cache[version]
401
assert set(current_values[4]).difference(set(new_parents)) == set()
402
self._index.add_version(version,
408
def get_delta(self, version_id):
409
"""Get a delta for constructing version from some other version."""
410
if not self.has_version(version_id):
411
raise RevisionNotPresent(version_id, self.filename)
413
parents = self.get_parents(version_id)
418
data_pos, data_size = self._index.get_position(version_id)
419
data, sha1 = self._data.read_records(((version_id, data_pos, data_size),))[version_id]
420
version_idx = self._index.lookup(version_id)
421
noeol = 'no-eol' in self._index.get_options(version_id)
422
if 'fulltext' == self._index.get_method(version_id):
423
new_content = self.factory.parse_fulltext(data, version_idx)
424
if parent is not None:
425
reference_content = self._get_content(parent)
426
old_texts = reference_content.text()
429
new_texts = new_content.text()
430
delta_seq = SequenceMatcher(None, old_texts, new_texts)
431
return parent, sha1, noeol, self._make_line_delta(delta_seq, new_content)
433
delta = self.factory.parse_line_delta(data, version_idx)
434
return parent, sha1, noeol, delta
436
def get_graph_with_ghosts(self):
437
"""See VersionedFile.get_graph_with_ghosts()."""
438
graph_items = self._index.get_graph()
439
return dict(graph_items)
441
def get_sha1(self, version_id):
442
"""See VersionedFile.get_sha1()."""
443
components = self._get_components(version_id)
444
return components[-1][-1][-1]
448
"""See VersionedFile.get_suffixes()."""
449
return [DATA_SUFFIX, INDEX_SUFFIX]
451
def has_ghost(self, version_id):
452
"""True if there is a ghost reference in the file to version_id."""
454
if self.has_version(version_id):
456
# optimisable if needed by memoising the _ghosts set.
457
items = self._index.get_graph()
458
for node, parents in items:
459
for parent in parents:
460
if parent not in self._index._cache:
461
if parent == version_id:
466
"""See VersionedFile.versions."""
467
return self._index.get_versions()
469
def has_version(self, version_id):
470
"""See VersionedFile.has_version."""
471
return self._index.has_version(version_id)
473
__contains__ = has_version
475
def _merge_annotations(self, content, parents, parent_texts={},
476
delta=None, annotated=None):
477
"""Merge annotations for content. This is done by comparing
478
the annotations based on changed to the text.
482
for parent_id in parents:
483
merge_content = self._get_content(parent_id, parent_texts)
484
seq = SequenceMatcher(None, merge_content.text(), content.text())
485
if delta_seq is None:
486
# setup a delta seq to reuse.
488
for i, j, n in seq.get_matching_blocks():
491
# this appears to copy (origin, text) pairs across to the new
492
# content for any line that matches the last-checked parent.
493
# FIXME: save the sequence control data for delta compression
494
# against the most relevant parent rather than rediffing.
495
content._lines[j:j+n] = merge_content._lines[i:i+n]
498
reference_content = self._get_content(parents[0], parent_texts)
499
new_texts = content.text()
500
old_texts = reference_content.text()
501
delta_seq = SequenceMatcher(None, old_texts, new_texts)
502
return self._make_line_delta(delta_seq, content)
504
def _make_line_delta(self, delta_seq, new_content):
505
"""Generate a line delta from delta_seq and new_content."""
507
for op in delta_seq.get_opcodes():
510
diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
513
def _get_components(self, version_id):
514
"""Return a list of (version_id, method, data) tuples that
515
makes up version specified by version_id of the knit.
517
The components should be applied in the order of the returned
520
The basis knit will be used to the largest extent possible
521
since it is assumed that accesses to it is faster.
524
# 4168 calls in 14912, 2289 internal
525
# 4168 in 9711 to read_records
526
# 52554 in 1250 to get_parents
527
# 170166 in 865 to list.append
529
# needed_revisions holds a list of (method, version_id) of
530
# versions that is needed to be fetched to construct the final
531
# version of the file.
533
# basis_revisions is a list of versions that needs to be
534
# fetched but exists in the basis knit.
536
basis = self.basis_knit
543
if basis and basis._index.has_version(cursor):
545
basis_versions.append(cursor)
546
method = picked_knit._index.get_method(cursor)
547
needed_versions.append((method, cursor))
548
if method == 'fulltext':
550
cursor = picked_knit.get_parents(cursor)[0]
555
for comp_id in basis_versions:
556
data_pos, data_size = basis._index.get_data_position(comp_id)
557
records.append((piece_id, data_pos, data_size))
558
components.update(basis._data.read_records(records))
561
for comp_id in [vid for method, vid in needed_versions
562
if vid not in basis_versions]:
563
data_pos, data_size = self._index.get_position(comp_id)
564
records.append((comp_id, data_pos, data_size))
565
components.update(self._data.read_records(records))
567
# get_data_records returns a mapping with the version id as
568
# index and the value as data. The order the components need
569
# to be applied is held by needed_versions (reversed).
571
for method, comp_id in reversed(needed_versions):
572
out.append((comp_id, method, components[comp_id]))
576
def _get_content(self, version_id, parent_texts={}):
577
"""Returns a content object that makes up the specified
579
if not self.has_version(version_id):
580
raise RevisionNotPresent(version_id, self.filename)
582
cached_version = parent_texts.get(version_id, None)
583
if cached_version is not None:
584
return cached_version
586
if self.basis_knit and version_id in self.basis_knit:
587
return self.basis_knit._get_content(version_id)
590
components = self._get_components(version_id)
591
for component_id, method, (data, digest) in components:
592
version_idx = self._index.lookup(component_id)
593
if method == 'fulltext':
594
assert content is None
595
content = self.factory.parse_fulltext(data, version_idx)
596
elif method == 'line-delta':
597
delta = self.factory.parse_line_delta(data, version_idx)
598
content._lines = self._apply_delta(content._lines, delta)
600
if 'no-eol' in self._index.get_options(version_id):
601
line = content._lines[-1][1].rstrip('\n')
602
content._lines[-1] = (content._lines[-1][0], line)
604
# digest here is the digest from the last applied component.
605
if sha_strings(content.text()) != digest:
606
import pdb;pdb.set_trace()
607
raise KnitCorrupt(self.filename, 'sha-1 does not match %s' % version_id)
611
def _check_versions_present(self, version_ids):
612
"""Check that all specified versions are present."""
613
version_ids = set(version_ids)
614
for r in list(version_ids):
615
if self._index.has_version(r):
616
version_ids.remove(r)
618
raise RevisionNotPresent(list(version_ids)[0], self.filename)
620
def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
621
"""See VersionedFile.add_lines_with_ghosts()."""
622
self._check_add(version_id, lines)
623
return self._add(version_id, lines[:], parents, self.delta, parent_texts)
625
def _add_lines(self, version_id, parents, lines, parent_texts):
626
"""See VersionedFile.add_lines."""
627
self._check_add(version_id, lines)
628
self._check_versions_present(parents)
629
return self._add(version_id, lines[:], parents, self.delta, parent_texts)
631
def _check_add(self, version_id, lines):
632
"""check that version_id and lines are safe to add."""
633
assert self.writable, "knit is not opened for write"
634
### FIXME escape. RBC 20060228
635
if contains_whitespace(version_id):
636
raise InvalidRevisionId(version_id, self.filename)
637
if self.has_version(version_id):
638
raise RevisionAlreadyPresent(version_id, self.filename)
639
self._check_lines_not_unicode(lines)
640
self._check_lines_are_lines(lines)
642
def _add(self, version_id, lines, parents, delta, parent_texts):
643
"""Add a set of lines on top of version specified by parents.
645
If delta is true, compress the text as a line-delta against
648
Any versions not present will be converted into ghosts.
650
# 461 0 6546.0390 43.9100 bzrlib.knit:489(_add)
651
# +400 0 889.4890 418.9790 +bzrlib.knit:192(lower_fulltext)
652
# +461 0 1364.8070 108.8030 +bzrlib.knit:996(add_record)
653
# +461 0 193.3940 41.5720 +bzrlib.knit:898(add_version)
654
# +461 0 134.0590 18.3810 +bzrlib.osutils:361(sha_strings)
655
# +461 0 36.3420 15.4540 +bzrlib.knit:146(make)
656
# +1383 0 8.0370 8.0370 +<len>
657
# +61 0 13.5770 7.9190 +bzrlib.knit:199(lower_line_delta)
658
# +61 0 963.3470 7.8740 +bzrlib.knit:427(_get_content)
659
# +61 0 973.9950 5.2950 +bzrlib.knit:136(line_delta)
660
# +61 0 1918.1800 5.2640 +bzrlib.knit:359(_merge_annotations)
664
if parent_texts is None:
666
for parent in parents:
667
if not self.has_version(parent):
668
ghosts.append(parent)
670
present_parents.append(parent)
672
if delta and not len(present_parents):
675
digest = sha_strings(lines)
678
if lines[-1][-1] != '\n':
679
options.append('no-eol')
680
lines[-1] = lines[-1] + '\n'
682
if len(present_parents) and delta:
683
# To speed the extract of texts the delta chain is limited
684
# to a fixed number of deltas. This should minimize both
685
# I/O and the time spend applying deltas.
687
delta_parents = present_parents
689
parent = delta_parents[0]
690
method = self._index.get_method(parent)
691
if method == 'fulltext':
693
delta_parents = self._index.get_parents(parent)
695
if method == 'line-delta':
698
lines = self.factory.make(lines, version_id)
699
if delta or (self.factory.annotated and len(present_parents) > 0):
700
# Merge annotations from parent texts if so is needed.
701
delta_hunks = self._merge_annotations(lines, present_parents, parent_texts,
702
delta, self.factory.annotated)
705
options.append('line-delta')
706
store_lines = self.factory.lower_line_delta(delta_hunks)
708
options.append('fulltext')
709
store_lines = self.factory.lower_fulltext(lines)
711
where, size = self._data.add_record(version_id, digest, store_lines)
712
self._index.add_version(version_id, options, where, size, parents)
715
def check(self, progress_bar=None):
716
"""See VersionedFile.check()."""
718
def _clone_text(self, new_version_id, old_version_id, parents):
719
"""See VersionedFile.clone_text()."""
720
# FIXME RBC 20060228 make fast by only inserting an index with null delta.
721
self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
723
def get_lines(self, version_id):
724
"""See VersionedFile.get_lines()."""
725
return self._get_content(version_id).text()
727
def iter_lines_added_or_present_in_versions(self, version_ids=None):
728
"""See VersionedFile.iter_lines_added_or_present_in_versions()."""
729
if version_ids is None:
730
version_ids = self.versions()
731
# we dont care about inclusions, the caller cares.
732
# but we need to setup a list of records to visit.
733
# we need version_id, position, length
734
version_id_records = []
735
requested_versions = list(version_ids)
736
# filter for available versions
737
for version_id in requested_versions:
738
if not self.has_version(version_id):
739
raise RevisionNotPresent(version_id, self.filename)
740
# get a in-component-order queue:
742
for version_id in self.versions():
743
if version_id in requested_versions:
744
version_ids.append(version_id)
745
data_pos, length = self._index.get_position(version_id)
746
version_id_records.append((version_id, data_pos, length))
748
pb = bzrlib.ui.ui_factory.nested_progress_bar()
750
total = len(version_id_records)
752
pb.update('Walking content.', count, total)
753
for version_id, data, sha_value in \
754
self._data.read_records_iter(version_id_records):
755
pb.update('Walking content.', count, total)
756
method = self._index.get_method(version_id)
757
version_idx = self._index.lookup(version_id)
758
assert method in ('fulltext', 'line-delta')
759
if method == 'fulltext':
760
content = self.factory.parse_fulltext(data, version_idx)
761
for line in content.text():
764
delta = self.factory.parse_line_delta(data, version_idx)
765
for start, end, count, lines in delta:
766
for origin, line in lines:
769
pb.update('Walking content.', total, total)
772
pb.update('Walking content.', total, total)
776
def num_versions(self):
777
"""See VersionedFile.num_versions()."""
778
return self._index.num_versions()
780
__len__ = num_versions
782
def annotate_iter(self, version_id):
783
"""See VersionedFile.annotate_iter."""
784
content = self._get_content(version_id)
785
for origin, text in content.annotate_iter():
788
def get_parents(self, version_id):
789
"""See VersionedFile.get_parents."""
792
# 52554 calls in 1264 872 internal down from 3674
794
return self._index.get_parents(version_id)
796
raise RevisionNotPresent(version_id, self.filename)
798
def get_parents_with_ghosts(self, version_id):
799
"""See VersionedFile.get_parents."""
801
return self._index.get_parents_with_ghosts(version_id)
803
raise RevisionNotPresent(version_id, self.filename)
805
def get_ancestry(self, versions):
806
"""See VersionedFile.get_ancestry."""
807
if isinstance(versions, basestring):
808
versions = [versions]
811
self._check_versions_present(versions)
812
return self._index.get_ancestry(versions)
814
def get_ancestry_with_ghosts(self, versions):
815
"""See VersionedFile.get_ancestry_with_ghosts."""
816
if isinstance(versions, basestring):
817
versions = [versions]
820
self._check_versions_present(versions)
821
return self._index.get_ancestry_with_ghosts(versions)
823
#@deprecated_method(zero_eight)
824
def walk(self, version_ids):
825
"""See VersionedFile.walk."""
826
# We take the short path here, and extract all relevant texts
827
# and put them in a weave and let that do all the work. Far
828
# from optimal, but is much simpler.
829
# FIXME RB 20060228 this really is inefficient!
830
from bzrlib.weave import Weave
832
w = Weave(self.filename)
833
ancestry = self.get_ancestry(version_ids)
834
sorted_graph = topo_sort(self._index.get_graph())
835
version_list = [vid for vid in sorted_graph if vid in ancestry]
837
for version_id in version_list:
838
lines = self.get_lines(version_id)
839
w.add_lines(version_id, self.get_parents(version_id), lines)
841
for lineno, insert_id, dset, line in w.walk(version_ids):
842
yield lineno, insert_id, dset, line
844
def plan_merge(self, ver_a, ver_b):
845
"""See VersionedFile.plan_merge."""
846
ancestors_b = set(self.get_ancestry(ver_b))
847
def status_a(revision, text):
848
if revision in ancestors_b:
849
return 'killed-b', text
853
ancestors_a = set(self.get_ancestry(ver_a))
854
def status_b(revision, text):
855
if revision in ancestors_a:
856
return 'killed-a', text
860
annotated_a = self.annotate(ver_a)
861
annotated_b = self.annotate(ver_b)
862
plain_a = [t for (a, t) in annotated_a]
863
plain_b = [t for (a, t) in annotated_b]
864
blocks = SequenceMatcher(None, plain_a, plain_b).get_matching_blocks()
867
for ai, bi, l in blocks:
868
# process all mismatched sections
869
# (last mismatched section is handled because blocks always
870
# includes a 0-length last block)
871
for revision, text in annotated_a[a_cur:ai]:
872
yield status_a(revision, text)
873
for revision, text in annotated_b[b_cur:bi]:
874
yield status_b(revision, text)
876
# and now the matched section
879
for text_a, text_b in zip(plain_a[ai:a_cur], plain_b[bi:b_cur]):
880
assert text_a == text_b
881
yield "unchanged", text_a
884
class _KnitComponentFile(object):
885
"""One of the files used to implement a knit database"""
887
def __init__(self, transport, filename, mode, file_mode=None):
888
self._transport = transport
889
self._filename = filename
891
self._file_mode=file_mode
893
def write_header(self):
894
if self._transport.append(self._filename, StringIO(self.HEADER),
895
mode=self._file_mode):
896
raise KnitCorrupt(self._filename, 'misaligned after writing header')
898
def check_header(self, fp):
900
if line != self.HEADER:
901
raise KnitHeaderError(badline=line)
904
"""Commit is a nop."""
907
return '%s(%s)' % (self.__class__.__name__, self._filename)
910
class _KnitIndex(_KnitComponentFile):
911
"""Manages knit index file.
913
The index is already kept in memory and read on startup, to enable
914
fast lookups of revision information. The cursor of the index
915
file is always pointing to the end, making it easy to append
918
_cache is a cache for fast mapping from version id to a Index
921
_history is a cache for fast mapping from indexes to version ids.
923
The index data format is dictionary compressed when it comes to
924
parent references; a index entry may only have parents that with a
925
lover index number. As a result, the index is topological sorted.
927
Duplicate entries may be written to the index for a single version id
928
if this is done then the latter one completely replaces the former:
929
this allows updates to correct version and parent information.
930
Note that the two entries may share the delta, and that successive
931
annotations and references MUST point to the first entry.
933
The index file on disc contains a header, followed by one line per knit
934
record. The same revision can be present in an index file more than once.
935
The first occurence gets assigned a sequence number starting from 0.
937
The format of a single line is
938
REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
939
REVISION_ID is a utf8-encoded revision id
940
FLAGS is a comma separated list of flags about the record. Values include
941
no-eol, line-delta, fulltext.
942
BYTE_OFFSET is the ascii representation of the byte offset in the data file
943
that the the compressed data starts at.
944
LENGTH is the ascii representation of the length of the data file.
945
PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
947
PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
948
revision id already in the knit that is a parent of REVISION_ID.
949
The ' :' marker is the end of record marker.
952
when a write is interrupted to the index file, it will result in a line that
953
does not end in ' :'. If the ' :' is not present at the end of a line, or at
954
the end of the file, then the record that is missing it will be ignored by
957
When writing new records to the index file, the data is preceeded by '\n'
958
to ensure that records always start on new lines even if the last write was
959
interrupted. As a result its normal for the last line in the index to be
960
missing a trailing newline. One can be added with no harmful effects.
963
HEADER = "# bzr knit index 8\n"
965
# speed of knit parsing went from 280 ms to 280 ms with slots addition.
966
# __slots__ = ['_cache', '_history', '_transport', '_filename']
968
def _cache_version(self, version_id, options, pos, size, parents):
969
"""Cache a version record in the history array and index cache.
971
This is inlined into __init__ for performance. KEEP IN SYNC.
972
(It saves 60ms, 25% of the __init__ overhead on local 4000 record
975
# only want the _history index to reference the 1st index entry
977
if version_id not in self._cache:
978
index = len(self._history)
979
self._history.append(version_id)
981
index = self._cache[version_id][5]
982
self._cache[version_id] = (version_id,
989
def __init__(self, transport, filename, mode, create=False, file_mode=None):
990
_KnitComponentFile.__init__(self, transport, filename, mode, file_mode)
992
# position in _history is the 'official' index for a revision
993
# but the values may have come from a newer entry.
994
# so - wc -l of a knit index is != the number of uniqe names
997
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1002
pb.update('read knit index', count, total)
1003
fp = self._transport.get(self._filename)
1004
self.check_header(fp)
1005
# readlines reads the whole file at once:
1006
# bad for transports like http, good for local disk
1007
# we save 60 ms doing this one change (
1008
# from calling readline each time to calling
1010
# probably what we want for nice behaviour on
1011
# http is a incremental readlines that yields, or
1012
# a check for local vs non local indexes,
1013
for l in fp.readlines():
1015
if len(rec) < 5 or rec[-1] != ':':
1017
# FIXME: in the future we should determine if its a
1018
# short write - and ignore it
1019
# or a different failure, and raise. RBC 20060407
1023
#pb.update('read knit index', count, total)
1024
# See self._parse_parents
1026
for value in rec[4:-1]:
1028
# uncompressed reference
1029
parents.append(value[1:])
1031
# this is 15/4000ms faster than isinstance,
1033
# this function is called thousands of times a
1034
# second so small variations add up.
1035
assert value.__class__ is str
1036
parents.append(self._history[int(value)])
1037
# end self._parse_parents
1038
# self._cache_version(rec[0],
1039
# rec[1].split(','),
1043
# --- self._cache_version
1044
# only want the _history index to reference the 1st
1045
# index entry for version_id
1047
if version_id not in self._cache:
1048
index = len(self._history)
1049
self._history.append(version_id)
1051
index = self._cache[version_id][5]
1052
self._cache[version_id] = (version_id,
1058
# --- self._cache_version
1059
except NoSuchFile, e:
1060
if mode != 'w' or not create:
1064
pb.update('read knit index', total, total)
1067
def _parse_parents(self, compressed_parents):
1068
"""convert a list of string parent values into version ids.
1070
ints are looked up in the index.
1071
.FOO values are ghosts and converted in to FOO.
1073
NOTE: the function is retained here for clarity, and for possible
1074
use in partial index reads. However bulk processing now has
1075
it inlined in __init__ for inner-loop optimisation.
1078
for value in compressed_parents:
1079
if value[-1] == '.':
1080
# uncompressed reference
1081
result.append(value[1:])
1083
# this is 15/4000ms faster than isinstance,
1084
# this function is called thousands of times a
1085
# second so small variations add up.
1086
assert value.__class__ is str
1087
result.append(self._history[int(value)])
1090
def get_graph(self):
1092
for version_id, index in self._cache.iteritems():
1093
graph.append((version_id, index[4]))
1096
def get_ancestry(self, versions):
1097
"""See VersionedFile.get_ancestry."""
1098
# get a graph of all the mentioned versions:
1100
pending = set(versions)
1102
version = pending.pop()
1103
parents = self._cache[version][4]
1104
# got the parents ok
1106
parents = [parent for parent in parents if parent in self._cache]
1107
for parent in parents:
1108
# if not completed and not a ghost
1109
if parent not in graph:
1111
graph[version] = parents
1112
return topo_sort(graph.items())
1114
def get_ancestry_with_ghosts(self, versions):
1115
"""See VersionedFile.get_ancestry_with_ghosts."""
1116
# get a graph of all the mentioned versions:
1118
pending = set(versions)
1120
version = pending.pop()
1122
parents = self._cache[version][4]
1128
# got the parents ok
1129
for parent in parents:
1130
if parent not in graph:
1132
graph[version] = parents
1133
return topo_sort(graph.items())
1135
def num_versions(self):
1136
return len(self._history)
1138
__len__ = num_versions
1140
def get_versions(self):
1141
return self._history
1143
def idx_to_name(self, idx):
1144
return self._history[idx]
1146
def lookup(self, version_id):
1147
assert version_id in self._cache
1148
return self._cache[version_id][5]
1150
def _version_list_to_index(self, versions):
1152
for version in versions:
1153
if version in self._cache:
1154
# -- inlined lookup() --
1155
result_list.append(str(self._cache[version][5]))
1156
# -- end lookup () --
1158
result_list.append('.' + version.encode('utf-8'))
1159
return ' '.join(result_list)
1161
def add_version(self, version_id, options, pos, size, parents):
1162
"""Add a version record to the index."""
1163
self.add_versions(((version_id, options, pos, size, parents),))
1165
def add_versions(self, versions):
1166
"""Add multiple versions to the index.
1168
:param versions: a list of tuples:
1169
(version_id, options, pos, size, parents).
1172
for version_id, options, pos, size, parents in versions:
1173
line = "\n%s %s %s %s %s :" % (version_id.encode('utf-8'),
1177
self._version_list_to_index(parents))
1178
assert isinstance(line, str), \
1179
'content must be utf-8 encoded: %r' % (line,)
1181
self._transport.append(self._filename, StringIO(''.join(lines)))
1182
# cache after writing, so that a failed write leads to missing cache
1183
# entries not extra ones. XXX TODO: RBC 20060502 in the event of a
1184
# failure, reload the index or flush it or some such, to prevent
1185
# writing records that did complete twice.
1186
for version_id, options, pos, size, parents in versions:
1187
self._cache_version(version_id, options, pos, size, parents)
1189
def has_version(self, version_id):
1190
"""True if the version is in the index."""
1191
return self._cache.has_key(version_id)
1193
def get_position(self, version_id):
1194
"""Return data position and size of specified version."""
1195
return (self._cache[version_id][2], \
1196
self._cache[version_id][3])
1198
def get_method(self, version_id):
1199
"""Return compression method of specified version."""
1200
options = self._cache[version_id][1]
1201
if 'fulltext' in options:
1204
assert 'line-delta' in options
1207
def get_options(self, version_id):
1208
return self._cache[version_id][1]
1210
def get_parents(self, version_id):
1211
"""Return parents of specified version ignoring ghosts."""
1212
return [parent for parent in self._cache[version_id][4]
1213
if parent in self._cache]
1215
def get_parents_with_ghosts(self, version_id):
1216
"""Return parents of specified version wth ghosts."""
1217
return self._cache[version_id][4]
1219
def check_versions_present(self, version_ids):
1220
"""Check that all specified versions are present."""
1221
version_ids = set(version_ids)
1222
for version_id in list(version_ids):
1223
if version_id in self._cache:
1224
version_ids.remove(version_id)
1226
raise RevisionNotPresent(list(version_ids)[0], self.filename)
1229
class _KnitData(_KnitComponentFile):
1230
"""Contents of the knit data file"""
1232
HEADER = "# bzr knit data 8\n"
1234
def __init__(self, transport, filename, mode, create=False, file_mode=None):
1235
_KnitComponentFile.__init__(self, transport, filename, mode)
1237
self._checked = False
1239
self._transport.put(self._filename, StringIO(''), mode=file_mode)
1242
def clear_cache(self):
1243
"""Clear the record cache."""
1246
def _open_file(self):
1247
if self._file is None:
1249
self._file = self._transport.get(self._filename)
1254
def _record_to_data(self, version_id, digest, lines):
1255
"""Convert version_id, digest, lines into a raw data block.
1257
:return: (len, a StringIO instance with the raw data ready to read.)
1260
data_file = GzipFile(None, mode='wb', fileobj=sio)
1261
data_file.writelines(chain(
1262
["version %s %d %s\n" % (version_id.encode('utf-8'),
1266
["end %s\n" % version_id.encode('utf-8')]))
1273
def add_raw_record(self, raw_data):
1274
"""Append a prepared record to the data file.
1276
:return: the offset in the data file raw_data was written.
1278
assert isinstance(raw_data, str), 'data must be plain bytes'
1279
return self._transport.append(self._filename, StringIO(raw_data))
1281
def add_record(self, version_id, digest, lines):
1282
"""Write new text record to disk. Returns the position in the
1283
file where it was written."""
1284
size, sio = self._record_to_data(version_id, digest, lines)
1286
self._records[version_id] = (digest, lines)
1288
start_pos = self._transport.append(self._filename, sio)
1289
return start_pos, size
1291
def _parse_record_header(self, version_id, raw_data):
1292
"""Parse a record header for consistency.
1294
:return: the header and the decompressor stream.
1295
as (stream, header_record)
1297
df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
1298
rec = df.readline().split()
1300
raise KnitCorrupt(self._filename, 'unexpected number of elements in record header')
1301
if rec[1].decode('utf-8')!= version_id:
1302
raise KnitCorrupt(self._filename,
1303
'unexpected version, wanted %r, got %r' % (
1304
version_id, rec[1]))
1307
def _parse_record(self, version_id, data):
1309
# 4168 calls in 2880 217 internal
1310
# 4168 calls to _parse_record_header in 2121
1311
# 4168 calls to readlines in 330
1312
df, rec = self._parse_record_header(version_id, data)
1313
record_contents = df.readlines()
1314
l = record_contents.pop()
1315
assert len(record_contents) == int(rec[2])
1316
if l.decode('utf-8') != 'end %s\n' % version_id:
1317
raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r'
1320
return record_contents, rec[3]
1322
def read_records_iter_raw(self, records):
1323
"""Read text records from data file and yield raw data.
1325
This unpacks enough of the text record to validate the id is
1326
as expected but thats all.
1328
It will actively recompress currently cached records on the
1329
basis that that is cheaper than I/O activity.
1332
for version_id, pos, size in records:
1333
if version_id not in self._records:
1334
needed_records.append((version_id, pos, size))
1336
# setup an iterator of the external records:
1337
# uses readv so nice and fast we hope.
1338
if len(needed_records):
1339
# grab the disk data needed.
1340
raw_records = self._transport.readv(self._filename,
1341
[(pos, size) for version_id, pos, size in needed_records])
1343
for version_id, pos, size in records:
1344
if version_id in self._records:
1345
# compress a new version
1346
size, sio = self._record_to_data(version_id,
1347
self._records[version_id][0],
1348
self._records[version_id][1])
1349
yield version_id, sio.getvalue()
1351
pos, data = raw_records.next()
1352
# validate the header
1353
df, rec = self._parse_record_header(version_id, data)
1355
yield version_id, data
1358
def read_records_iter(self, records):
1359
"""Read text records from data file and yield result.
1361
Each passed record is a tuple of (version_id, pos, len) and
1362
will be read in the given order. Yields (version_id,
1366
# 60890 calls for 4168 extractions in 5045, 683 internal.
1367
# 4168 calls to readv in 1411
1368
# 4168 calls to parse_record in 2880
1371
for version_id, pos, size in records:
1372
if version_id not in self._records:
1373
needed_records.append((version_id, pos, size))
1375
if len(needed_records):
1376
# We take it that the transport optimizes the fetching as good
1377
# as possible (ie, reads continous ranges.)
1378
response = self._transport.readv(self._filename,
1379
[(pos, size) for version_id, pos, size in needed_records])
1381
for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
1382
content, digest = self._parse_record(record_id, data)
1383
self._records[record_id] = (digest, content)
1385
for version_id, pos, size in records:
1386
yield version_id, list(self._records[version_id][1]), self._records[version_id][0]
1388
def read_records(self, records):
1389
"""Read records into a dictionary."""
1391
for record_id, content, digest in self.read_records_iter(records):
1392
components[record_id] = (content, digest)
1396
class InterKnit(InterVersionedFile):
1397
"""Optimised code paths for knit to knit operations."""
1399
_matching_file_from_factory = KnitVersionedFile
1400
_matching_file_to_factory = KnitVersionedFile
1403
def is_compatible(source, target):
1404
"""Be compatible with knits. """
1406
return (isinstance(source, KnitVersionedFile) and
1407
isinstance(target, KnitVersionedFile))
1408
except AttributeError:
1411
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1412
"""See InterVersionedFile.join."""
1413
assert isinstance(self.source, KnitVersionedFile)
1414
assert isinstance(self.target, KnitVersionedFile)
1416
version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1421
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1423
version_ids = list(version_ids)
1424
if None in version_ids:
1425
version_ids.remove(None)
1427
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1428
this_versions = set(self.target._index.get_versions())
1429
needed_versions = self.source_ancestry - this_versions
1430
cross_check_versions = self.source_ancestry.intersection(this_versions)
1431
mismatched_versions = set()
1432
for version in cross_check_versions:
1433
# scan to include needed parents.
1434
n1 = set(self.target.get_parents_with_ghosts(version))
1435
n2 = set(self.source.get_parents_with_ghosts(version))
1437
# FIXME TEST this check for cycles being introduced works
1438
# the logic is we have a cycle if in our graph we are an
1439
# ancestor of any of the n2 revisions.
1445
parent_ancestors = self.source.get_ancestry(parent)
1446
if version in parent_ancestors:
1447
raise errors.GraphCycleError([parent, version])
1448
# ensure this parent will be available later.
1449
new_parents = n2.difference(n1)
1450
needed_versions.update(new_parents.difference(this_versions))
1451
mismatched_versions.add(version)
1453
if not needed_versions and not mismatched_versions:
1455
full_list = topo_sort(self.source.get_graph())
1457
version_list = [i for i in full_list if (not self.target.has_version(i)
1458
and i in needed_versions)]
1462
copy_queue_records = []
1464
for version_id in version_list:
1465
options = self.source._index.get_options(version_id)
1466
parents = self.source._index.get_parents_with_ghosts(version_id)
1467
# check that its will be a consistent copy:
1468
for parent in parents:
1469
# if source has the parent, we must :
1470
# * already have it or
1471
# * have it scheduled already
1472
# otherwise we dont care
1473
assert (self.target.has_version(parent) or
1474
parent in copy_set or
1475
not self.source.has_version(parent))
1476
data_pos, data_size = self.source._index.get_position(version_id)
1477
copy_queue_records.append((version_id, data_pos, data_size))
1478
copy_queue.append((version_id, options, parents))
1479
copy_set.add(version_id)
1481
# data suck the join:
1483
total = len(version_list)
1486
for (version_id, raw_data), \
1487
(version_id2, options, parents) in \
1488
izip(self.source._data.read_records_iter_raw(copy_queue_records),
1490
assert version_id == version_id2, 'logic error, inconsistent results'
1492
pb.update("Joining knit", count, total)
1493
raw_records.append((version_id, options, parents, len(raw_data)))
1494
raw_datum.append(raw_data)
1495
self.target._add_raw_records(raw_records, ''.join(raw_datum))
1497
for version in mismatched_versions:
1498
# FIXME RBC 20060309 is this needed?
1499
n1 = set(self.target.get_parents_with_ghosts(version))
1500
n2 = set(self.source.get_parents_with_ghosts(version))
1501
# write a combined record to our history preserving the current
1502
# parents as first in the list
1503
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1504
self.target.fix_parents(version, new_parents)
1510
InterVersionedFile.register_optimiser(InterKnit)
1513
class WeaveToKnit(InterVersionedFile):
1514
"""Optimised code paths for weave to knit operations."""
1516
_matching_file_from_factory = bzrlib.weave.WeaveFile
1517
_matching_file_to_factory = KnitVersionedFile
1520
def is_compatible(source, target):
1521
"""Be compatible with weaves to knits."""
1523
return (isinstance(source, bzrlib.weave.Weave) and
1524
isinstance(target, KnitVersionedFile))
1525
except AttributeError:
1528
def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1529
"""See InterVersionedFile.join."""
1530
assert isinstance(self.source, bzrlib.weave.Weave)
1531
assert isinstance(self.target, KnitVersionedFile)
1533
version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1538
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1540
version_ids = list(version_ids)
1542
self.source_ancestry = set(self.source.get_ancestry(version_ids))
1543
this_versions = set(self.target._index.get_versions())
1544
needed_versions = self.source_ancestry - this_versions
1545
cross_check_versions = self.source_ancestry.intersection(this_versions)
1546
mismatched_versions = set()
1547
for version in cross_check_versions:
1548
# scan to include needed parents.
1549
n1 = set(self.target.get_parents_with_ghosts(version))
1550
n2 = set(self.source.get_parents(version))
1551
# if all of n2's parents are in n1, then its fine.
1552
if n2.difference(n1):
1553
# FIXME TEST this check for cycles being introduced works
1554
# the logic is we have a cycle if in our graph we are an
1555
# ancestor of any of the n2 revisions.
1561
parent_ancestors = self.source.get_ancestry(parent)
1562
if version in parent_ancestors:
1563
raise errors.GraphCycleError([parent, version])
1564
# ensure this parent will be available later.
1565
new_parents = n2.difference(n1)
1566
needed_versions.update(new_parents.difference(this_versions))
1567
mismatched_versions.add(version)
1569
if not needed_versions and not mismatched_versions:
1571
full_list = topo_sort(self.source.get_graph())
1573
version_list = [i for i in full_list if (not self.target.has_version(i)
1574
and i in needed_versions)]
1578
total = len(version_list)
1579
for version_id in version_list:
1580
pb.update("Converting to knit", count, total)
1581
parents = self.source.get_parents(version_id)
1582
# check that its will be a consistent copy:
1583
for parent in parents:
1584
# if source has the parent, we must already have it
1585
assert (self.target.has_version(parent))
1586
self.target.add_lines(
1587
version_id, parents, self.source.get_lines(version_id))
1590
for version in mismatched_versions:
1591
# FIXME RBC 20060309 is this needed?
1592
n1 = set(self.target.get_parents_with_ghosts(version))
1593
n2 = set(self.source.get_parents(version))
1594
# write a combined record to our history preserving the current
1595
# parents as first in the list
1596
new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1597
self.target.fix_parents(version, new_parents)
1603
InterVersionedFile.register_optimiser(WeaveToKnit)
1606
class SequenceMatcher(difflib.SequenceMatcher):
1607
"""Knit tuned sequence matcher.
1609
This is based on profiling of difflib which indicated some improvements
1610
for our usage pattern.
1613
def find_longest_match(self, alo, ahi, blo, bhi):
1614
"""Find longest matching block in a[alo:ahi] and b[blo:bhi].
1616
If isjunk is not defined:
1618
Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
1619
alo <= i <= i+k <= ahi
1620
blo <= j <= j+k <= bhi
1621
and for all (i',j',k') meeting those conditions,
1624
and if i == i', j <= j'
1626
In other words, of all maximal matching blocks, return one that
1627
starts earliest in a, and of all those maximal matching blocks that
1628
start earliest in a, return the one that starts earliest in b.
1630
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
1631
>>> s.find_longest_match(0, 5, 0, 9)
1634
If isjunk is defined, first the longest matching block is
1635
determined as above, but with the additional restriction that no
1636
junk element appears in the block. Then that block is extended as
1637
far as possible by matching (only) junk elements on both sides. So
1638
the resulting block never matches on junk except as identical junk
1639
happens to be adjacent to an "interesting" match.
1641
Here's the same example as before, but considering blanks to be
1642
junk. That prevents " abcd" from matching the " abcd" at the tail
1643
end of the second sequence directly. Instead only the "abcd" can
1644
match, and matches the leftmost "abcd" in the second sequence:
1646
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
1647
>>> s.find_longest_match(0, 5, 0, 9)
1650
If no blocks match, return (alo, blo, 0).
1652
>>> s = SequenceMatcher(None, "ab", "c")
1653
>>> s.find_longest_match(0, 2, 0, 1)
1657
# CAUTION: stripping common prefix or suffix would be incorrect.
1661
# Longest matching block is "ab", but if common prefix is
1662
# stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
1663
# strip, so ends up claiming that ab is changed to acab by
1664
# inserting "ca" in the middle. That's minimal but unintuitive:
1665
# "it's obvious" that someone inserted "ac" at the front.
1666
# Windiff ends up at the same place as diff, but by pairing up
1667
# the unique 'b's and then matching the first two 'a's.
1669
a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
1670
besti, bestj, bestsize = alo, blo, 0
1671
# find longest junk-free match
1672
# during an iteration of the loop, j2len[j] = length of longest
1673
# junk-free match ending with a[i-1] and b[j]
1677
for i in xrange(alo, ahi):
1678
# look at all instances of a[i] in b; note that because
1679
# b2j has no junk keys, the loop is skipped if a[i] is junk
1680
j2lenget = j2len.get
1683
# changing b2j.get(a[i], nothing) to a try:Keyerror pair produced the
1684
# following improvement
1685
# 704 0 4650.5320 2620.7410 bzrlib.knit:1336(find_longest_match)
1686
# +326674 0 1655.1210 1655.1210 +<method 'get' of 'dict' objects>
1687
# +76519 0 374.6700 374.6700 +<method 'has_key' of 'dict' objects>
1689
# 704 0 3733.2820 2209.6520 bzrlib.knit:1336(find_longest_match)
1690
# +211400 0 1147.3520 1147.3520 +<method 'get' of 'dict' objects>
1691
# +76519 0 376.2780 376.2780 +<method 'has_key' of 'dict' objects>
1703
k = newj2len[j] = 1 + j2lenget(-1 + j, 0)
1705
besti, bestj, bestsize = 1 + i-k, 1 + j-k, k
1708
# Extend the best by non-junk elements on each end. In particular,
1709
# "popular" non-junk elements aren't in b2j, which greatly speeds
1710
# the inner loop above, but also means "the best" match so far
1711
# doesn't contain any junk *or* popular non-junk elements.
1712
while besti > alo and bestj > blo and \
1713
not isbjunk(b[bestj-1]) and \
1714
a[besti-1] == b[bestj-1]:
1715
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1716
while besti+bestsize < ahi and bestj+bestsize < bhi and \
1717
not isbjunk(b[bestj+bestsize]) and \
1718
a[besti+bestsize] == b[bestj+bestsize]:
1721
# Now that we have a wholly interesting match (albeit possibly
1722
# empty!), we may as well suck up the matching junk on each
1723
# side of it too. Can't think of a good reason not to, and it
1724
# saves post-processing the (possibly considerable) expense of
1725
# figuring out what to do with it. In the case of an empty
1726
# interesting match, this is clearly the right thing to do,
1727
# because no other kind of match is possible in the regions.
1728
while besti > alo and bestj > blo and \
1729
isbjunk(b[bestj-1]) and \
1730
a[besti-1] == b[bestj-1]:
1731
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1732
while besti+bestsize < ahi and bestj+bestsize < bhi and \
1733
isbjunk(b[bestj+bestsize]) and \
1734
a[besti+bestsize] == b[bestj+bestsize]:
1735
bestsize = bestsize + 1
1737
return besti, bestj, bestsize