/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/knit.py

Utf8 safety in knit indexes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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.
 
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
 
 
55
"""
 
56
 
 
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.
 
62
# move sha1 out of the content so that join is faster at verifying parents
 
63
# record content length ?
 
64
                  
 
65
 
 
66
from copy import copy
 
67
from cStringIO import StringIO
 
68
import difflib
 
69
from difflib import SequenceMatcher
 
70
from gzip import GzipFile
 
71
from itertools import izip
 
72
import os
 
73
 
 
74
 
 
75
import bzrlib
 
76
import bzrlib.errors as errors
 
77
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
 
78
        InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
 
79
        RevisionNotPresent, RevisionAlreadyPresent
 
80
from bzrlib.trace import mutter
 
81
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
 
82
     sha_strings
 
83
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
 
84
from bzrlib.tsort import topo_sort
 
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
 
 
92
# TODO: accomodate binaries, perhaps by storing a byte count
 
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 apply_delta(self, delta):
 
120
        """Apply delta to this content."""
 
121
        offset = 0
 
122
        for start, end, count, lines in delta:
 
123
            self._lines[offset+start:offset+end] = lines
 
124
            offset = offset + (start - end) + count
 
125
 
 
126
    def line_delta_iter(self, new_lines):
 
127
        """Generate line-based delta from new_lines to this content."""
 
128
        new_texts = [text for origin, text in new_lines._lines]
 
129
        old_texts = [text for origin, text in self._lines]
 
130
        s = difflib.SequenceMatcher(None, old_texts, new_texts)
 
131
        for op in s.get_opcodes():
 
132
            if op[0] == 'equal':
 
133
                continue
 
134
            yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
 
135
 
 
136
    def line_delta(self, new_lines):
 
137
        return list(self.line_delta_iter(new_lines))
 
138
 
 
139
    def text(self):
 
140
        return [text for origin, text in self._lines]
 
141
 
 
142
 
 
143
class _KnitFactory(object):
 
144
    """Base factory for creating content objects."""
 
145
 
 
146
    def make(self, lines, version):
 
147
        num_lines = len(lines)
 
148
        return KnitContent(zip([version] * num_lines, lines))
 
149
 
 
150
 
 
151
class KnitAnnotateFactory(_KnitFactory):
 
152
    """Factory for creating annotated Content objects."""
 
153
 
 
154
    annotated = True
 
155
 
 
156
    def parse_fulltext(self, content, version):
 
157
        """Convert fulltext to internal representation
 
158
 
 
159
        fulltext content is of the format
 
160
        revid(utf8) plaintext\n
 
161
        internal representation is of the format:
 
162
        (revid, plaintext)
 
163
        """
 
164
        lines = []
 
165
        for line in content:
 
166
            origin, text = line.split(' ', 1)
 
167
            lines.append((origin.decode('utf-8'), text))
 
168
        return KnitContent(lines)
 
169
 
 
170
    def parse_line_delta_iter(self, lines):
 
171
        """Convert a line based delta into internal representation.
 
172
 
 
173
        line delta is in the form of:
 
174
        intstart intend intcount
 
175
        1..count lines:
 
176
        revid(utf8) newline\n
 
177
        internal represnetation is
 
178
        (start, end, count, [1..count tuples (revid, newline)])
 
179
        """
 
180
        while lines:
 
181
            header = lines.pop(0)
 
182
            start, end, c = [int(n) for n in header.split(',')]
 
183
            contents = []
 
184
            for i in range(c):
 
185
                origin, text = lines.pop(0).split(' ', 1)
 
186
                contents.append((origin.decode('utf-8'), text))
 
187
            yield start, end, c, contents
 
188
 
 
189
    def parse_line_delta(self, lines, version):
 
190
        return list(self.parse_line_delta_iter(lines))
 
191
 
 
192
    def lower_fulltext(self, content):
 
193
        """convert a fulltext content record into a serializable form.
 
194
 
 
195
        see parse_fulltext which this inverts.
 
196
        """
 
197
        return ['%s %s' % (o.encode('utf-8'), t) for o, t in content._lines]
 
198
 
 
199
    def lower_line_delta(self, delta):
 
200
        """convert a delta into a serializable form.
 
201
 
 
202
        See parse_line_delta_iter which this inverts.
 
203
        """
 
204
        out = []
 
205
        for start, end, c, lines in delta:
 
206
            out.append('%d,%d,%d\n' % (start, end, c))
 
207
            for origin, text in lines:
 
208
                out.append('%s %s' % (origin.encode('utf-8'), text))
 
209
        return out
 
210
 
 
211
 
 
212
class KnitPlainFactory(_KnitFactory):
 
213
    """Factory for creating plain Content objects."""
 
214
 
 
215
    annotated = False
 
216
 
 
217
    def parse_fulltext(self, content, version):
 
218
        """This parses an unannotated fulltext.
 
219
 
 
220
        Note that this is not a noop - the internal representation
 
221
        has (versionid, line) - its just a constant versionid.
 
222
        """
 
223
        return self.make(content, version)
 
224
 
 
225
    def parse_line_delta_iter(self, lines, version):
 
226
        while lines:
 
227
            header = lines.pop(0)
 
228
            start, end, c = [int(n) for n in header.split(',')]
 
229
            yield start, end, c, zip([version] * c, lines[:c])
 
230
            del lines[:c]
 
231
 
 
232
    def parse_line_delta(self, lines, version):
 
233
        return list(self.parse_line_delta_iter(lines, version))
 
234
    
 
235
    def lower_fulltext(self, content):
 
236
        return content.text()
 
237
 
 
238
    def lower_line_delta(self, delta):
 
239
        out = []
 
240
        for start, end, c, lines in delta:
 
241
            out.append('%d,%d,%d\n' % (start, end, c))
 
242
            out.extend([text for origin, text in lines])
 
243
        return out
 
244
 
 
245
 
 
246
def make_empty_knit(transport, relpath):
 
247
    """Construct a empty knit at the specified location."""
 
248
    k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
 
249
    k._data._open_file()
 
250
 
 
251
 
 
252
class KnitVersionedFile(VersionedFile):
 
253
    """Weave-like structure with faster random access.
 
254
 
 
255
    A knit stores a number of texts and a summary of the relationships
 
256
    between them.  Texts are identified by a string version-id.  Texts
 
257
    are normally stored and retrieved as a series of lines, but can
 
258
    also be passed as single strings.
 
259
 
 
260
    Lines are stored with the trailing newline (if any) included, to
 
261
    avoid special cases for files with no final newline.  Lines are
 
262
    composed of 8-bit characters, not unicode.  The combination of
 
263
    these approaches should mean any 'binary' file can be safely
 
264
    stored and retrieved.
 
265
    """
 
266
 
 
267
    def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
 
268
                 basis_knit=None, delta=True, create=False):
 
269
        """Construct a knit at location specified by relpath.
 
270
        
 
271
        :param create: If not True, only open an existing knit.
 
272
        """
 
273
        if access_mode is None:
 
274
            access_mode = 'w'
 
275
        super(KnitVersionedFile, self).__init__(access_mode)
 
276
        assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
 
277
        assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
 
278
            type(basis_knit)
 
279
 
 
280
        self.transport = transport
 
281
        self.filename = relpath
 
282
        self.basis_knit = basis_knit
 
283
        self.factory = factory or KnitAnnotateFactory()
 
284
        self.writable = (access_mode == 'w')
 
285
        self.delta = delta
 
286
 
 
287
        self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
 
288
            access_mode, create=create)
 
289
        self._data = _KnitData(transport, relpath + DATA_SUFFIX,
 
290
            access_mode, create=not len(self.versions()))
 
291
 
 
292
    def clear_cache(self):
 
293
        """Clear the data cache only."""
 
294
        self._data.clear_cache()
 
295
 
 
296
    def copy_to(self, name, transport):
 
297
        """See VersionedFile.copy_to()."""
 
298
        # copy the current index to a temp index to avoid racing with local
 
299
        # writes
 
300
        transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
 
301
        # copy the data file
 
302
        transport.put(name + DATA_SUFFIX, self._data._open_file())
 
303
        # rename the copied index into place
 
304
        transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
 
305
 
 
306
    def create_empty(self, name, transport, mode=None):
 
307
        return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
 
308
    
 
309
    def _fix_parents(self, version, new_parents):
 
310
        """Fix the parents list for version.
 
311
        
 
312
        This is done by appending a new version to the index
 
313
        with identical data except for the parents list.
 
314
        the parents list must be a superset of the current
 
315
        list.
 
316
        """
 
317
        current_values = self._index._cache[version]
 
318
        assert set(current_values[4]).difference(set(new_parents)) == set()
 
319
        self._index.add_version(version,
 
320
                                current_values[1], 
 
321
                                current_values[2],
 
322
                                current_values[3],
 
323
                                new_parents)
 
324
 
 
325
    def get_graph_with_ghosts(self):
 
326
        """See VersionedFile.get_graph_with_ghosts()."""
 
327
        graph_items = self._index.get_graph()
 
328
        return dict(graph_items)
 
329
 
 
330
    @staticmethod
 
331
    def get_suffixes():
 
332
        """See VersionedFile.get_suffixes()."""
 
333
        return [DATA_SUFFIX, INDEX_SUFFIX]
 
334
 
 
335
    def has_ghost(self, version_id):
 
336
        """True if there is a ghost reference in the file to version_id."""
 
337
        # maybe we have it
 
338
        if self.has_version(version_id):
 
339
            return False
 
340
        # optimisable if needed by memoising the _ghosts set.
 
341
        items = self._index.get_graph()
 
342
        for node, parents in items:
 
343
            for parent in parents:
 
344
                if parent not in self._index._cache:
 
345
                    if parent == version_id:
 
346
                        return True
 
347
        return False
 
348
 
 
349
    def versions(self):
 
350
        """See VersionedFile.versions."""
 
351
        return self._index.get_versions()
 
352
 
 
353
    def has_version(self, version_id):
 
354
        """See VersionedFile.has_version."""
 
355
        return self._index.has_version(version_id)
 
356
 
 
357
    __contains__ = has_version
 
358
 
 
359
    def _merge_annotations(self, content, parents):
 
360
        """Merge annotations for content.  This is done by comparing
 
361
        the annotations based on changed to the text."""
 
362
        for parent_id in parents:
 
363
            merge_content = self._get_content(parent_id)
 
364
            seq = SequenceMatcher(None, merge_content.text(), content.text())
 
365
            for i, j, n in seq.get_matching_blocks():
 
366
                if n == 0:
 
367
                    continue
 
368
                content._lines[j:j+n] = merge_content._lines[i:i+n]
 
369
 
 
370
    def _get_components(self, version_id):
 
371
        """Return a list of (version_id, method, data) tuples that
 
372
        makes up version specified by version_id of the knit.
 
373
 
 
374
        The components should be applied in the order of the returned
 
375
        list.
 
376
 
 
377
        The basis knit will be used to the largest extent possible
 
378
        since it is assumed that accesses to it is faster.
 
379
        """
 
380
        # needed_revisions holds a list of (method, version_id) of
 
381
        # versions that is needed to be fetched to construct the final
 
382
        # version of the file.
 
383
        #
 
384
        # basis_revisions is a list of versions that needs to be
 
385
        # fetched but exists in the basis knit.
 
386
 
 
387
        basis = self.basis_knit
 
388
        needed_versions = []
 
389
        basis_versions = []
 
390
        cursor = version_id
 
391
 
 
392
        while 1:
 
393
            picked_knit = self
 
394
            if basis and basis._index.has_version(cursor):
 
395
                picked_knit = basis
 
396
                basis_versions.append(cursor)
 
397
            method = picked_knit._index.get_method(cursor)
 
398
            needed_versions.append((method, cursor))
 
399
            if method == 'fulltext':
 
400
                break
 
401
            cursor = picked_knit.get_parents(cursor)[0]
 
402
 
 
403
        components = {}
 
404
        if basis_versions:
 
405
            records = []
 
406
            for comp_id in basis_versions:
 
407
                data_pos, data_size = basis._index.get_data_position(comp_id)
 
408
                records.append((piece_id, data_pos, data_size))
 
409
            components.update(basis._data.read_records(records))
 
410
 
 
411
        records = []
 
412
        for comp_id in [vid for method, vid in needed_versions
 
413
                        if vid not in basis_versions]:
 
414
            data_pos, data_size = self._index.get_position(comp_id)
 
415
            records.append((comp_id, data_pos, data_size))
 
416
        components.update(self._data.read_records(records))
 
417
 
 
418
        # get_data_records returns a mapping with the version id as
 
419
        # index and the value as data.  The order the components need
 
420
        # to be applied is held by needed_versions (reversed).
 
421
        out = []
 
422
        for method, comp_id in reversed(needed_versions):
 
423
            out.append((comp_id, method, components[comp_id]))
 
424
 
 
425
        return out
 
426
 
 
427
    def _get_content(self, version_id):
 
428
        """Returns a content object that makes up the specified
 
429
        version."""
 
430
        if not self.has_version(version_id):
 
431
            raise RevisionNotPresent(version_id, self.filename)
 
432
 
 
433
        if self.basis_knit and version_id in self.basis_knit:
 
434
            return self.basis_knit._get_content(version_id)
 
435
 
 
436
        content = None
 
437
        components = self._get_components(version_id)
 
438
        for component_id, method, (data, digest) in components:
 
439
            version_idx = self._index.lookup(component_id)
 
440
            if method == 'fulltext':
 
441
                assert content is None
 
442
                content = self.factory.parse_fulltext(data, version_idx)
 
443
            elif method == 'line-delta':
 
444
                delta = self.factory.parse_line_delta(data, version_idx)
 
445
                content.apply_delta(delta)
 
446
 
 
447
        if 'no-eol' in self._index.get_options(version_id):
 
448
            line = content._lines[-1][1].rstrip('\n')
 
449
            content._lines[-1] = (content._lines[-1][0], line)
 
450
 
 
451
        if sha_strings(content.text()) != digest:
 
452
            raise KnitCorrupt(self.filename, 'sha-1 does not match')
 
453
 
 
454
        return content
 
455
 
 
456
    def _check_versions_present(self, version_ids):
 
457
        """Check that all specified versions are present."""
 
458
        version_ids = set(version_ids)
 
459
        for r in list(version_ids):
 
460
            if self._index.has_version(r):
 
461
                version_ids.remove(r)
 
462
        if version_ids:
 
463
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
464
 
 
465
    def _add_lines_with_ghosts(self, version_id, parents, lines):
 
466
        """See VersionedFile.add_lines_with_ghosts()."""
 
467
        self._check_add(version_id, lines)
 
468
        return self._add(version_id, lines[:], parents, self.delta)
 
469
 
 
470
    def _add_lines(self, version_id, parents, lines):
 
471
        """See VersionedFile.add_lines."""
 
472
        self._check_add(version_id, lines)
 
473
        self._check_versions_present(parents)
 
474
        return self._add(version_id, lines[:], parents, self.delta)
 
475
 
 
476
    def _check_add(self, version_id, lines):
 
477
        """check that version_id and lines are safe to add."""
 
478
        assert self.writable, "knit is not opened for write"
 
479
        ### FIXME escape. RBC 20060228
 
480
        if contains_whitespace(version_id):
 
481
            raise InvalidRevisionId(version_id)
 
482
        if self.has_version(version_id):
 
483
            raise RevisionAlreadyPresent(version_id, self.filename)
 
484
 
 
485
        if False or __debug__:
 
486
            for l in lines:
 
487
                assert '\n' not in l[:-1]
 
488
 
 
489
    def _add(self, version_id, lines, parents, delta):
 
490
        """Add a set of lines on top of version specified by parents.
 
491
 
 
492
        If delta is true, compress the text as a line-delta against
 
493
        the first parent.
 
494
 
 
495
        Any versions not present will be converted into ghosts.
 
496
        """
 
497
        ghostless_parents = []
 
498
        ghosts = []
 
499
        for parent in parents:
 
500
            if not self.has_version(parent):
 
501
                ghosts.append(parent)
 
502
            else:
 
503
                ghostless_parents.append(parent)
 
504
 
 
505
        if delta and not len(ghostless_parents):
 
506
            delta = False
 
507
 
 
508
        digest = sha_strings(lines)
 
509
        options = []
 
510
        if lines:
 
511
            if lines[-1][-1] != '\n':
 
512
                options.append('no-eol')
 
513
                lines[-1] = lines[-1] + '\n'
 
514
 
 
515
        lines = self.factory.make(lines, version_id) #len(self._index))
 
516
        if self.factory.annotated and len(ghostless_parents) > 0:
 
517
            # Merge annotations from parent texts if so is needed.
 
518
            self._merge_annotations(lines, ghostless_parents)
 
519
 
 
520
        if len(ghostless_parents) and delta:
 
521
            # To speed the extract of texts the delta chain is limited
 
522
            # to a fixed number of deltas.  This should minimize both
 
523
            # I/O and the time spend applying deltas.
 
524
            count = 0
 
525
            delta_parents = ghostless_parents
 
526
            while count < 25:
 
527
                parent = delta_parents[0]
 
528
                method = self._index.get_method(parent)
 
529
                if method == 'fulltext':
 
530
                    break
 
531
                delta_parents = self._index.get_parents(parent)
 
532
                count = count + 1
 
533
            if method == 'line-delta':
 
534
                delta = False
 
535
 
 
536
        if delta:
 
537
            options.append('line-delta')
 
538
            content = self._get_content(ghostless_parents[0])
 
539
            delta_hunks = content.line_delta(lines)
 
540
            store_lines = self.factory.lower_line_delta(delta_hunks)
 
541
        else:
 
542
            options.append('fulltext')
 
543
            store_lines = self.factory.lower_fulltext(lines)
 
544
 
 
545
        where, size = self._data.add_record(version_id, digest, store_lines)
 
546
        self._index.add_version(version_id, options, where, size, parents)
 
547
 
 
548
    def check(self, progress_bar=None):
 
549
        """See VersionedFile.check()."""
 
550
 
 
551
    def _clone_text(self, new_version_id, old_version_id, parents):
 
552
        """See VersionedFile.clone_text()."""
 
553
        # FIXME RBC 20060228 make fast by only inserting an index with null delta.
 
554
        self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
 
555
 
 
556
    def get_lines(self, version_id):
 
557
        """See VersionedFile.get_lines()."""
 
558
        return self._get_content(version_id).text()
 
559
 
 
560
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
 
561
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
 
562
        if version_ids is None:
 
563
            version_ids = self.versions()
 
564
        # we dont care about inclusions, the caller cares.
 
565
        # but we need to setup a list of records to visit.
 
566
        # we need version_id, position, length
 
567
        version_id_records = []
 
568
        requested_versions = list(version_ids)
 
569
        # filter for available versions
 
570
        for version_id in requested_versions:
 
571
            if not self.has_version(version_id):
 
572
                raise RevisionNotPresent(version_id, self.filename)
 
573
        # get a in-component-order queue:
 
574
        version_ids = []
 
575
        for version_id in self.versions():
 
576
            if version_id in requested_versions:
 
577
                version_ids.append(version_id)
 
578
                data_pos, length = self._index.get_position(version_id)
 
579
                version_id_records.append((version_id, data_pos, length))
 
580
 
 
581
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
582
        count = 0
 
583
        total = len(version_id_records)
 
584
        try:
 
585
            pb.update('Walking content.', count, total)
 
586
            for version_id, data, sha_value in \
 
587
                self._data.read_records_iter(version_id_records):
 
588
                pb.update('Walking content.', count, total)
 
589
                method = self._index.get_method(version_id)
 
590
                version_idx = self._index.lookup(version_id)
 
591
                assert method in ('fulltext', 'line-delta')
 
592
                if method == 'fulltext':
 
593
                    content = self.factory.parse_fulltext(data, version_idx)
 
594
                    for line in content.text():
 
595
                        yield line
 
596
                else:
 
597
                    delta = self.factory.parse_line_delta(data, version_idx)
 
598
                    for start, end, count, lines in delta:
 
599
                        for origin, line in lines:
 
600
                            yield line
 
601
                count +=1
 
602
            pb.update('Walking content.', total, total)
 
603
            pb.finished()
 
604
        except:
 
605
            pb.update('Walking content.', total, total)
 
606
            pb.finished()
 
607
            raise
 
608
        
 
609
    def num_versions(self):
 
610
        """See VersionedFile.num_versions()."""
 
611
        return self._index.num_versions()
 
612
 
 
613
    __len__ = num_versions
 
614
 
 
615
    def annotate_iter(self, version_id):
 
616
        """See VersionedFile.annotate_iter."""
 
617
        content = self._get_content(version_id)
 
618
        for origin, text in content.annotate_iter():
 
619
            yield origin, text
 
620
 
 
621
    def get_parents(self, version_id):
 
622
        """See VersionedFile.get_parents."""
 
623
        self._check_versions_present([version_id])
 
624
        return list(self._index.get_parents(version_id))
 
625
 
 
626
    def get_parents_with_ghosts(self, version_id):
 
627
        """See VersionedFile.get_parents."""
 
628
        self._check_versions_present([version_id])
 
629
        return list(self._index.get_parents_with_ghosts(version_id))
 
630
 
 
631
    def get_ancestry(self, versions):
 
632
        """See VersionedFile.get_ancestry."""
 
633
        if isinstance(versions, basestring):
 
634
            versions = [versions]
 
635
        if not versions:
 
636
            return []
 
637
        self._check_versions_present(versions)
 
638
        return self._index.get_ancestry(versions)
 
639
 
 
640
    def get_ancestry_with_ghosts(self, versions):
 
641
        """See VersionedFile.get_ancestry_with_ghosts."""
 
642
        if isinstance(versions, basestring):
 
643
            versions = [versions]
 
644
        if not versions:
 
645
            return []
 
646
        self._check_versions_present(versions)
 
647
        return self._index.get_ancestry_with_ghosts(versions)
 
648
 
 
649
    #@deprecated_method(zero_eight)
 
650
    def walk(self, version_ids):
 
651
        """See VersionedFile.walk."""
 
652
        # We take the short path here, and extract all relevant texts
 
653
        # and put them in a weave and let that do all the work.  Far
 
654
        # from optimal, but is much simpler.
 
655
        # FIXME RB 20060228 this really is inefficient!
 
656
        from bzrlib.weave import Weave
 
657
 
 
658
        w = Weave(self.filename)
 
659
        ancestry = self.get_ancestry(version_ids)
 
660
        sorted_graph = topo_sort(self._index.get_graph())
 
661
        version_list = [vid for vid in sorted_graph if vid in ancestry]
 
662
        
 
663
        for version_id in version_list:
 
664
            lines = self.get_lines(version_id)
 
665
            w.add_lines(version_id, self.get_parents(version_id), lines)
 
666
 
 
667
        for lineno, insert_id, dset, line in w.walk(version_ids):
 
668
            yield lineno, insert_id, dset, line
 
669
 
 
670
 
 
671
class _KnitComponentFile(object):
 
672
    """One of the files used to implement a knit database"""
 
673
 
 
674
    def __init__(self, transport, filename, mode):
 
675
        self._transport = transport
 
676
        self._filename = filename
 
677
        self._mode = mode
 
678
 
 
679
    def write_header(self):
 
680
        old_len = self._transport.append(self._filename, StringIO(self.HEADER))
 
681
        if old_len != 0:
 
682
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
 
683
 
 
684
    def check_header(self, fp):
 
685
        line = fp.read(len(self.HEADER))
 
686
        if line != self.HEADER:
 
687
            raise KnitHeaderError(badline=line)
 
688
 
 
689
    def commit(self):
 
690
        """Commit is a nop."""
 
691
 
 
692
    def __repr__(self):
 
693
        return '%s(%s)' % (self.__class__.__name__, self._filename)
 
694
 
 
695
 
 
696
class _KnitIndex(_KnitComponentFile):
 
697
    """Manages knit index file.
 
698
 
 
699
    The index is already kept in memory and read on startup, to enable
 
700
    fast lookups of revision information.  The cursor of the index
 
701
    file is always pointing to the end, making it easy to append
 
702
    entries.
 
703
 
 
704
    _cache is a cache for fast mapping from version id to a Index
 
705
    object.
 
706
 
 
707
    _history is a cache for fast mapping from indexes to version ids.
 
708
 
 
709
    The index data format is dictionary compressed when it comes to
 
710
    parent references; a index entry may only have parents that with a
 
711
    lover index number.  As a result, the index is topological sorted.
 
712
 
 
713
    Duplicate entries may be written to the index for a single version id
 
714
    if this is done then the latter one completely replaces the former:
 
715
    this allows updates to correct version and parent information. 
 
716
    Note that the two entries may share the delta, and that successive
 
717
    annotations and references MUST point to the first entry.
 
718
    """
 
719
 
 
720
    HEADER = "# bzr knit index 7\n"
 
721
 
 
722
    def _cache_version(self, version_id, options, pos, size, parents):
 
723
        val = (version_id, options, pos, size, parents)
 
724
        self._cache[version_id] = val
 
725
        if not version_id in self._history:
 
726
            self._history.append(version_id)
 
727
 
 
728
    def _iter_index(self, fp):
 
729
        l = fp.readline()
 
730
        while l != '':
 
731
            yield l.split()
 
732
            l = fp.readline()
 
733
        #lines = fp.read()
 
734
        #for l in lines.splitlines(False):
 
735
        #    yield l.split()
 
736
 
 
737
    def __init__(self, transport, filename, mode, create=False):
 
738
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
739
        self._cache = {}
 
740
        # position in _history is the 'official' index for a revision
 
741
        # but the values may have come from a newer entry.
 
742
        # so - wc -l of a knit index is != the number of uniqe names
 
743
        # in the weave.
 
744
        self._history = []
 
745
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
746
        try:
 
747
            count = 0
 
748
            total = 1
 
749
            try:
 
750
                pb.update('read knit index', count, total)
 
751
                fp = self._transport.get(self._filename)
 
752
                self.check_header(fp)
 
753
                for rec in self._iter_index(fp):
 
754
                    count += 1
 
755
                    total += 1
 
756
                    pb.update('read knit index', count, total)
 
757
                    parents = self._parse_parents(rec[4:])
 
758
                    self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
 
759
                        parents)
 
760
            except NoSuchFile, e:
 
761
                if mode != 'w' or not create:
 
762
                    raise
 
763
                self.write_header()
 
764
        finally:
 
765
            pb.update('read knit index', total, total)
 
766
            pb.finished()
 
767
 
 
768
    def _parse_parents(self, compressed_parents):
 
769
        """convert a list of string parent values into version ids.
 
770
 
 
771
        ints are looked up in the index.
 
772
        .FOO values are ghosts and converted in to FOO.
 
773
        """
 
774
        result = []
 
775
        for value in compressed_parents:
 
776
            if value.startswith('.'):
 
777
                result.append(value[1:])
 
778
            else:
 
779
                assert isinstance(value, str)
 
780
                try:
 
781
                    result.append(self._history[int(value)])
 
782
                except ValueError:
 
783
                    import pdb;pdb.set_trace()
 
784
        return result
 
785
 
 
786
    def get_graph(self):
 
787
        graph = []
 
788
        for version_id, index in self._cache.iteritems():
 
789
            graph.append((version_id, index[4]))
 
790
        return graph
 
791
 
 
792
    def get_ancestry(self, versions):
 
793
        """See VersionedFile.get_ancestry."""
 
794
        # get a graph of all the mentioned versions:
 
795
        graph = {}
 
796
        pending = set(versions)
 
797
        while len(pending):
 
798
            version = pending.pop()
 
799
            parents = self._cache[version][4]
 
800
            # got the parents ok
 
801
            # trim ghosts
 
802
            parents = [parent for parent in parents if parent in self._cache]
 
803
            for parent in parents:
 
804
                # if not completed and not a ghost
 
805
                if parent not in graph:
 
806
                    pending.add(parent)
 
807
            graph[version] = parents
 
808
        return topo_sort(graph.items())
 
809
 
 
810
    def get_ancestry_with_ghosts(self, versions):
 
811
        """See VersionedFile.get_ancestry_with_ghosts."""
 
812
        # get a graph of all the mentioned versions:
 
813
        graph = {}
 
814
        pending = set(versions)
 
815
        while len(pending):
 
816
            version = pending.pop()
 
817
            try:
 
818
                parents = self._cache[version][4]
 
819
            except KeyError:
 
820
                # ghost, fake it
 
821
                graph[version] = []
 
822
                pass
 
823
            else:
 
824
                # got the parents ok
 
825
                for parent in parents:
 
826
                    if parent not in graph:
 
827
                        pending.add(parent)
 
828
                graph[version] = parents
 
829
        return topo_sort(graph.items())
 
830
 
 
831
    def num_versions(self):
 
832
        return len(self._history)
 
833
 
 
834
    __len__ = num_versions
 
835
 
 
836
    def get_versions(self):
 
837
        return self._history
 
838
 
 
839
    def idx_to_name(self, idx):
 
840
        return self._history[idx]
 
841
 
 
842
    def lookup(self, version_id):
 
843
        assert version_id in self._cache
 
844
        return self._history.index(version_id)
 
845
 
 
846
    def _version_list_to_index(self, versions):
 
847
        result_list = []
 
848
        for version in versions:
 
849
            if version in self._cache:
 
850
                result_list.append(str(self._history.index(version)))
 
851
            else:
 
852
                result_list.append('.' + version.encode('utf-8'))
 
853
        return ' '.join(result_list)
 
854
 
 
855
    def add_version(self, version_id, options, pos, size, parents):
 
856
        """Add a version record to the index."""
 
857
        self._cache_version(version_id, options, pos, size, parents)
 
858
 
 
859
        content = "%s %s %s %s %s\n" % (version_id.encode('utf-8'),
 
860
                                        ','.join(options),
 
861
                                        pos,
 
862
                                        size,
 
863
                                        self._version_list_to_index(parents))
 
864
        assert isinstance(content, str), 'content must be utf-8 encoded'
 
865
        self._transport.append(self._filename, StringIO(content))
 
866
 
 
867
    def has_version(self, version_id):
 
868
        """True if the version is in the index."""
 
869
        return self._cache.has_key(version_id)
 
870
 
 
871
    def get_position(self, version_id):
 
872
        """Return data position and size of specified version."""
 
873
        return (self._cache[version_id][2], \
 
874
                self._cache[version_id][3])
 
875
 
 
876
    def get_method(self, version_id):
 
877
        """Return compression method of specified version."""
 
878
        options = self._cache[version_id][1]
 
879
        if 'fulltext' in options:
 
880
            return 'fulltext'
 
881
        else:
 
882
            assert 'line-delta' in options
 
883
            return 'line-delta'
 
884
 
 
885
    def get_options(self, version_id):
 
886
        return self._cache[version_id][1]
 
887
 
 
888
    def get_parents(self, version_id):
 
889
        """Return parents of specified version ignoring ghosts."""
 
890
        return [parent for parent in self._cache[version_id][4] 
 
891
                if parent in self._cache]
 
892
 
 
893
    def get_parents_with_ghosts(self, version_id):
 
894
        """Return parents of specified version wth ghosts."""
 
895
        return self._cache[version_id][4] 
 
896
 
 
897
    def check_versions_present(self, version_ids):
 
898
        """Check that all specified versions are present."""
 
899
        version_ids = set(version_ids)
 
900
        for version_id in list(version_ids):
 
901
            if version_id in self._cache:
 
902
                version_ids.remove(version_id)
 
903
        if version_ids:
 
904
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
905
 
 
906
 
 
907
class _KnitData(_KnitComponentFile):
 
908
    """Contents of the knit data file"""
 
909
 
 
910
    HEADER = "# bzr knit data 7\n"
 
911
 
 
912
    def __init__(self, transport, filename, mode, create=False):
 
913
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
914
        self._file = None
 
915
        self._checked = False
 
916
        if create:
 
917
            self._transport.put(self._filename, StringIO(''))
 
918
        self._records = {}
 
919
 
 
920
    def clear_cache(self):
 
921
        """Clear the record cache."""
 
922
        self._records = {}
 
923
 
 
924
    def _open_file(self):
 
925
        if self._file is None:
 
926
            try:
 
927
                self._file = self._transport.get(self._filename)
 
928
            except NoSuchFile:
 
929
                pass
 
930
        return self._file
 
931
 
 
932
    def _record_to_data(self, version_id, digest, lines):
 
933
        """Convert version_id, digest, lines into a raw data block.
 
934
        
 
935
        :return: (len, a StringIO instance with the raw data ready to read.)
 
936
        """
 
937
        sio = StringIO()
 
938
        data_file = GzipFile(None, mode='wb', fileobj=sio)
 
939
        print >>data_file, "version %s %d %s" % (version_id.encode('utf-8'), len(lines), digest)
 
940
        data_file.writelines(lines)
 
941
        print >>data_file, "end %s\n" % version_id.encode('utf-8')
 
942
        data_file.close()
 
943
        length= sio.tell()
 
944
        sio.seek(0)
 
945
        return length, sio
 
946
 
 
947
    def add_raw_record(self, raw_data):
 
948
        """Append a prepared record to the data file."""
 
949
        assert isinstance(raw_data, str), 'data must be plain bytes'
 
950
        start_pos = self._transport.append(self._filename, StringIO(raw_data))
 
951
        return start_pos, len(raw_data)
 
952
        
 
953
    def add_record(self, version_id, digest, lines):
 
954
        """Write new text record to disk.  Returns the position in the
 
955
        file where it was written."""
 
956
        size, sio = self._record_to_data(version_id, digest, lines)
 
957
        # cache
 
958
        self._records[version_id] = (digest, lines)
 
959
        # write to disk
 
960
        start_pos = self._transport.append(self._filename, sio)
 
961
        return start_pos, size
 
962
 
 
963
    def _parse_record_header(self, version_id, raw_data):
 
964
        """Parse a record header for consistency.
 
965
 
 
966
        :return: the header and the decompressor stream.
 
967
                 as (stream, header_record)
 
968
        """
 
969
        df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
 
970
        rec = df.readline().split()
 
971
        if len(rec) != 4:
 
972
            raise KnitCorrupt(self._filename, 'unexpected number of elements in record header')
 
973
        if rec[1].decode('utf-8')!= version_id:
 
974
            raise KnitCorrupt(self._filename, 
 
975
                              'unexpected version, wanted %r, got %r' % (
 
976
                                version_id, rec[1]))
 
977
        return df, rec
 
978
 
 
979
    def _parse_record(self, version_id, data):
 
980
        df, rec = self._parse_record_header(version_id, data)
 
981
        lines = int(rec[2])
 
982
        record_contents = self._read_record_contents(df, lines)
 
983
        l = df.readline()
 
984
        if l.decode('utf-8') != 'end %s\n' % version_id:
 
985
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
 
986
                        % (l, version_id))
 
987
        df.close()
 
988
        return record_contents, rec[3]
 
989
 
 
990
    def _read_record_contents(self, df, record_lines):
 
991
        """Read and return n lines from datafile."""
 
992
        r = []
 
993
        for i in range(record_lines):
 
994
            r.append(df.readline())
 
995
        return r
 
996
 
 
997
    def read_records_iter_raw(self, records):
 
998
        """Read text records from data file and yield raw data.
 
999
 
 
1000
        This unpacks enough of the text record to validate the id is
 
1001
        as expected but thats all.
 
1002
 
 
1003
        It will actively recompress currently cached records on the
 
1004
        basis that that is cheaper than I/O activity.
 
1005
        """
 
1006
        needed_records = []
 
1007
        for version_id, pos, size in records:
 
1008
            if version_id not in self._records:
 
1009
                needed_records.append((version_id, pos, size))
 
1010
 
 
1011
        # setup an iterator of the external records:
 
1012
        # uses readv so nice and fast we hope.
 
1013
        if len(needed_records):
 
1014
            # grab the disk data needed.
 
1015
            raw_records = self._transport.readv(self._filename,
 
1016
                [(pos, size) for version_id, pos, size in needed_records])
 
1017
 
 
1018
        for version_id, pos, size in records:
 
1019
            if version_id in self._records:
 
1020
                # compress a new version
 
1021
                size, sio = self._record_to_data(version_id,
 
1022
                                                 self._records[version_id][0],
 
1023
                                                 self._records[version_id][1])
 
1024
                yield version_id, sio.getvalue()
 
1025
            else:
 
1026
                pos, data = raw_records.next()
 
1027
                # validate the header
 
1028
                df, rec = self._parse_record_header(version_id, data)
 
1029
                df.close()
 
1030
                yield version_id, data
 
1031
 
 
1032
 
 
1033
    def read_records_iter(self, records):
 
1034
        """Read text records from data file and yield result.
 
1035
 
 
1036
        Each passed record is a tuple of (version_id, pos, len) and
 
1037
        will be read in the given order.  Yields (version_id,
 
1038
        contents, digest).
 
1039
        """
 
1040
 
 
1041
        needed_records = []
 
1042
        for version_id, pos, size in records:
 
1043
            if version_id not in self._records:
 
1044
                needed_records.append((version_id, pos, size))
 
1045
 
 
1046
        if len(needed_records):
 
1047
            # We take it that the transport optimizes the fetching as good
 
1048
            # as possible (ie, reads continous ranges.)
 
1049
            response = self._transport.readv(self._filename,
 
1050
                [(pos, size) for version_id, pos, size in needed_records])
 
1051
 
 
1052
            for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
 
1053
                content, digest = self._parse_record(record_id, data)
 
1054
                self._records[record_id] = (digest, content)
 
1055
    
 
1056
        for version_id, pos, size in records:
 
1057
            yield version_id, copy(self._records[version_id][1]), copy(self._records[version_id][0])
 
1058
 
 
1059
    def read_records(self, records):
 
1060
        """Read records into a dictionary."""
 
1061
        components = {}
 
1062
        for record_id, content, digest in self.read_records_iter(records):
 
1063
            components[record_id] = (content, digest)
 
1064
        return components
 
1065
 
 
1066
 
 
1067
class InterKnit(InterVersionedFile):
 
1068
    """Optimised code paths for knit to knit operations."""
 
1069
    
 
1070
    _matching_file_factory = KnitVersionedFile
 
1071
    
 
1072
    @staticmethod
 
1073
    def is_compatible(source, target):
 
1074
        """Be compatible with knits.  """
 
1075
        try:
 
1076
            return (isinstance(source, KnitVersionedFile) and
 
1077
                    isinstance(target, KnitVersionedFile))
 
1078
        except AttributeError:
 
1079
            return False
 
1080
 
 
1081
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
1082
        """See InterVersionedFile.join."""
 
1083
        assert isinstance(self.source, KnitVersionedFile)
 
1084
        assert isinstance(self.target, KnitVersionedFile)
 
1085
 
 
1086
        if version_ids is None:
 
1087
            version_ids = self.source.versions()
 
1088
        else:
 
1089
            if not ignore_missing:
 
1090
                self.source._check_versions_present(version_ids)
 
1091
            else:
 
1092
                version_ids = set(self.source.versions()).intersection(
 
1093
                    set(version_ids))
 
1094
 
 
1095
        if not version_ids:
 
1096
            return 0
 
1097
 
 
1098
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1099
        try:
 
1100
            version_ids = list(version_ids)
 
1101
            if None in version_ids:
 
1102
                version_ids.remove(None)
 
1103
    
 
1104
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
 
1105
            this_versions = set(self.target._index.get_versions())
 
1106
            needed_versions = self.source_ancestry - this_versions
 
1107
            cross_check_versions = self.source_ancestry.intersection(this_versions)
 
1108
            mismatched_versions = set()
 
1109
            for version in cross_check_versions:
 
1110
                # scan to include needed parents.
 
1111
                n1 = set(self.target.get_parents_with_ghosts(version))
 
1112
                n2 = set(self.source.get_parents_with_ghosts(version))
 
1113
                if n1 != n2:
 
1114
                    # FIXME TEST this check for cycles being introduced works
 
1115
                    # the logic is we have a cycle if in our graph we are an
 
1116
                    # ancestor of any of the n2 revisions.
 
1117
                    for parent in n2:
 
1118
                        if parent in n1:
 
1119
                            # safe
 
1120
                            continue
 
1121
                        else:
 
1122
                            parent_ancestors = self.source.get_ancestry(parent)
 
1123
                            if version in parent_ancestors:
 
1124
                                raise errors.GraphCycleError([parent, version])
 
1125
                    # ensure this parent will be available later.
 
1126
                    new_parents = n2.difference(n1)
 
1127
                    needed_versions.update(new_parents.difference(this_versions))
 
1128
                    mismatched_versions.add(version)
 
1129
    
 
1130
            if not needed_versions and not cross_check_versions:
 
1131
                return 0
 
1132
            full_list = topo_sort(self.source.get_graph())
 
1133
    
 
1134
            version_list = [i for i in full_list if (not self.target.has_version(i)
 
1135
                            and i in needed_versions)]
 
1136
    
 
1137
            # plan the join:
 
1138
            copy_queue = []
 
1139
            copy_queue_records = []
 
1140
            copy_set = set()
 
1141
            for version_id in version_list:
 
1142
                options = self.source._index.get_options(version_id)
 
1143
                parents = self.source._index.get_parents_with_ghosts(version_id)
 
1144
                # check that its will be a consistent copy:
 
1145
                for parent in parents:
 
1146
                    # if source has the parent, we must :
 
1147
                    # * already have it or
 
1148
                    # * have it scheduled already
 
1149
                    # otherwise we dont care
 
1150
                    assert (self.target.has_version(parent) or
 
1151
                            parent in copy_set or
 
1152
                            not self.source.has_version(parent))
 
1153
                data_pos, data_size = self.source._index.get_position(version_id)
 
1154
                copy_queue_records.append((version_id, data_pos, data_size))
 
1155
                copy_queue.append((version_id, options, parents))
 
1156
                copy_set.add(version_id)
 
1157
 
 
1158
            # data suck the join:
 
1159
            count = 0
 
1160
            total = len(version_list)
 
1161
            # we want the raw gzip for bulk copying, but the record validated
 
1162
            # just enough to be sure its the right one.
 
1163
            # TODO: consider writev or write combining to reduce 
 
1164
            # death of a thousand cuts feeling.
 
1165
            for (version_id, raw_data), \
 
1166
                (version_id2, options, parents) in \
 
1167
                izip(self.source._data.read_records_iter_raw(copy_queue_records),
 
1168
                     copy_queue):
 
1169
                assert version_id == version_id2, 'logic error, inconsistent results'
 
1170
                count = count + 1
 
1171
                pb.update("Joining knit", count, total)
 
1172
                pos, size = self.target._data.add_raw_record(raw_data)
 
1173
                self.target._index.add_version(version_id, options, pos, size, parents)
 
1174
 
 
1175
            for version in mismatched_versions:
 
1176
                # FIXME RBC 20060309 is this needed?
 
1177
                n1 = set(self.target.get_parents_with_ghosts(version))
 
1178
                n2 = set(self.source.get_parents_with_ghosts(version))
 
1179
                # write a combined record to our history preserving the current 
 
1180
                # parents as first in the list
 
1181
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
 
1182
                self.target.fix_parents(version, new_parents)
 
1183
            return count
 
1184
        finally:
 
1185
            pb.clear()
 
1186
            pb.finished()
 
1187
 
 
1188
 
 
1189
InterVersionedFile.register_optimiser(InterKnit)