/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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>
5
#
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.
10
#
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.
15
#
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
19
20
"""Knit versionedfile implementation.
21
22
A knit is a versioned file implementation that supports efficient append only
23
updates.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
24
25
Knit file layout:
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"
30
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
34
59,59,3
35
8
36
8         if ie.executable:
37
8             e.set('executable', 'yes')
38
130,130,2
39
8         if elt.get('executable') == 'yes':
40
8             ie.executable = True
41
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 
42
43
44
whats in an index:
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
50
51
52
so the index sequence is the dictionary compressed sequence number used
53
in the deltas to provide line annotation
54
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
55
"""
56
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
57
# TODOS:
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 
61
#                    always' approach.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
62
# move sha1 out of the content so that join is faster at verifying parents
63
# record content length ?
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
64
                  
65
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
66
from copy import copy
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
67
from cStringIO import StringIO
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
68
import difflib
1596.2.28 by Robert Collins
more knit profile based tuning.
69
from itertools import izip, chain
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
70
import os
1628.1.2 by Robert Collins
More knit micro-optimisations.
71
import sys
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
72
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
73
import bzrlib
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
74
import bzrlib.errors as errors
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
75
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
76
        InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
77
        RevisionNotPresent, RevisionAlreadyPresent
1641.1.1 by Robert Collins
* Various microoptimisations to knit and gzip - reducing function call
78
from bzrlib.tuned_gzip import *
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
79
from bzrlib.trace import mutter
80
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
1664.2.13 by Aaron Bentley
Knit plan_merge uses slices instead of xenumerate
81
     sha_strings
1563.2.13 by Robert Collins
InterVersionedFile implemented.
82
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
83
from bzrlib.tsort import topo_sort
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
84
import bzrlib.weave
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
85
86
87
# TODO: Split out code specific to this format into an associated object.
88
89
# TODO: Can we put in some kind of value to check that the index and data
90
# files belong together?
91
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
92
# TODO: accommodate binaries, perhaps by storing a byte count
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
93
94
# TODO: function to check whole file
95
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.
99
100
DATA_SUFFIX = '.knit'
101
INDEX_SUFFIX = '.kndx'
102
103
104
class KnitContent(object):
105
    """Content of a knit version to which deltas can be applied."""
106
107
    def __init__(self, lines):
108
        self._lines = lines
109
110
    def annotate_iter(self):
111
        """Yield tuples of (origin, text) for each content line."""
112
        for origin, text in self._lines:
113
            yield origin, text
114
115
    def annotate(self):
116
        """Return a list of (origin, text) tuples."""
117
        return list(self.annotate_iter())
118
119
    def line_delta_iter(self, new_lines):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
120
        """Generate line-based delta from this content to new_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
121
        new_texts = [text for origin, text in new_lines._lines]
122
        old_texts = [text for origin, text in self._lines]
1711.2.11 by John Arbash Meinel
Rename patiencediff.SequenceMatcher => PatienceSequenceMatcher and knit.SequenceMatcher => KnitSequenceMatcher
123
        s = KnitSequenceMatcher(None, old_texts, new_texts)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
124
        for op in s.get_opcodes():
125
            if op[0] == 'equal':
126
                continue
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
127
            #     ofrom   oto   length        data
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
128
            yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
129
130
    def line_delta(self, new_lines):
131
        return list(self.line_delta_iter(new_lines))
132
133
    def text(self):
134
        return [text for origin, text in self._lines]
135
136
137
class _KnitFactory(object):
138
    """Base factory for creating content objects."""
139
140
    def make(self, lines, version):
141
        num_lines = len(lines)
142
        return KnitContent(zip([version] * num_lines, lines))
143
144
145
class KnitAnnotateFactory(_KnitFactory):
146
    """Factory for creating annotated Content objects."""
147
148
    annotated = True
149
150
    def parse_fulltext(self, content, version):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
151
        """Convert fulltext to internal representation
152
153
        fulltext content is of the format
154
        revid(utf8) plaintext\n
155
        internal representation is of the format:
156
        (revid, plaintext)
157
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
158
        lines = []
159
        for line in content:
160
            origin, text = line.split(' ', 1)
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
161
            lines.append((origin.decode('utf-8'), text))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
162
        return KnitContent(lines)
163
164
    def parse_line_delta_iter(self, lines):
1628.1.2 by Robert Collins
More knit micro-optimisations.
165
        for result_item in self.parse_line_delta[lines]:
166
            yield result_item
167
168
    def parse_line_delta(self, lines, version):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
169
        """Convert a line based delta into internal representation.
170
171
        line delta is in the form of:
172
        intstart intend intcount
173
        1..count lines:
174
        revid(utf8) newline\n
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
175
        internal representation is
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
176
        (start, end, count, [1..count tuples (revid, newline)])
177
        """
1628.1.2 by Robert Collins
More knit micro-optimisations.
178
        result = []
179
        lines = iter(lines)
180
        next = lines.next
181
        # walk through the lines parsing.
182
        for header in lines:
183
            start, end, count = [int(n) for n in header.split(',')]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
184
            contents = []
1628.1.2 by Robert Collins
More knit micro-optimisations.
185
            remaining = count
186
            while remaining:
187
                origin, text = next().split(' ', 1)
188
                remaining -= 1
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
189
                contents.append((origin.decode('utf-8'), text))
1628.1.2 by Robert Collins
More knit micro-optimisations.
190
            result.append((start, end, count, contents))
191
        return result
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
192
193
    def lower_fulltext(self, content):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
194
        """convert a fulltext content record into a serializable form.
195
196
        see parse_fulltext which this inverts.
197
        """
198
        return ['%s %s' % (o.encode('utf-8'), t) for o, t in content._lines]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
199
200
    def lower_line_delta(self, delta):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
201
        """convert a delta into a serializable form.
202
1628.1.2 by Robert Collins
More knit micro-optimisations.
203
        See parse_line_delta which this inverts.
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
204
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
205
        out = []
206
        for start, end, c, lines in delta:
207
            out.append('%d,%d,%d\n' % (start, end, c))
208
            for origin, text in lines:
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
209
                out.append('%s %s' % (origin.encode('utf-8'), text))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
210
        return out
211
212
213
class KnitPlainFactory(_KnitFactory):
214
    """Factory for creating plain Content objects."""
215
216
    annotated = False
217
218
    def parse_fulltext(self, content, version):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
219
        """This parses an unannotated fulltext.
220
221
        Note that this is not a noop - the internal representation
222
        has (versionid, line) - its just a constant versionid.
223
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
224
        return self.make(content, version)
225
226
    def parse_line_delta_iter(self, lines, version):
227
        while lines:
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])
231
            del lines[:c]
232
233
    def parse_line_delta(self, lines, version):
234
        return list(self.parse_line_delta_iter(lines, version))
235
    
236
    def lower_fulltext(self, content):
237
        return content.text()
238
239
    def lower_line_delta(self, delta):
240
        out = []
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])
244
        return out
245
246
247
def make_empty_knit(transport, relpath):
248
    """Construct a empty knit at the specified location."""
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
249
    k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
250
    k._data._open_file()
251
252
253
class KnitVersionedFile(VersionedFile):
254
    """Weave-like structure with faster random access.
255
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.
260
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.
266
    """
267
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
268
    def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
1563.2.25 by Robert Collins
Merge in upstream.
269
                 basis_knit=None, delta=True, create=False):
270
        """Construct a knit at location specified by relpath.
271
        
272
        :param create: If not True, only open an existing knit.
273
        """
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
274
        if access_mode is None:
275
            access_mode = 'w'
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
276
        super(KnitVersionedFile, self).__init__(access_mode)
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
277
        assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
278
        assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
279
            type(basis_knit)
280
281
        self.transport = transport
282
        self.filename = relpath
283
        self.basis_knit = basis_knit
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
284
        self.factory = factory or KnitAnnotateFactory()
285
        self.writable = (access_mode == 'w')
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
286
        self.delta = delta
287
288
        self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
1666.1.6 by Robert Collins
Make knit the default format.
289
            access_mode, create=create, file_mode=file_mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
290
        self._data = _KnitData(transport, relpath + DATA_SUFFIX,
1666.1.6 by Robert Collins
Make knit the default format.
291
            access_mode, create=create and not len(self), file_mode=file_mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
292
1704.2.10 by Martin Pool
Add KnitVersionedFile.__repr__ method
293
    def __repr__(self):
294
        return '%s(%s)' % (self.__class__.__name__, 
295
                           self.transport.abspath(self.filename))
296
    
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
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)
301
        present_parents = []
302
        ghosts = []
303
        parent_texts = {}
304
        for parent in parents:
305
            if not self.has_version(parent):
306
                ghosts.append(parent)
307
            else:
308
                present_parents.append(parent)
309
310
        if delta_parent is None:
311
            # reconstitute as full text.
312
            assert len(delta) == 1 or len(delta) == 0
313
            if len(delta):
314
                assert delta[0][0] == 0
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
315
                assert delta[0][1] == 0, delta[0][1]
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
316
            return super(KnitVersionedFile, self)._add_delta(version_id,
317
                                                             parents,
318
                                                             delta_parent,
319
                                                             sha1,
320
                                                             noeol,
321
                                                             delta)
322
323
        digest = sha1
324
325
        options = []
326
        if noeol:
327
            options.append('no-eol')
328
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.
334
            count = 0
335
            delta_parents = [delta_parent]
336
            while count < 25:
337
                parent = delta_parents[0]
338
                method = self._index.get_method(parent)
339
                if method == 'fulltext':
340
                    break
341
                delta_parents = self._index.get_parents(parent)
342
                count = count + 1
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,
347
                                                                 parents,
348
                                                                 delta_parent,
349
                                                                 sha1,
350
                                                                 noeol,
351
                                                                 delta)
352
353
        options.append('line-delta')
354
        store_lines = self.factory.lower_line_delta(delta)
355
356
        where, size = self._data.add_record(version_id, digest, store_lines)
357
        self._index.add_version(version_id, options, where, size, parents)
358
1692.2.1 by Robert Collins
Fix knit based push to only perform 2 appends to the target, rather that 2*new-versions.
359
    def _add_raw_records(self, records, data):
360
        """Add all the records 'records' with data pre-joined in 'data'.
361
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
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
365
                     the preceding records sizes.
1692.2.1 by Robert Collins
Fix knit based push to only perform 2 appends to the target, rather that 2*new-versions.
366
        """
367
        # write all the data
368
        pos = self._data.add_raw_record(data)
369
        index_entries = []
370
        for (version_id, options, parents, size) in records:
371
            index_entries.append((version_id, options, pos, size, parents))
372
            pos += size
373
        self._index.add_versions(index_entries)
374
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
375
    def clear_cache(self):
376
        """Clear the data cache only."""
377
        self._data.clear_cache()
378
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
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
382
        # writes
1666.1.6 by Robert Collins
Make knit the default format.
383
        transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename),)
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
384
        # copy the data file
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)
388
1563.2.13 by Robert Collins
InterVersionedFile implemented.
389
    def create_empty(self, name, transport, mode=None):
1563.2.25 by Robert Collins
Merge in upstream.
390
        return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
391
    
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
392
    def _fix_parents(self, version, new_parents):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
393
        """Fix the parents list for version.
394
        
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
398
        list.
399
        """
400
        current_values = self._index._cache[version]
401
        assert set(current_values[4]).difference(set(new_parents)) == set()
402
        self._index.add_version(version,
403
                                current_values[1], 
404
                                current_values[2],
405
                                current_values[3],
406
                                new_parents)
407
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
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)
412
        
413
        parents = self.get_parents(version_id)
414
        if len(parents):
415
            parent = parents[0]
416
        else:
417
            parent = None
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)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
421
        noeol = 'no-eol' in self._index.get_options(version_id)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
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()
427
            else:
428
                old_texts = []
429
            new_texts = new_content.text()
1711.2.11 by John Arbash Meinel
Rename patiencediff.SequenceMatcher => PatienceSequenceMatcher and knit.SequenceMatcher => KnitSequenceMatcher
430
            delta_seq = KnitSequenceMatcher(None, old_texts, new_texts)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
431
            return parent, sha1, noeol, self._make_line_delta(delta_seq, new_content)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
432
        else:
433
            delta = self.factory.parse_line_delta(data, version_idx)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
434
            return parent, sha1, noeol, delta
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
435
        
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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)
440
1666.1.6 by Robert Collins
Make knit the default format.
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]
445
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
446
    @staticmethod
447
    def get_suffixes():
448
        """See VersionedFile.get_suffixes()."""
449
        return [DATA_SUFFIX, INDEX_SUFFIX]
1563.2.13 by Robert Collins
InterVersionedFile implemented.
450
1594.2.8 by Robert Collins
add ghost aware apis to knits.
451
    def has_ghost(self, version_id):
452
        """True if there is a ghost reference in the file to version_id."""
453
        # maybe we have it
454
        if self.has_version(version_id):
455
            return False
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
456
        # optimisable if needed by memoising the _ghosts set.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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:
462
                        return True
463
        return False
464
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
465
    def versions(self):
466
        """See VersionedFile.versions."""
467
        return self._index.get_versions()
468
469
    def has_version(self, version_id):
470
        """See VersionedFile.has_version."""
471
        return self._index.has_version(version_id)
472
473
    __contains__ = has_version
474
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
475
    def _merge_annotations(self, content, parents, parent_texts={},
476
                           delta=None, annotated=None):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
477
        """Merge annotations for content.  This is done by comparing
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
478
        the annotations based on changed to the text.
479
        """
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
480
        if annotated:
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
481
            delta_seq = None
482
            for parent_id in parents:
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
483
                merge_content = self._get_content(parent_id, parent_texts)
1711.2.11 by John Arbash Meinel
Rename patiencediff.SequenceMatcher => PatienceSequenceMatcher and knit.SequenceMatcher => KnitSequenceMatcher
484
                seq = KnitSequenceMatcher(None, merge_content.text(), content.text())
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
485
                if delta_seq is None:
486
                    # setup a delta seq to reuse.
487
                    delta_seq = seq
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
488
                for i, j, n in seq.get_matching_blocks():
489
                    if n == 0:
490
                        continue
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]
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
496
        if delta:
497
            if not annotated:
498
                reference_content = self._get_content(parents[0], parent_texts)
499
                new_texts = content.text()
500
                old_texts = reference_content.text()
1711.2.11 by John Arbash Meinel
Rename patiencediff.SequenceMatcher => PatienceSequenceMatcher and knit.SequenceMatcher => KnitSequenceMatcher
501
                delta_seq = KnitSequenceMatcher(None, old_texts, new_texts)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
502
            return self._make_line_delta(delta_seq, content)
503
504
    def _make_line_delta(self, delta_seq, new_content):
505
        """Generate a line delta from delta_seq and new_content."""
506
        diff_hunks = []
507
        for op in delta_seq.get_opcodes():
508
            if op[0] == 'equal':
509
                continue
510
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
511
        return diff_hunks
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
512
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.
516
517
        The components should be applied in the order of the returned
518
        list.
519
520
        The basis knit will be used to the largest extent possible
521
        since it is assumed that accesses to it is faster.
522
        """
1628.1.2 by Robert Collins
More knit micro-optimisations.
523
        #profile notes:
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
528
        
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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.
532
        #
533
        # basis_revisions is a list of versions that needs to be
534
        # fetched but exists in the basis knit.
535
536
        basis = self.basis_knit
537
        needed_versions = []
538
        basis_versions = []
539
        cursor = version_id
540
541
        while 1:
542
            picked_knit = self
543
            if basis and basis._index.has_version(cursor):
544
                picked_knit = basis
545
                basis_versions.append(cursor)
546
            method = picked_knit._index.get_method(cursor)
547
            needed_versions.append((method, cursor))
548
            if method == 'fulltext':
549
                break
550
            cursor = picked_knit.get_parents(cursor)[0]
551
552
        components = {}
553
        if basis_versions:
554
            records = []
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))
559
560
        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))
566
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).
570
        out = []
571
        for method, comp_id in reversed(needed_versions):
572
            out.append((comp_id, method, components[comp_id]))
573
574
        return out
575
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
576
    def _get_content(self, version_id, parent_texts={}):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
577
        """Returns a content object that makes up the specified
578
        version."""
579
        if not self.has_version(version_id):
580
            raise RevisionNotPresent(version_id, self.filename)
581
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
582
        cached_version = parent_texts.get(version_id, None)
583
        if cached_version is not None:
584
            return cached_version
585
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
586
        if self.basis_knit and version_id in self.basis_knit:
587
            return self.basis_knit._get_content(version_id)
588
589
        content = None
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)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
598
                content._lines = self._apply_delta(content._lines, delta)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
599
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)
603
1666.1.6 by Robert Collins
Make knit the default format.
604
        # digest here is the digest from the last applied component.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
605
        if sha_strings(content.text()) != digest:
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
606
            import pdb;pdb.set_trace()
607
            raise KnitCorrupt(self.filename, 'sha-1 does not match %s' % version_id)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
608
609
        return content
610
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)
617
        if version_ids:
618
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
619
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
620
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
621
        """See VersionedFile.add_lines_with_ghosts()."""
622
        self._check_add(version_id, lines)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
623
        return self._add(version_id, lines[:], parents, self.delta, parent_texts)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
624
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
625
    def _add_lines(self, version_id, parents, lines, parent_texts):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
626
        """See VersionedFile.add_lines."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
627
        self._check_add(version_id, lines)
628
        self._check_versions_present(parents)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
629
        return self._add(version_id, lines[:], parents, self.delta, parent_texts)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
630
631
    def _check_add(self, version_id, lines):
632
        """check that version_id and lines are safe to add."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
633
        assert self.writable, "knit is not opened for write"
634
        ### FIXME escape. RBC 20060228
635
        if contains_whitespace(version_id):
1668.5.1 by Olaf Conradi
Fix bug in knits when raising InvalidRevisionId without the required
636
            raise InvalidRevisionId(version_id, self.filename)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
637
        if self.has_version(version_id):
638
            raise RevisionAlreadyPresent(version_id, self.filename)
1666.1.6 by Robert Collins
Make knit the default format.
639
        self._check_lines_not_unicode(lines)
640
        self._check_lines_are_lines(lines)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
641
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
642
    def _add(self, version_id, lines, parents, delta, parent_texts):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
643
        """Add a set of lines on top of version specified by parents.
644
645
        If delta is true, compress the text as a line-delta against
646
        the first parent.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
647
648
        Any versions not present will be converted into ghosts.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
649
        """
1596.2.28 by Robert Collins
more knit profile based tuning.
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)
661
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
662
        present_parents = []
1594.2.8 by Robert Collins
add ghost aware apis to knits.
663
        ghosts = []
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
664
        if parent_texts is None:
665
            parent_texts = {}
1594.2.8 by Robert Collins
add ghost aware apis to knits.
666
        for parent in parents:
667
            if not self.has_version(parent):
668
                ghosts.append(parent)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
669
            else:
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
670
                present_parents.append(parent)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
671
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
672
        if delta and not len(present_parents):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
673
            delta = False
674
675
        digest = sha_strings(lines)
676
        options = []
677
        if lines:
678
            if lines[-1][-1] != '\n':
679
                options.append('no-eol')
680
                lines[-1] = lines[-1] + '\n'
681
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
682
        if len(present_parents) and delta:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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.
686
            count = 0
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
687
            delta_parents = present_parents
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
688
            while count < 25:
689
                parent = delta_parents[0]
690
                method = self._index.get_method(parent)
691
                if method == 'fulltext':
692
                    break
693
                delta_parents = self._index.get_parents(parent)
694
                count = count + 1
695
            if method == 'line-delta':
696
                delta = False
697
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
698
        lines = self.factory.make(lines, version_id)
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
699
        if delta or (self.factory.annotated and len(present_parents) > 0):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
700
            # Merge annotations from parent texts if so is needed.
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
701
            delta_hunks = self._merge_annotations(lines, present_parents, parent_texts,
702
                                                  delta, self.factory.annotated)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
703
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
704
        if delta:
705
            options.append('line-delta')
706
            store_lines = self.factory.lower_line_delta(delta_hunks)
707
        else:
708
            options.append('fulltext')
709
            store_lines = self.factory.lower_fulltext(lines)
710
711
        where, size = self._data.add_record(version_id, digest, store_lines)
712
        self._index.add_version(version_id, options, where, size, parents)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
713
        return lines
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
714
1563.2.19 by Robert Collins
stub out a check for knits.
715
    def check(self, progress_bar=None):
716
        """See VersionedFile.check()."""
717
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
718
    def _clone_text(self, new_version_id, old_version_id, parents):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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))
722
723
    def get_lines(self, version_id):
724
        """See VersionedFile.get_lines()."""
725
        return self._get_content(version_id).text()
726
1756.2.1 by Aaron Bentley
Implement get_texts
727
    def get_texts(self, version_ids):
728
        """Return the texts of listed versions as a list of strings."""
729
        texts = []
730
        for version_id in version_ids:
731
            if not self.has_version(version_id):
732
                raise RevisionNotPresent(version_id, self.filename)
733
734
            if self.basis_knit and version_id in self.basis_knit:
735
                continue
736
737
        for version_id in version_ids:
738
            if self.basis_knit and version_id in self.basis_knit:
739
                texts.append(''.join(self.basis_knit._get_content(version_id).text()))
740
                continue
741
742
            content = None
743
            components = self._get_components(version_id)
744
            for component_id, method, (data, digest) in components:
745
                version_idx = self._index.lookup(component_id)
746
                if method == 'fulltext':
747
                    assert content is None
748
                    content = self.factory.parse_fulltext(data, version_idx)
749
                elif method == 'line-delta':
750
                    delta = self.factory.parse_line_delta(data, version_idx)
751
                    content._lines = self._apply_delta(content._lines, delta)
752
753
            if 'no-eol' in self._index.get_options(version_id):
754
                line = content._lines[-1][1].rstrip('\n')
755
                content._lines[-1] = (content._lines[-1][0], line)
756
757
            # digest here is the digest from the last applied component.
758
            if sha_strings(content.text()) != digest:
759
                import pdb;pdb.set_trace()
760
                raise KnitCorrupt(self.filename, 'sha-1 does not match %s' % version_id)
761
762
            texts.append(''.join(content.text()))
763
        return texts
764
            
765
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
766
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
767
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
768
        if version_ids is None:
769
            version_ids = self.versions()
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
770
        # we don't care about inclusions, the caller cares.
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
771
        # but we need to setup a list of records to visit.
772
        # we need version_id, position, length
773
        version_id_records = []
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
774
        requested_versions = list(version_ids)
775
        # filter for available versions
776
        for version_id in requested_versions:
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
777
            if not self.has_version(version_id):
778
                raise RevisionNotPresent(version_id, self.filename)
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
779
        # get a in-component-order queue:
780
        version_ids = []
781
        for version_id in self.versions():
782
            if version_id in requested_versions:
783
                version_ids.append(version_id)
784
                data_pos, length = self._index.get_position(version_id)
785
                version_id_records.append((version_id, data_pos, length))
786
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
787
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
788
        count = 0
789
        total = len(version_id_records)
790
        try:
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
791
            pb.update('Walking content.', count, total)
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
792
            for version_id, data, sha_value in \
793
                self._data.read_records_iter(version_id_records):
794
                pb.update('Walking content.', count, total)
795
                method = self._index.get_method(version_id)
796
                version_idx = self._index.lookup(version_id)
797
                assert method in ('fulltext', 'line-delta')
798
                if method == 'fulltext':
799
                    content = self.factory.parse_fulltext(data, version_idx)
800
                    for line in content.text():
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
801
                        yield line
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
802
                else:
803
                    delta = self.factory.parse_line_delta(data, version_idx)
804
                    for start, end, count, lines in delta:
805
                        for origin, line in lines:
806
                            yield line
807
                count +=1
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
808
            pb.update('Walking content.', total, total)
809
            pb.finished()
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
810
        except:
811
            pb.update('Walking content.', total, total)
812
            pb.finished()
813
            raise
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
814
        
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
815
    def num_versions(self):
816
        """See VersionedFile.num_versions()."""
817
        return self._index.num_versions()
818
819
    __len__ = num_versions
820
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
821
    def annotate_iter(self, version_id):
822
        """See VersionedFile.annotate_iter."""
823
        content = self._get_content(version_id)
824
        for origin, text in content.annotate_iter():
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
825
            yield origin, text
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
826
827
    def get_parents(self, version_id):
828
        """See VersionedFile.get_parents."""
1628.1.2 by Robert Collins
More knit micro-optimisations.
829
        # perf notes:
830
        # optimism counts!
831
        # 52554 calls in 1264 872 internal down from 3674
832
        try:
833
            return self._index.get_parents(version_id)
834
        except KeyError:
835
            raise RevisionNotPresent(version_id, self.filename)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
836
1594.2.8 by Robert Collins
add ghost aware apis to knits.
837
    def get_parents_with_ghosts(self, version_id):
838
        """See VersionedFile.get_parents."""
1628.1.2 by Robert Collins
More knit micro-optimisations.
839
        try:
840
            return self._index.get_parents_with_ghosts(version_id)
841
        except KeyError:
842
            raise RevisionNotPresent(version_id, self.filename)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
843
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
844
    def get_ancestry(self, versions):
845
        """See VersionedFile.get_ancestry."""
846
        if isinstance(versions, basestring):
847
            versions = [versions]
848
        if not versions:
849
            return []
850
        self._check_versions_present(versions)
851
        return self._index.get_ancestry(versions)
852
1594.2.8 by Robert Collins
add ghost aware apis to knits.
853
    def get_ancestry_with_ghosts(self, versions):
854
        """See VersionedFile.get_ancestry_with_ghosts."""
855
        if isinstance(versions, basestring):
856
            versions = [versions]
857
        if not versions:
858
            return []
859
        self._check_versions_present(versions)
860
        return self._index.get_ancestry_with_ghosts(versions)
861
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
862
    #@deprecated_method(zero_eight)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
863
    def walk(self, version_ids):
864
        """See VersionedFile.walk."""
865
        # We take the short path here, and extract all relevant texts
866
        # and put them in a weave and let that do all the work.  Far
867
        # from optimal, but is much simpler.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
868
        # FIXME RB 20060228 this really is inefficient!
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
869
        from bzrlib.weave import Weave
870
871
        w = Weave(self.filename)
872
        ancestry = self.get_ancestry(version_ids)
873
        sorted_graph = topo_sort(self._index.get_graph())
874
        version_list = [vid for vid in sorted_graph if vid in ancestry]
875
        
876
        for version_id in version_list:
877
            lines = self.get_lines(version_id)
878
            w.add_lines(version_id, self.get_parents(version_id), lines)
879
880
        for lineno, insert_id, dset, line in w.walk(version_ids):
881
            yield lineno, insert_id, dset, line
882
1664.2.3 by Aaron Bentley
Add failing test case
883
    def plan_merge(self, ver_a, ver_b):
1664.2.11 by Aaron Bentley
Clarifications from merge review
884
        """See VersionedFile.plan_merge."""
1664.2.6 by Aaron Bentley
Got plan-merge passing tests
885
        ancestors_b = set(self.get_ancestry(ver_b))
886
        def status_a(revision, text):
887
            if revision in ancestors_b:
888
                return 'killed-b', text
889
            else:
890
                return 'new-a', text
891
        
892
        ancestors_a = set(self.get_ancestry(ver_a))
893
        def status_b(revision, text):
894
            if revision in ancestors_a:
895
                return 'killed-a', text
896
            else:
897
                return 'new-b', text
898
1664.2.4 by Aaron Bentley
Identify unchanged lines correctly
899
        annotated_a = self.annotate(ver_a)
900
        annotated_b = self.annotate(ver_b)
1664.2.11 by Aaron Bentley
Clarifications from merge review
901
        plain_a = [t for (a, t) in annotated_a]
902
        plain_b = [t for (a, t) in annotated_b]
1711.2.11 by John Arbash Meinel
Rename patiencediff.SequenceMatcher => PatienceSequenceMatcher and knit.SequenceMatcher => KnitSequenceMatcher
903
        blocks = KnitSequenceMatcher(None, plain_a, plain_b).get_matching_blocks()
1664.2.4 by Aaron Bentley
Identify unchanged lines correctly
904
        a_cur = 0
905
        b_cur = 0
906
        for ai, bi, l in blocks:
1664.2.13 by Aaron Bentley
Knit plan_merge uses slices instead of xenumerate
907
            # process all mismatched sections
908
            # (last mismatched section is handled because blocks always
909
            # includes a 0-length last block)
910
            for revision, text in annotated_a[a_cur:ai]:
1664.2.6 by Aaron Bentley
Got plan-merge passing tests
911
                yield status_a(revision, text)
1664.2.13 by Aaron Bentley
Knit plan_merge uses slices instead of xenumerate
912
            for revision, text in annotated_b[b_cur:bi]:
1664.2.6 by Aaron Bentley
Got plan-merge passing tests
913
                yield status_b(revision, text)
1664.2.13 by Aaron Bentley
Knit plan_merge uses slices instead of xenumerate
914
1664.2.11 by Aaron Bentley
Clarifications from merge review
915
            # and now the matched section
1664.2.13 by Aaron Bentley
Knit plan_merge uses slices instead of xenumerate
916
            a_cur = ai + l
917
            b_cur = bi + l
918
            for text_a, text_b in zip(plain_a[ai:a_cur], plain_b[bi:b_cur]):
1664.2.4 by Aaron Bentley
Identify unchanged lines correctly
919
                assert text_a == text_b
920
                yield "unchanged", text_a
921
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
922
923
class _KnitComponentFile(object):
924
    """One of the files used to implement a knit database"""
925
1666.1.6 by Robert Collins
Make knit the default format.
926
    def __init__(self, transport, filename, mode, file_mode=None):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
927
        self._transport = transport
928
        self._filename = filename
929
        self._mode = mode
1666.1.6 by Robert Collins
Make knit the default format.
930
        self._file_mode=file_mode
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
931
932
    def write_header(self):
1666.1.6 by Robert Collins
Make knit the default format.
933
        if self._transport.append(self._filename, StringIO(self.HEADER),
934
            mode=self._file_mode):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
935
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
936
937
    def check_header(self, fp):
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
938
        line = fp.readline()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
939
        if line != self.HEADER:
940
            raise KnitHeaderError(badline=line)
941
942
    def commit(self):
943
        """Commit is a nop."""
944
945
    def __repr__(self):
946
        return '%s(%s)' % (self.__class__.__name__, self._filename)
947
948
949
class _KnitIndex(_KnitComponentFile):
950
    """Manages knit index file.
951
952
    The index is already kept in memory and read on startup, to enable
953
    fast lookups of revision information.  The cursor of the index
954
    file is always pointing to the end, making it easy to append
955
    entries.
956
957
    _cache is a cache for fast mapping from version id to a Index
958
    object.
959
960
    _history is a cache for fast mapping from indexes to version ids.
961
962
    The index data format is dictionary compressed when it comes to
963
    parent references; a index entry may only have parents that with a
964
    lover index number.  As a result, the index is topological sorted.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
965
966
    Duplicate entries may be written to the index for a single version id
967
    if this is done then the latter one completely replaces the former:
968
    this allows updates to correct version and parent information. 
969
    Note that the two entries may share the delta, and that successive
970
    annotations and references MUST point to the first entry.
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
971
972
    The index file on disc contains a header, followed by one line per knit
973
    record. The same revision can be present in an index file more than once.
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
974
    The first occurrence gets assigned a sequence number starting from 0. 
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
975
    
976
    The format of a single line is
977
    REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
978
    REVISION_ID is a utf8-encoded revision id
979
    FLAGS is a comma separated list of flags about the record. Values include 
980
        no-eol, line-delta, fulltext.
981
    BYTE_OFFSET is the ascii representation of the byte offset in the data file
982
        that the the compressed data starts at.
983
    LENGTH is the ascii representation of the length of the data file.
984
    PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
985
        REVISION_ID.
986
    PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
987
        revision id already in the knit that is a parent of REVISION_ID.
988
    The ' :' marker is the end of record marker.
989
    
990
    partial writes:
991
    when a write is interrupted to the index file, it will result in a line that
992
    does not end in ' :'. If the ' :' is not present at the end of a line, or at
993
    the end of the file, then the record that is missing it will be ignored by
994
    the parser.
995
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
996
    When writing new records to the index file, the data is preceded by '\n'
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
997
    to ensure that records always start on new lines even if the last write was
998
    interrupted. As a result its normal for the last line in the index to be
999
    missing a trailing newline. One can be added with no harmful effects.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1000
    """
1001
1666.1.6 by Robert Collins
Make knit the default format.
1002
    HEADER = "# bzr knit index 8\n"
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1003
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1004
    # speed of knit parsing went from 280 ms to 280 ms with slots addition.
1005
    # __slots__ = ['_cache', '_history', '_transport', '_filename']
1006
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1007
    def _cache_version(self, version_id, options, pos, size, parents):
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1008
        """Cache a version record in the history array and index cache.
1009
        
1010
        This is inlined into __init__ for performance. KEEP IN SYNC.
1011
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
1012
         indexes).
1013
        """
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
1014
        # only want the _history index to reference the 1st index entry
1015
        # for version_id
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1016
        if version_id not in self._cache:
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1017
            index = len(self._history)
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
1018
            self._history.append(version_id)
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1019
        else:
1020
            index = self._cache[version_id][5]
1021
        self._cache[version_id] = (version_id, 
1022
                                   options,
1023
                                   pos,
1024
                                   size,
1025
                                   parents,
1026
                                   index)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1027
1666.1.6 by Robert Collins
Make knit the default format.
1028
    def __init__(self, transport, filename, mode, create=False, file_mode=None):
1029
        _KnitComponentFile.__init__(self, transport, filename, mode, file_mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1030
        self._cache = {}
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
1031
        # position in _history is the 'official' index for a revision
1032
        # but the values may have come from a newer entry.
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1033
        # so - wc -l of a knit index is != the number of unique names
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
1034
        # in the weave.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1035
        self._history = []
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
1036
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1037
        try:
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
1038
            count = 0
1039
            total = 1
1040
            try:
1041
                pb.update('read knit index', count, total)
1042
                fp = self._transport.get(self._filename)
1043
                self.check_header(fp)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1044
                # readlines reads the whole file at once:
1045
                # bad for transports like http, good for local disk
1046
                # we save 60 ms doing this one change (
1047
                # from calling readline each time to calling
1048
                # readlines once.
1049
                # probably what we want for nice behaviour on
1050
                # http is a incremental readlines that yields, or
1051
                # a check for local vs non local indexes,
1052
                for l in fp.readlines():
1053
                    rec = l.split()
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1054
                    if len(rec) < 5 or rec[-1] != ':':
1055
                        # corrupt line.
1056
                        # FIXME: in the future we should determine if its a
1057
                        # short write - and ignore it 
1058
                        # or a different failure, and raise. RBC 20060407
1059
                        continue
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
1060
                    count += 1
1061
                    total += 1
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1062
                    #pb.update('read knit index', count, total)
1063
                    # See self._parse_parents
1064
                    parents = []
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1065
                    for value in rec[4:-1]:
1596.2.19 by Robert Collins
Shave 20% off id2path.
1066
                        if '.' == value[0]:
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1067
                            # uncompressed reference
1068
                            parents.append(value[1:])
1069
                        else:
1070
                            # this is 15/4000ms faster than isinstance,
1071
                            # (in lsprof)
1072
                            # this function is called thousands of times a 
1073
                            # second so small variations add up.
1074
                            assert value.__class__ is str
1075
                            parents.append(self._history[int(value)])
1076
                    # end self._parse_parents
1077
                    # self._cache_version(rec[0], 
1078
                    #                     rec[1].split(','),
1079
                    #                     int(rec[2]),
1080
                    #                     int(rec[3]),
1081
                    #                     parents)
1082
                    # --- self._cache_version
1083
                    # only want the _history index to reference the 1st 
1084
                    # index entry for version_id
1085
                    version_id = rec[0]
1086
                    if version_id not in self._cache:
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1087
                        index = len(self._history)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1088
                        self._history.append(version_id)
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1089
                    else:
1090
                        index = self._cache[version_id][5]
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1091
                    self._cache[version_id] = (version_id,
1092
                                               rec[1].split(','),
1093
                                               int(rec[2]),
1094
                                               int(rec[3]),
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1095
                                               parents,
1096
                                               index)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1097
                    # --- self._cache_version 
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
1098
            except NoSuchFile, e:
1099
                if mode != 'w' or not create:
1100
                    raise
1101
                self.write_header()
1102
        finally:
1103
            pb.update('read knit index', total, total)
1104
            pb.finished()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1105
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1106
    def _parse_parents(self, compressed_parents):
1107
        """convert a list of string parent values into version ids.
1108
1109
        ints are looked up in the index.
1110
        .FOO values are ghosts and converted in to FOO.
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1111
1112
        NOTE: the function is retained here for clarity, and for possible
1113
              use in partial index reads. However bulk processing now has
1114
              it inlined in __init__ for inner-loop optimisation.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1115
        """
1116
        result = []
1117
        for value in compressed_parents:
1596.2.15 by Robert Collins
Microprofiling of knit parsing.
1118
            if value[-1] == '.':
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1119
                # uncompressed reference
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1120
                result.append(value[1:])
1121
            else:
1596.2.15 by Robert Collins
Microprofiling of knit parsing.
1122
                # this is 15/4000ms faster than isinstance,
1123
                # this function is called thousands of times a 
1124
                # second so small variations add up.
1125
                assert value.__class__ is str
1596.2.11 by Robert Collins
Remove utf8 debugging code
1126
                result.append(self._history[int(value)])
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1127
        return result
1128
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1129
    def get_graph(self):
1130
        graph = []
1131
        for version_id, index in self._cache.iteritems():
1132
            graph.append((version_id, index[4]))
1133
        return graph
1134
1135
    def get_ancestry(self, versions):
1136
        """See VersionedFile.get_ancestry."""
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1137
        # get a graph of all the mentioned versions:
1138
        graph = {}
1139
        pending = set(versions)
1140
        while len(pending):
1141
            version = pending.pop()
1142
            parents = self._cache[version][4]
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1143
            # got the parents ok
1144
            # trim ghosts
1145
            parents = [parent for parent in parents if parent in self._cache]
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1146
            for parent in parents:
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1147
                # if not completed and not a ghost
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1148
                if parent not in graph:
1149
                    pending.add(parent)
1150
            graph[version] = parents
1151
        return topo_sort(graph.items())
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1152
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1153
    def get_ancestry_with_ghosts(self, versions):
1154
        """See VersionedFile.get_ancestry_with_ghosts."""
1155
        # get a graph of all the mentioned versions:
1156
        graph = {}
1157
        pending = set(versions)
1158
        while len(pending):
1159
            version = pending.pop()
1160
            try:
1161
                parents = self._cache[version][4]
1162
            except KeyError:
1163
                # ghost, fake it
1164
                graph[version] = []
1165
                pass
1166
            else:
1167
                # got the parents ok
1168
                for parent in parents:
1169
                    if parent not in graph:
1170
                        pending.add(parent)
1171
                graph[version] = parents
1172
        return topo_sort(graph.items())
1173
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1174
    def num_versions(self):
1175
        return len(self._history)
1176
1177
    __len__ = num_versions
1178
1179
    def get_versions(self):
1180
        return self._history
1181
1182
    def idx_to_name(self, idx):
1183
        return self._history[idx]
1184
1185
    def lookup(self, version_id):
1186
        assert version_id in self._cache
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1187
        return self._cache[version_id][5]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1188
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1189
    def _version_list_to_index(self, versions):
1190
        result_list = []
1191
        for version in versions:
1192
            if version in self._cache:
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1193
                # -- inlined lookup() --
1194
                result_list.append(str(self._cache[version][5]))
1195
                # -- end lookup () --
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1196
            else:
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1197
                result_list.append('.' + version.encode('utf-8'))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1198
        return ' '.join(result_list)
1199
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1200
    def add_version(self, version_id, options, pos, size, parents):
1201
        """Add a version record to the index."""
1692.4.1 by Robert Collins
Multiple merges:
1202
        self.add_versions(((version_id, options, pos, size, parents),))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1203
1692.2.1 by Robert Collins
Fix knit based push to only perform 2 appends to the target, rather that 2*new-versions.
1204
    def add_versions(self, versions):
1205
        """Add multiple versions to the index.
1206
        
1207
        :param versions: a list of tuples:
1208
                         (version_id, options, pos, size, parents).
1209
        """
1210
        lines = []
1211
        for version_id, options, pos, size, parents in versions:
1212
            line = "\n%s %s %s %s %s :" % (version_id.encode('utf-8'),
1213
                                           ','.join(options),
1214
                                           pos,
1215
                                           size,
1216
                                           self._version_list_to_index(parents))
1692.4.1 by Robert Collins
Multiple merges:
1217
            assert isinstance(line, str), \
1218
                'content must be utf-8 encoded: %r' % (line,)
1692.2.1 by Robert Collins
Fix knit based push to only perform 2 appends to the target, rather that 2*new-versions.
1219
            lines.append(line)
1220
        self._transport.append(self._filename, StringIO(''.join(lines)))
1221
        # cache after writing, so that a failed write leads to missing cache
1222
        # entries not extra ones. XXX TODO: RBC 20060502 in the event of a 
1223
        # failure, reload the index or flush it or some such, to prevent
1224
        # writing records that did complete twice.
1225
        for version_id, options, pos, size, parents in versions:
1226
            self._cache_version(version_id, options, pos, size, parents)
1227
        
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1228
    def has_version(self, version_id):
1229
        """True if the version is in the index."""
1230
        return self._cache.has_key(version_id)
1231
1232
    def get_position(self, version_id):
1233
        """Return data position and size of specified version."""
1234
        return (self._cache[version_id][2], \
1235
                self._cache[version_id][3])
1236
1237
    def get_method(self, version_id):
1238
        """Return compression method of specified version."""
1239
        options = self._cache[version_id][1]
1240
        if 'fulltext' in options:
1241
            return 'fulltext'
1242
        else:
1243
            assert 'line-delta' in options
1244
            return 'line-delta'
1245
1246
    def get_options(self, version_id):
1247
        return self._cache[version_id][1]
1248
1249
    def get_parents(self, version_id):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1250
        """Return parents of specified version ignoring ghosts."""
1251
        return [parent for parent in self._cache[version_id][4] 
1252
                if parent in self._cache]
1253
1254
    def get_parents_with_ghosts(self, version_id):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1255
        """Return parents of specified version with ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1256
        return self._cache[version_id][4] 
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1257
1258
    def check_versions_present(self, version_ids):
1259
        """Check that all specified versions are present."""
1260
        version_ids = set(version_ids)
1261
        for version_id in list(version_ids):
1262
            if version_id in self._cache:
1263
                version_ids.remove(version_id)
1264
        if version_ids:
1265
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
1266
1267
1268
class _KnitData(_KnitComponentFile):
1269
    """Contents of the knit data file"""
1270
1666.1.6 by Robert Collins
Make knit the default format.
1271
    HEADER = "# bzr knit data 8\n"
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1272
1666.1.6 by Robert Collins
Make knit the default format.
1273
    def __init__(self, transport, filename, mode, create=False, file_mode=None):
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
1274
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1275
        self._file = None
1276
        self._checked = False
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1277
        if create:
1666.1.6 by Robert Collins
Make knit the default format.
1278
            self._transport.put(self._filename, StringIO(''), mode=file_mode)
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1279
        self._records = {}
1280
1281
    def clear_cache(self):
1282
        """Clear the record cache."""
1283
        self._records = {}
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1284
1285
    def _open_file(self):
1286
        if self._file is None:
1287
            try:
1288
                self._file = self._transport.get(self._filename)
1289
            except NoSuchFile:
1290
                pass
1291
        return self._file
1292
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1293
    def _record_to_data(self, version_id, digest, lines):
1294
        """Convert version_id, digest, lines into a raw data block.
1295
        
1296
        :return: (len, a StringIO instance with the raw data ready to read.)
1297
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1298
        sio = StringIO()
1299
        data_file = GzipFile(None, mode='wb', fileobj=sio)
1596.2.28 by Robert Collins
more knit profile based tuning.
1300
        data_file.writelines(chain(
1301
            ["version %s %d %s\n" % (version_id.encode('utf-8'), 
1302
                                     len(lines),
1303
                                     digest)],
1304
            lines,
1628.1.2 by Robert Collins
More knit micro-optimisations.
1305
            ["end %s\n" % version_id.encode('utf-8')]))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1306
        data_file.close()
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1307
        length= sio.tell()
1596.2.28 by Robert Collins
more knit profile based tuning.
1308
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1309
        sio.seek(0)
1310
        return length, sio
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1311
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1312
    def add_raw_record(self, raw_data):
1692.4.1 by Robert Collins
Multiple merges:
1313
        """Append a prepared record to the data file.
1314
        
1315
        :return: the offset in the data file raw_data was written.
1316
        """
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1317
        assert isinstance(raw_data, str), 'data must be plain bytes'
1692.2.1 by Robert Collins
Fix knit based push to only perform 2 appends to the target, rather that 2*new-versions.
1318
        return self._transport.append(self._filename, StringIO(raw_data))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1319
        
1320
    def add_record(self, version_id, digest, lines):
1321
        """Write new text record to disk.  Returns the position in the
1322
        file where it was written."""
1323
        size, sio = self._record_to_data(version_id, digest, lines)
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1324
        # cache
1325
        self._records[version_id] = (digest, lines)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1326
        # write to disk
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1327
        start_pos = self._transport.append(self._filename, sio)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1328
        return start_pos, size
1329
1330
    def _parse_record_header(self, version_id, raw_data):
1331
        """Parse a record header for consistency.
1332
1333
        :return: the header and the decompressor stream.
1334
                 as (stream, header_record)
1335
        """
1336
        df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1337
        rec = df.readline().split()
1338
        if len(rec) != 4:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1339
            raise KnitCorrupt(self._filename, 'unexpected number of elements in record header')
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1340
        if rec[1].decode('utf-8')!= version_id:
1594.3.3 by Robert Collins
Bugfix error message output in knit error raising.
1341
            raise KnitCorrupt(self._filename, 
1594.3.4 by Robert Collins
Change urllib ranges implementation to be one coalesced range per http request.
1342
                              'unexpected version, wanted %r, got %r' % (
1343
                                version_id, rec[1]))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1344
        return df, rec
1345
1346
    def _parse_record(self, version_id, data):
1628.1.2 by Robert Collins
More knit micro-optimisations.
1347
        # profiling notes:
1348
        # 4168 calls in 2880 217 internal
1349
        # 4168 calls to _parse_record_header in 2121
1350
        # 4168 calls to readlines in 330
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1351
        df, rec = self._parse_record_header(version_id, data)
1628.1.2 by Robert Collins
More knit micro-optimisations.
1352
        record_contents = df.readlines()
1353
        l = record_contents.pop()
1354
        assert len(record_contents) == int(rec[2])
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1355
        if l.decode('utf-8') != 'end %s\n' % version_id:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1356
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
1357
                        % (l, version_id))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1358
        df.close()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1359
        return record_contents, rec[3]
1360
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1361
    def read_records_iter_raw(self, records):
1362
        """Read text records from data file and yield raw data.
1363
1364
        This unpacks enough of the text record to validate the id is
1365
        as expected but thats all.
1366
1367
        It will actively recompress currently cached records on the
1368
        basis that that is cheaper than I/O activity.
1369
        """
1370
        needed_records = []
1371
        for version_id, pos, size in records:
1372
            if version_id not in self._records:
1373
                needed_records.append((version_id, pos, size))
1374
1375
        # setup an iterator of the external records:
1376
        # uses readv so nice and fast we hope.
1377
        if len(needed_records):
1378
            # grab the disk data needed.
1379
            raw_records = self._transport.readv(self._filename,
1380
                [(pos, size) for version_id, pos, size in needed_records])
1381
1382
        for version_id, pos, size in records:
1383
            if version_id in self._records:
1384
                # compress a new version
1385
                size, sio = self._record_to_data(version_id,
1386
                                                 self._records[version_id][0],
1387
                                                 self._records[version_id][1])
1388
                yield version_id, sio.getvalue()
1389
            else:
1390
                pos, data = raw_records.next()
1391
                # validate the header
1392
                df, rec = self._parse_record_header(version_id, data)
1393
                df.close()
1394
                yield version_id, data
1395
1396
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1397
    def read_records_iter(self, records):
1398
        """Read text records from data file and yield result.
1399
1400
        Each passed record is a tuple of (version_id, pos, len) and
1401
        will be read in the given order.  Yields (version_id,
1402
        contents, digest).
1403
        """
1628.1.2 by Robert Collins
More knit micro-optimisations.
1404
        # profiling notes:
1405
        # 60890  calls for 4168 extractions in 5045, 683 internal.
1406
        # 4168   calls to readv              in 1411
1407
        # 4168   calls to parse_record       in 2880
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1408
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1409
        needed_records = []
1410
        for version_id, pos, size in records:
1411
            if version_id not in self._records:
1412
                needed_records.append((version_id, pos, size))
1413
1414
        if len(needed_records):
1415
            # We take it that the transport optimizes the fetching as good
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1416
            # as possible (ie, reads continuous ranges.)
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1417
            response = self._transport.readv(self._filename,
1418
                [(pos, size) for version_id, pos, size in needed_records])
1419
1594.3.5 by Robert Collins
Bugfix knit caching implementation.
1420
            for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1421
                content, digest = self._parse_record(record_id, data)
1422
                self._records[record_id] = (digest, content)
1423
    
1424
        for version_id, pos, size in records:
1628.1.2 by Robert Collins
More knit micro-optimisations.
1425
            yield version_id, list(self._records[version_id][1]), self._records[version_id][0]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1426
1427
    def read_records(self, records):
1428
        """Read records into a dictionary."""
1429
        components = {}
1430
        for record_id, content, digest in self.read_records_iter(records):
1431
            components[record_id] = (content, digest)
1432
        return components
1433
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1434
1435
class InterKnit(InterVersionedFile):
1436
    """Optimised code paths for knit to knit operations."""
1437
    
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
1438
    _matching_file_from_factory = KnitVersionedFile
1439
    _matching_file_to_factory = KnitVersionedFile
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1440
    
1441
    @staticmethod
1442
    def is_compatible(source, target):
1443
        """Be compatible with knits.  """
1444
        try:
1445
            return (isinstance(source, KnitVersionedFile) and
1446
                    isinstance(target, KnitVersionedFile))
1447
        except AttributeError:
1448
            return False
1449
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1450
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1451
        """See InterVersionedFile.join."""
1452
        assert isinstance(self.source, KnitVersionedFile)
1453
        assert isinstance(self.target, KnitVersionedFile)
1454
1684.3.2 by Robert Collins
Factor out version_ids-to-join selection in InterVersionedfile.
1455
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1456
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1457
        if not version_ids:
1458
            return 0
1459
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1460
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1461
        try:
1462
            version_ids = list(version_ids)
1463
            if None in version_ids:
1464
                version_ids.remove(None)
1465
    
1466
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
1467
            this_versions = set(self.target._index.get_versions())
1468
            needed_versions = self.source_ancestry - this_versions
1469
            cross_check_versions = self.source_ancestry.intersection(this_versions)
1470
            mismatched_versions = set()
1471
            for version in cross_check_versions:
1472
                # scan to include needed parents.
1473
                n1 = set(self.target.get_parents_with_ghosts(version))
1474
                n2 = set(self.source.get_parents_with_ghosts(version))
1475
                if n1 != n2:
1476
                    # FIXME TEST this check for cycles being introduced works
1477
                    # the logic is we have a cycle if in our graph we are an
1478
                    # ancestor of any of the n2 revisions.
1479
                    for parent in n2:
1480
                        if parent in n1:
1481
                            # safe
1482
                            continue
1483
                        else:
1484
                            parent_ancestors = self.source.get_ancestry(parent)
1485
                            if version in parent_ancestors:
1486
                                raise errors.GraphCycleError([parent, version])
1487
                    # ensure this parent will be available later.
1488
                    new_parents = n2.difference(n1)
1489
                    needed_versions.update(new_parents.difference(this_versions))
1490
                    mismatched_versions.add(version)
1491
    
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
1492
            if not needed_versions and not mismatched_versions:
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1493
                return 0
1494
            full_list = topo_sort(self.source.get_graph())
1495
    
1496
            version_list = [i for i in full_list if (not self.target.has_version(i)
1497
                            and i in needed_versions)]
1498
    
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1499
            # plan the join:
1500
            copy_queue = []
1501
            copy_queue_records = []
1502
            copy_set = set()
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1503
            for version_id in version_list:
1504
                options = self.source._index.get_options(version_id)
1505
                parents = self.source._index.get_parents_with_ghosts(version_id)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1506
                # check that its will be a consistent copy:
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1507
                for parent in parents:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1508
                    # if source has the parent, we must :
1509
                    # * already have it or
1510
                    # * have it scheduled already
1759.2.2 by Jelmer Vernooij
Revert some of my spelling fixes and fix some typos after review by Aaron.
1511
                    # otherwise we don't care
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1512
                    assert (self.target.has_version(parent) or
1513
                            parent in copy_set or
1514
                            not self.source.has_version(parent))
1515
                data_pos, data_size = self.source._index.get_position(version_id)
1516
                copy_queue_records.append((version_id, data_pos, data_size))
1517
                copy_queue.append((version_id, options, parents))
1518
                copy_set.add(version_id)
1519
1520
            # data suck the join:
1521
            count = 0
1522
            total = len(version_list)
1692.2.1 by Robert Collins
Fix knit based push to only perform 2 appends to the target, rather that 2*new-versions.
1523
            raw_datum = []
1524
            raw_records = []
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1525
            for (version_id, raw_data), \
1526
                (version_id2, options, parents) in \
1527
                izip(self.source._data.read_records_iter_raw(copy_queue_records),
1528
                     copy_queue):
1529
                assert version_id == version_id2, 'logic error, inconsistent results'
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1530
                count = count + 1
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1531
                pb.update("Joining knit", count, total)
1692.2.1 by Robert Collins
Fix knit based push to only perform 2 appends to the target, rather that 2*new-versions.
1532
                raw_records.append((version_id, options, parents, len(raw_data)))
1533
                raw_datum.append(raw_data)
1534
            self.target._add_raw_records(raw_records, ''.join(raw_datum))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1535
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1536
            for version in mismatched_versions:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1537
                # FIXME RBC 20060309 is this needed?
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1538
                n1 = set(self.target.get_parents_with_ghosts(version))
1539
                n2 = set(self.source.get_parents_with_ghosts(version))
1540
                # write a combined record to our history preserving the current 
1541
                # parents as first in the list
1542
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1543
                self.target.fix_parents(version, new_parents)
1544
            return count
1545
        finally:
1546
            pb.finished()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1547
1548
1549
InterVersionedFile.register_optimiser(InterKnit)
1596.2.24 by Robert Collins
Gzipfile was slightly slower than ideal.
1550
1551
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
1552
class WeaveToKnit(InterVersionedFile):
1553
    """Optimised code paths for weave to knit operations."""
1554
    
1555
    _matching_file_from_factory = bzrlib.weave.WeaveFile
1556
    _matching_file_to_factory = KnitVersionedFile
1557
    
1558
    @staticmethod
1559
    def is_compatible(source, target):
1560
        """Be compatible with weaves to knits."""
1561
        try:
1562
            return (isinstance(source, bzrlib.weave.Weave) and
1563
                    isinstance(target, KnitVersionedFile))
1564
        except AttributeError:
1565
            return False
1566
1567
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1568
        """See InterVersionedFile.join."""
1569
        assert isinstance(self.source, bzrlib.weave.Weave)
1570
        assert isinstance(self.target, KnitVersionedFile)
1571
1572
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1573
1574
        if not version_ids:
1575
            return 0
1576
1577
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1578
        try:
1579
            version_ids = list(version_ids)
1580
    
1581
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
1582
            this_versions = set(self.target._index.get_versions())
1583
            needed_versions = self.source_ancestry - this_versions
1584
            cross_check_versions = self.source_ancestry.intersection(this_versions)
1585
            mismatched_versions = set()
1586
            for version in cross_check_versions:
1587
                # scan to include needed parents.
1588
                n1 = set(self.target.get_parents_with_ghosts(version))
1589
                n2 = set(self.source.get_parents(version))
1590
                # if all of n2's parents are in n1, then its fine.
1591
                if n2.difference(n1):
1592
                    # FIXME TEST this check for cycles being introduced works
1593
                    # the logic is we have a cycle if in our graph we are an
1594
                    # ancestor of any of the n2 revisions.
1595
                    for parent in n2:
1596
                        if parent in n1:
1597
                            # safe
1598
                            continue
1599
                        else:
1600
                            parent_ancestors = self.source.get_ancestry(parent)
1601
                            if version in parent_ancestors:
1602
                                raise errors.GraphCycleError([parent, version])
1603
                    # ensure this parent will be available later.
1604
                    new_parents = n2.difference(n1)
1605
                    needed_versions.update(new_parents.difference(this_versions))
1606
                    mismatched_versions.add(version)
1607
    
1608
            if not needed_versions and not mismatched_versions:
1609
                return 0
1610
            full_list = topo_sort(self.source.get_graph())
1611
    
1612
            version_list = [i for i in full_list if (not self.target.has_version(i)
1613
                            and i in needed_versions)]
1614
    
1615
            # do the join:
1616
            count = 0
1617
            total = len(version_list)
1618
            for version_id in version_list:
1619
                pb.update("Converting to knit", count, total)
1620
                parents = self.source.get_parents(version_id)
1621
                # check that its will be a consistent copy:
1622
                for parent in parents:
1623
                    # if source has the parent, we must already have it
1624
                    assert (self.target.has_version(parent))
1625
                self.target.add_lines(
1626
                    version_id, parents, self.source.get_lines(version_id))
1627
                count = count + 1
1628
1629
            for version in mismatched_versions:
1630
                # FIXME RBC 20060309 is this needed?
1631
                n1 = set(self.target.get_parents_with_ghosts(version))
1632
                n2 = set(self.source.get_parents(version))
1633
                # write a combined record to our history preserving the current 
1634
                # parents as first in the list
1635
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1636
                self.target.fix_parents(version, new_parents)
1637
            return count
1638
        finally:
1639
            pb.finished()
1640
1641
1642
InterVersionedFile.register_optimiser(WeaveToKnit)
1643
1644
1711.2.11 by John Arbash Meinel
Rename patiencediff.SequenceMatcher => PatienceSequenceMatcher and knit.SequenceMatcher => KnitSequenceMatcher
1645
class KnitSequenceMatcher(difflib.SequenceMatcher):
1596.2.35 by Robert Collins
Subclass SequenceMatcher to get a slightly faster (in our case) find_longest_match routine.
1646
    """Knit tuned sequence matcher.
1647
1648
    This is based on profiling of difflib which indicated some improvements
1649
    for our usage pattern.
1650
    """
1651
1652
    def find_longest_match(self, alo, ahi, blo, bhi):
1653
        """Find longest matching block in a[alo:ahi] and b[blo:bhi].
1654
1655
        If isjunk is not defined:
1656
1657
        Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
1658
            alo <= i <= i+k <= ahi
1659
            blo <= j <= j+k <= bhi
1660
        and for all (i',j',k') meeting those conditions,
1661
            k >= k'
1662
            i <= i'
1663
            and if i == i', j <= j'
1664
1665
        In other words, of all maximal matching blocks, return one that
1666
        starts earliest in a, and of all those maximal matching blocks that
1667
        start earliest in a, return the one that starts earliest in b.
1668
1669
        >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
1670
        >>> s.find_longest_match(0, 5, 0, 9)
1671
        (0, 4, 5)
1672
1673
        If isjunk is defined, first the longest matching block is
1674
        determined as above, but with the additional restriction that no
1675
        junk element appears in the block.  Then that block is extended as
1676
        far as possible by matching (only) junk elements on both sides.  So
1677
        the resulting block never matches on junk except as identical junk
1678
        happens to be adjacent to an "interesting" match.
1679
1680
        Here's the same example as before, but considering blanks to be
1681
        junk.  That prevents " abcd" from matching the " abcd" at the tail
1682
        end of the second sequence directly.  Instead only the "abcd" can
1683
        match, and matches the leftmost "abcd" in the second sequence:
1684
1685
        >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
1686
        >>> s.find_longest_match(0, 5, 0, 9)
1687
        (1, 0, 4)
1688
1689
        If no blocks match, return (alo, blo, 0).
1690
1691
        >>> s = SequenceMatcher(None, "ab", "c")
1692
        >>> s.find_longest_match(0, 2, 0, 1)
1693
        (0, 0, 0)
1694
        """
1695
1696
        # CAUTION:  stripping common prefix or suffix would be incorrect.
1697
        # E.g.,
1698
        #    ab
1699
        #    acab
1700
        # Longest matching block is "ab", but if common prefix is
1701
        # stripped, it's "a" (tied with "b").  UNIX(tm) diff does so
1702
        # strip, so ends up claiming that ab is changed to acab by
1703
        # inserting "ca" in the middle.  That's minimal but unintuitive:
1704
        # "it's obvious" that someone inserted "ac" at the front.
1705
        # Windiff ends up at the same place as diff, but by pairing up
1706
        # the unique 'b's and then matching the first two 'a's.
1707
1708
        a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
1709
        besti, bestj, bestsize = alo, blo, 0
1710
        # find longest junk-free match
1711
        # during an iteration of the loop, j2len[j] = length of longest
1712
        # junk-free match ending with a[i-1] and b[j]
1713
        j2len = {}
1714
        # nothing = []
1715
        b2jget = b2j.get
1716
        for i in xrange(alo, ahi):
1717
            # look at all instances of a[i] in b; note that because
1718
            # b2j has no junk keys, the loop is skipped if a[i] is junk
1719
            j2lenget = j2len.get
1720
            newj2len = {}
1721
            
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1722
            # changing b2j.get(a[i], nothing) to a try:KeyError pair produced the
1596.2.35 by Robert Collins
Subclass SequenceMatcher to get a slightly faster (in our case) find_longest_match routine.
1723
            # following improvement
1724
            #     704  0   4650.5320   2620.7410   bzrlib.knit:1336(find_longest_match)
1725
            # +326674  0   1655.1210   1655.1210   +<method 'get' of 'dict' objects>
1726
            #  +76519  0    374.6700    374.6700   +<method 'has_key' of 'dict' objects>
1727
            # to 
1728
            #     704  0   3733.2820   2209.6520   bzrlib.knit:1336(find_longest_match)
1729
            #  +211400 0   1147.3520   1147.3520   +<method 'get' of 'dict' objects>
1730
            #  +76519  0    376.2780    376.2780   +<method 'has_key' of 'dict' objects>
1731
1732
            try:
1733
                js = b2j[a[i]]
1734
            except KeyError:
1735
                pass
1736
            else:
1737
                for j in js:
1738
                    # a[i] matches b[j]
1739
                    if j >= blo:
1740
                        if j >= bhi:
1741
                            break
1742
                        k = newj2len[j] = 1 + j2lenget(-1 + j, 0)
1743
                        if k > bestsize:
1744
                            besti, bestj, bestsize = 1 + i-k, 1 + j-k, k
1745
            j2len = newj2len
1746
1747
        # Extend the best by non-junk elements on each end.  In particular,
1748
        # "popular" non-junk elements aren't in b2j, which greatly speeds
1749
        # the inner loop above, but also means "the best" match so far
1750
        # doesn't contain any junk *or* popular non-junk elements.
1751
        while besti > alo and bestj > blo and \
1752
              not isbjunk(b[bestj-1]) and \
1753
              a[besti-1] == b[bestj-1]:
1754
            besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1755
        while besti+bestsize < ahi and bestj+bestsize < bhi and \
1756
              not isbjunk(b[bestj+bestsize]) and \
1757
              a[besti+bestsize] == b[bestj+bestsize]:
1758
            bestsize += 1
1759
1760
        # Now that we have a wholly interesting match (albeit possibly
1761
        # empty!), we may as well suck up the matching junk on each
1762
        # side of it too.  Can't think of a good reason not to, and it
1763
        # saves post-processing the (possibly considerable) expense of
1764
        # figuring out what to do with it.  In the case of an empty
1765
        # interesting match, this is clearly the right thing to do,
1766
        # because no other kind of match is possible in the regions.
1767
        while besti > alo and bestj > blo and \
1768
              isbjunk(b[bestj-1]) and \
1769
              a[besti-1] == b[bestj-1]:
1770
            besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1771
        while besti+bestsize < ahi and bestj+bestsize < bhi and \
1772
              isbjunk(b[bestj+bestsize]) and \
1773
              a[besti+bestsize] == b[bestj+bestsize]:
1774
            bestsize = bestsize + 1
1775
1776
        return besti, bestj, bestsize
1777