~bzr-pqm/bzr/bzr.dev

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