/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
# Written by Martin Pool.
3
# Modified by Johan Rydberg <jrydberg@gnu.org>
4
# Modified by Robert Collins <robert.collins@canonical.com>
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20
"""Knit versionedfile implementation.
21
22
A knit is a versioned file implementation that supports efficient append only
23
updates.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
24
25
Knit file layout:
26
lifeless: the data file is made up of "delta records".  each delta record has a delta header 
27
that contains; (1) a version id, (2) the size of the delta (in lines), and (3)  the digest of 
28
the -expanded data- (ie, the delta applied to the parent).  the delta also ends with a 
29
end-marker; simply "end VERSION"
30
31
delta can be line or full contents.a
32
... the 8's there are the index number of the annotation.
33
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
34
59,59,3
35
8
36
8         if ie.executable:
37
8             e.set('executable', 'yes')
38
130,130,2
39
8         if elt.get('executable') == 'yes':
40
8             ie.executable = True
41
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 
42
43
44
whats in an index:
45
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
46
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
47
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
48
09:33 < lifeless> right
49
09:33 < jrydberg> lifeless: the position and size is the range in the data file
50
51
52
so the index sequence is the dictionary compressed sequence number used
53
in the deltas to provide line annotation
54
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
55
"""
56
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
57
# TODOS:
58
# 10:16 < lifeless> make partial index writes safe
59
# 10:16 < lifeless> implement 'knit.check()' like weave.check()
60
# 10:17 < lifeless> record known ghosts so we can detect when they are filled in rather than the current 'reweave 
61
#                    always' approach.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
62
# move sha1 out of the content so that join is faster at verifying parents
63
# record content length ?
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
64
                  
65
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
66
from copy import copy
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
67
from cStringIO import StringIO
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
68
import difflib
69
from difflib import SequenceMatcher
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
70
from gzip import GzipFile
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
71
from itertools import izip
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
72
import os
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
73
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
74
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
75
import bzrlib
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
76
import bzrlib.errors as errors
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1563.2.13 by Robert Collins
InterVersionedFile implemented.
83
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
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
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
164
        lines = []
165
        for line in content:
166
            origin, text = line.split(' ', 1)
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
167
            lines.append((origin.decode('utf-8'), text))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
168
        return KnitContent(lines)
169
170
    def parse_line_delta_iter(self, lines):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
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
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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)
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
186
                contents.append((origin.decode('utf-8'), text))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
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]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
198
199
    def lower_line_delta(self, delta):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
200
        """convert a delta into a serializable form.
201
202
        See parse_line_delta_iter which this inverts.
203
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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:
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
208
                out.append('%s %s' % (origin.encode('utf-8'), text))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
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
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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."""
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
248
    k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
267
    def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
1563.2.25 by Robert Collins
Merge in upstream.
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
        """
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
273
        if access_mode is None:
274
            access_mode = 'w'
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
275
        super(KnitVersionedFile, self).__init__(access_mode)
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
276
        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.
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
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
283
        self.factory = factory or KnitAnnotateFactory()
284
        self.writable = (access_mode == 'w')
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
285
        self.delta = delta
286
287
        self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
1563.2.25 by Robert Collins
Merge in upstream.
288
            access_mode, create=create)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
289
        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.
290
            access_mode, create=not len(self.versions()))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
291
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
292
    def clear_cache(self):
293
        """Clear the data cache only."""
294
        self._data.clear_cache()
295
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
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
1563.2.13 by Robert Collins
InterVersionedFile implemented.
306
    def create_empty(self, name, transport, mode=None):
1563.2.25 by Robert Collins
Merge in upstream.
307
        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.
308
    
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
309
    def _fix_parents(self, version, new_parents):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
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
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
330
    @staticmethod
331
    def get_suffixes():
332
        """See VersionedFile.get_suffixes()."""
333
        return [DATA_SUFFIX, INDEX_SUFFIX]
1563.2.13 by Robert Collins
InterVersionedFile implemented.
334
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
465
    def _add_lines_with_ghosts(self, version_id, parents, lines):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
470
    def _add_lines(self, version_id, parents, lines):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
471
        """See VersionedFile.add_lines."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
485
        if False or __debug__:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
494
495
        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.
496
        """
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
497
        ghostless_parents = []
1594.2.8 by Robert Collins
add ghost aware apis to knits.
498
        ghosts = []
499
        for parent in parents:
500
            if not self.has_version(parent):
501
                ghosts.append(parent)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
502
            else:
503
                ghostless_parents.append(parent)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
504
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
505
        if delta and not len(ghostless_parents):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
515
        lines = self.factory.make(lines, version_id) #len(self._index))
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
516
        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.
517
            # 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.
518
            self._merge_annotations(lines, ghostless_parents)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
519
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
520
        if len(ghostless_parents) and delta:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
525
            delta_parents = ghostless_parents
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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')
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
538
            content = self._get_content(ghostless_parents[0])
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1563.2.19 by Robert Collins
stub out a check for knits.
548
    def check(self, progress_bar=None):
549
        """See VersionedFile.check()."""
550
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
551
    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.
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
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
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 = []
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
568
        requested_versions = list(version_ids)
569
        # filter for available versions
570
        for version_id in requested_versions:
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
571
            if not self.has_version(version_id):
572
                raise RevisionNotPresent(version_id, self.filename)
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
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
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
581
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
582
        count = 0
583
        total = len(version_id_records)
584
        try:
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
585
            pb.update('Walking content.', count, total)
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
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():
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
595
                        yield line
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
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
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
602
            pb.update('Walking content.', total, total)
603
            pb.finished()
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
604
        except:
605
            pb.update('Walking content.', total, total)
606
            pb.finished()
607
            raise
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
608
        
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
609
    def num_versions(self):
610
        """See VersionedFile.num_versions()."""
611
        return self._index.num_versions()
612
613
    __len__ = num_versions
614
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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():
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
619
            yield origin, text
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
649
    #@deprecated_method(zero_eight)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
655
        # FIXME RB 20060228 this really is inefficient!
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
674
    def __init__(self, transport, filename, mode):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
675
        self._transport = transport
676
        self._filename = filename
677
        self._mode = mode
678
679
    def write_header(self):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
680
        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.
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.
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.
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.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
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.
725
        if not version_id in self._history:
726
            self._history.append(version_id)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
727
728
    def _iter_index(self, fp):
1594.2.18 by Robert Collins
Really do incremental index status.
729
        l = fp.readline()
730
        while l != '':
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
731
            yield l.split()
1594.2.18 by Robert Collins
Really do incremental index status.
732
            l = fp.readline()
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
733
        #lines = fp.read()
734
        #for l in lines.splitlines(False):
735
        #    yield l.split()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
736
1563.2.25 by Robert Collins
Merge in upstream.
737
    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.
738
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
739
        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.
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.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
744
        self._history = []
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
745
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
746
        try:
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
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()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
767
1594.2.8 by Robert Collins
add ghost aware apis to knits.
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:
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
779
                assert isinstance(value, str)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
780
                result.append(self._history[int(value)])
781
        return result
782
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
783
    def get_graph(self):
784
        graph = []
785
        for version_id, index in self._cache.iteritems():
786
            graph.append((version_id, index[4]))
787
        return graph
788
789
    def get_ancestry(self, versions):
790
        """See VersionedFile.get_ancestry."""
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
791
        # get a graph of all the mentioned versions:
792
        graph = {}
793
        pending = set(versions)
794
        while len(pending):
795
            version = pending.pop()
796
            parents = self._cache[version][4]
1594.2.8 by Robert Collins
add ghost aware apis to knits.
797
            # got the parents ok
798
            # trim ghosts
799
            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.
800
            for parent in parents:
1594.2.8 by Robert Collins
add ghost aware apis to knits.
801
                # 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.
802
                if parent not in graph:
803
                    pending.add(parent)
804
            graph[version] = parents
805
        return topo_sort(graph.items())
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
806
1594.2.8 by Robert Collins
add ghost aware apis to knits.
807
    def get_ancestry_with_ghosts(self, versions):
808
        """See VersionedFile.get_ancestry_with_ghosts."""
809
        # get a graph of all the mentioned versions:
810
        graph = {}
811
        pending = set(versions)
812
        while len(pending):
813
            version = pending.pop()
814
            try:
815
                parents = self._cache[version][4]
816
            except KeyError:
817
                # ghost, fake it
818
                graph[version] = []
819
                pass
820
            else:
821
                # got the parents ok
822
                for parent in parents:
823
                    if parent not in graph:
824
                        pending.add(parent)
825
                graph[version] = parents
826
        return topo_sort(graph.items())
827
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
828
    def num_versions(self):
829
        return len(self._history)
830
831
    __len__ = num_versions
832
833
    def get_versions(self):
834
        return self._history
835
836
    def idx_to_name(self, idx):
837
        return self._history[idx]
838
839
    def lookup(self, version_id):
840
        assert version_id in self._cache
841
        return self._history.index(version_id)
842
1594.2.8 by Robert Collins
add ghost aware apis to knits.
843
    def _version_list_to_index(self, versions):
844
        result_list = []
845
        for version in versions:
846
            if version in self._cache:
847
                result_list.append(str(self._history.index(version)))
848
            else:
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
849
                result_list.append('.' + version.encode('utf-8'))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
850
        return ' '.join(result_list)
851
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
852
    def add_version(self, version_id, options, pos, size, parents):
853
        """Add a version record to the index."""
854
        self._cache_version(version_id, options, pos, size, parents)
855
856
        content = "%s %s %s %s %s\n" % (version_id,
857
                                        ','.join(options),
858
                                        pos,
859
                                        size,
1594.2.8 by Robert Collins
add ghost aware apis to knits.
860
                                        self._version_list_to_index(parents))
1563.2.13 by Robert Collins
InterVersionedFile implemented.
861
        self._transport.append(self._filename, StringIO(content))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
862
863
    def has_version(self, version_id):
864
        """True if the version is in the index."""
865
        return self._cache.has_key(version_id)
866
867
    def get_position(self, version_id):
868
        """Return data position and size of specified version."""
869
        return (self._cache[version_id][2], \
870
                self._cache[version_id][3])
871
872
    def get_method(self, version_id):
873
        """Return compression method of specified version."""
874
        options = self._cache[version_id][1]
875
        if 'fulltext' in options:
876
            return 'fulltext'
877
        else:
878
            assert 'line-delta' in options
879
            return 'line-delta'
880
881
    def get_options(self, version_id):
882
        return self._cache[version_id][1]
883
884
    def get_parents(self, version_id):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
885
        """Return parents of specified version ignoring ghosts."""
886
        return [parent for parent in self._cache[version_id][4] 
887
                if parent in self._cache]
888
889
    def get_parents_with_ghosts(self, version_id):
890
        """Return parents of specified version wth ghosts."""
891
        return self._cache[version_id][4] 
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
892
893
    def check_versions_present(self, version_ids):
894
        """Check that all specified versions are present."""
895
        version_ids = set(version_ids)
896
        for version_id in list(version_ids):
897
            if version_id in self._cache:
898
                version_ids.remove(version_id)
899
        if version_ids:
900
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
901
902
903
class _KnitData(_KnitComponentFile):
904
    """Contents of the knit data file"""
905
906
    HEADER = "# bzr knit data 7\n"
907
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
908
    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.
909
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
910
        self._file = None
911
        self._checked = False
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
912
        if create:
913
            self._transport.put(self._filename, StringIO(''))
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
914
        self._records = {}
915
916
    def clear_cache(self):
917
        """Clear the record cache."""
918
        self._records = {}
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
919
920
    def _open_file(self):
921
        if self._file is None:
922
            try:
923
                self._file = self._transport.get(self._filename)
924
            except NoSuchFile:
925
                pass
926
        return self._file
927
928
    def add_record(self, version_id, digest, lines):
929
        """Write new text record to disk.  Returns the position in the
930
        file where it was written."""
931
        sio = StringIO()
932
        data_file = GzipFile(None, mode='wb', fileobj=sio)
933
        print >>data_file, "version %s %d %s" % (version_id, len(lines), digest)
934
        data_file.writelines(lines)
935
        print >>data_file, "end %s\n" % version_id
936
        data_file.close()
937
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
938
        # cache
939
        self._records[version_id] = (digest, lines)
940
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
941
        content = sio.getvalue()
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
942
        sio.seek(0)
943
        start_pos = self._transport.append(self._filename, sio)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
944
        return start_pos, len(content)
945
946
    def _parse_record(self, version_id, data):
947
        df = GzipFile(mode='rb', fileobj=StringIO(data))
948
        rec = df.readline().split()
949
        if len(rec) != 4:
950
            raise KnitCorrupt(self._filename, 'unexpected number of records')
951
        if rec[1] != version_id:
1594.3.3 by Robert Collins
Bugfix error message output in knit error raising.
952
            raise KnitCorrupt(self._filename, 
1594.3.4 by Robert Collins
Change urllib ranges implementation to be one coalesced range per http request.
953
                              'unexpected version, wanted %r, got %r' % (
954
                                version_id, rec[1]))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
955
        lines = int(rec[2])
956
        record_contents = self._read_record_contents(df, lines)
957
        l = df.readline()
958
        if l != 'end %s\n' % version_id:
959
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
960
                        % (l, version_id))
961
        return record_contents, rec[3]
962
963
    def _read_record_contents(self, df, record_lines):
964
        """Read and return n lines from datafile."""
965
        r = []
966
        for i in range(record_lines):
967
            r.append(df.readline())
968
        return r
969
970
    def read_records_iter(self, records):
971
        """Read text records from data file and yield result.
972
973
        Each passed record is a tuple of (version_id, pos, len) and
974
        will be read in the given order.  Yields (version_id,
975
        contents, digest).
976
        """
977
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
978
        needed_records = []
979
        for version_id, pos, size in records:
980
            if version_id not in self._records:
981
                needed_records.append((version_id, pos, size))
982
983
        if len(needed_records):
984
            # We take it that the transport optimizes the fetching as good
985
            # as possible (ie, reads continous ranges.)
986
            response = self._transport.readv(self._filename,
987
                [(pos, size) for version_id, pos, size in needed_records])
988
1594.3.5 by Robert Collins
Bugfix knit caching implementation.
989
            for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
990
                content, digest = self._parse_record(record_id, data)
991
                self._records[record_id] = (digest, content)
992
    
993
        for version_id, pos, size in records:
994
            yield version_id, copy(self._records[version_id][1]), copy(self._records[version_id][0])
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
995
996
    def read_records(self, records):
997
        """Read records into a dictionary."""
998
        components = {}
999
        for record_id, content, digest in self.read_records_iter(records):
1000
            components[record_id] = (content, digest)
1001
        return components
1002
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1003
1004
class InterKnit(InterVersionedFile):
1005
    """Optimised code paths for knit to knit operations."""
1006
    
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1007
    _matching_file_factory = KnitVersionedFile
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1008
    
1009
    @staticmethod
1010
    def is_compatible(source, target):
1011
        """Be compatible with knits.  """
1012
        try:
1013
            return (isinstance(source, KnitVersionedFile) and
1014
                    isinstance(target, KnitVersionedFile))
1015
        except AttributeError:
1016
            return False
1017
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1018
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1019
        """See InterVersionedFile.join."""
1020
        assert isinstance(self.source, KnitVersionedFile)
1021
        assert isinstance(self.target, KnitVersionedFile)
1022
1023
        if version_ids is None:
1024
            version_ids = self.source.versions()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1025
        else:
1026
            if not ignore_missing:
1027
                self.source._check_versions_present(version_ids)
1028
            else:
1029
                version_ids = set(self.source.versions()).intersection(
1030
                    set(version_ids))
1031
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1032
        if not version_ids:
1033
            return 0
1034
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1035
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1036
        try:
1037
            version_ids = list(version_ids)
1038
            if None in version_ids:
1039
                version_ids.remove(None)
1040
    
1041
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
1042
            this_versions = set(self.target._index.get_versions())
1043
            needed_versions = self.source_ancestry - this_versions
1044
            cross_check_versions = self.source_ancestry.intersection(this_versions)
1045
            mismatched_versions = set()
1046
            for version in cross_check_versions:
1047
                # scan to include needed parents.
1048
                n1 = set(self.target.get_parents_with_ghosts(version))
1049
                n2 = set(self.source.get_parents_with_ghosts(version))
1050
                if n1 != n2:
1051
                    # FIXME TEST this check for cycles being introduced works
1052
                    # the logic is we have a cycle if in our graph we are an
1053
                    # ancestor of any of the n2 revisions.
1054
                    for parent in n2:
1055
                        if parent in n1:
1056
                            # safe
1057
                            continue
1058
                        else:
1059
                            parent_ancestors = self.source.get_ancestry(parent)
1060
                            if version in parent_ancestors:
1061
                                raise errors.GraphCycleError([parent, version])
1062
                    # ensure this parent will be available later.
1063
                    new_parents = n2.difference(n1)
1064
                    needed_versions.update(new_parents.difference(this_versions))
1065
                    mismatched_versions.add(version)
1066
    
1067
            if not needed_versions and not cross_check_versions:
1068
                return 0
1069
            full_list = topo_sort(self.source.get_graph())
1070
    
1071
            version_list = [i for i in full_list if (not self.target.has_version(i)
1072
                            and i in needed_versions)]
1073
    
1074
            records = []
1075
            for version_id in version_list:
1076
                data_pos, data_size = self.source._index.get_position(version_id)
1077
                records.append((version_id, data_pos, data_size))
1078
    
1079
            count = 0
1080
            for version_id, lines, digest \
1081
                    in self.source._data.read_records_iter(records):
1082
                options = self.source._index.get_options(version_id)
1083
                parents = self.source._index.get_parents_with_ghosts(version_id)
1084
                
1085
                for parent in parents:
1086
                    # if source has the parent, we must hav grabbed it first.
1087
                    assert (self.target.has_version(parent) or not
1088
                            self.source.has_version(parent))
1089
    
1090
                count = count + 1
1091
                pb.update("Joining knit", count, len(version_list))
1092
    
1093
                pos, size = self.target._data.add_record(version_id, digest, lines)
1094
                self.target._index.add_version(version_id, options, pos, size, parents)
1095
    
1096
            for version in mismatched_versions:
1097
                n1 = set(self.target.get_parents_with_ghosts(version))
1098
                n2 = set(self.source.get_parents_with_ghosts(version))
1099
                # write a combined record to our history preserving the current 
1100
                # parents as first in the list
1101
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1102
                self.target.fix_parents(version, new_parents)
1103
            return count
1104
        finally:
1105
            pb.clear()
1106
            pb.finished()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1107
1108
1109
InterVersionedFile.register_optimiser(InterKnit)