/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
1596.2.24 by Robert Collins
Gzipfile was slightly slower than ideal.
70
import gzip
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
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
361
        the annotations based on changed to the text.
362
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
363
        for parent_id in parents:
364
            merge_content = self._get_content(parent_id)
365
            seq = SequenceMatcher(None, merge_content.text(), content.text())
366
            for i, j, n in seq.get_matching_blocks():
367
                if n == 0:
368
                    continue
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
369
                # this appears to copy (origin, text) pairs across to the new
370
                # content for any line that matches the last-checked parent.
371
                # FIXME: save the sequence control data for delta compression
372
                # against the most relevant parent rather than rediffing.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
373
                content._lines[j:j+n] = merge_content._lines[i:i+n]
374
375
    def _get_components(self, version_id):
376
        """Return a list of (version_id, method, data) tuples that
377
        makes up version specified by version_id of the knit.
378
379
        The components should be applied in the order of the returned
380
        list.
381
382
        The basis knit will be used to the largest extent possible
383
        since it is assumed that accesses to it is faster.
384
        """
385
        # needed_revisions holds a list of (method, version_id) of
386
        # versions that is needed to be fetched to construct the final
387
        # version of the file.
388
        #
389
        # basis_revisions is a list of versions that needs to be
390
        # fetched but exists in the basis knit.
391
392
        basis = self.basis_knit
393
        needed_versions = []
394
        basis_versions = []
395
        cursor = version_id
396
397
        while 1:
398
            picked_knit = self
399
            if basis and basis._index.has_version(cursor):
400
                picked_knit = basis
401
                basis_versions.append(cursor)
402
            method = picked_knit._index.get_method(cursor)
403
            needed_versions.append((method, cursor))
404
            if method == 'fulltext':
405
                break
406
            cursor = picked_knit.get_parents(cursor)[0]
407
408
        components = {}
409
        if basis_versions:
410
            records = []
411
            for comp_id in basis_versions:
412
                data_pos, data_size = basis._index.get_data_position(comp_id)
413
                records.append((piece_id, data_pos, data_size))
414
            components.update(basis._data.read_records(records))
415
416
        records = []
417
        for comp_id in [vid for method, vid in needed_versions
418
                        if vid not in basis_versions]:
419
            data_pos, data_size = self._index.get_position(comp_id)
420
            records.append((comp_id, data_pos, data_size))
421
        components.update(self._data.read_records(records))
422
423
        # get_data_records returns a mapping with the version id as
424
        # index and the value as data.  The order the components need
425
        # to be applied is held by needed_versions (reversed).
426
        out = []
427
        for method, comp_id in reversed(needed_versions):
428
            out.append((comp_id, method, components[comp_id]))
429
430
        return out
431
432
    def _get_content(self, version_id):
433
        """Returns a content object that makes up the specified
434
        version."""
435
        if not self.has_version(version_id):
436
            raise RevisionNotPresent(version_id, self.filename)
437
438
        if self.basis_knit and version_id in self.basis_knit:
439
            return self.basis_knit._get_content(version_id)
440
441
        content = None
442
        components = self._get_components(version_id)
443
        for component_id, method, (data, digest) in components:
444
            version_idx = self._index.lookup(component_id)
445
            if method == 'fulltext':
446
                assert content is None
447
                content = self.factory.parse_fulltext(data, version_idx)
448
            elif method == 'line-delta':
449
                delta = self.factory.parse_line_delta(data, version_idx)
450
                content.apply_delta(delta)
451
452
        if 'no-eol' in self._index.get_options(version_id):
453
            line = content._lines[-1][1].rstrip('\n')
454
            content._lines[-1] = (content._lines[-1][0], line)
455
456
        if sha_strings(content.text()) != digest:
457
            raise KnitCorrupt(self.filename, 'sha-1 does not match')
458
459
        return content
460
461
    def _check_versions_present(self, version_ids):
462
        """Check that all specified versions are present."""
463
        version_ids = set(version_ids)
464
        for r in list(version_ids):
465
            if self._index.has_version(r):
466
                version_ids.remove(r)
467
        if version_ids:
468
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
469
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
470
    def _add_lines_with_ghosts(self, version_id, parents, lines):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
471
        """See VersionedFile.add_lines_with_ghosts()."""
472
        self._check_add(version_id, lines)
473
        return self._add(version_id, lines[:], parents, self.delta)
474
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
475
    def _add_lines(self, version_id, parents, lines):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
476
        """See VersionedFile.add_lines."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
477
        self._check_add(version_id, lines)
478
        self._check_versions_present(parents)
479
        return self._add(version_id, lines[:], parents, self.delta)
480
481
    def _check_add(self, version_id, lines):
482
        """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.
483
        assert self.writable, "knit is not opened for write"
484
        ### FIXME escape. RBC 20060228
485
        if contains_whitespace(version_id):
486
            raise InvalidRevisionId(version_id)
487
        if self.has_version(version_id):
488
            raise RevisionAlreadyPresent(version_id, self.filename)
489
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
490
        if False or __debug__:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
491
            for l in lines:
492
                assert '\n' not in l[:-1]
493
494
    def _add(self, version_id, lines, parents, delta):
495
        """Add a set of lines on top of version specified by parents.
496
497
        If delta is true, compress the text as a line-delta against
498
        the first parent.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
499
500
        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.
501
        """
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
502
        present_parents = []
1594.2.8 by Robert Collins
add ghost aware apis to knits.
503
        ghosts = []
504
        for parent in parents:
505
            if not self.has_version(parent):
506
                ghosts.append(parent)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
507
            else:
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
508
                present_parents.append(parent)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
509
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
510
        if delta and not len(present_parents):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
511
            delta = False
512
513
        digest = sha_strings(lines)
514
        options = []
515
        if lines:
516
            if lines[-1][-1] != '\n':
517
                options.append('no-eol')
518
                lines[-1] = lines[-1] + '\n'
519
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
520
        lines = self.factory.make(lines, version_id)
521
        if self.factory.annotated and len(present_parents) > 0:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
522
            # Merge annotations from parent texts if so is needed.
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
523
            self._merge_annotations(lines, present_parents)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
524
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
525
        if len(present_parents) and delta:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
526
            # To speed the extract of texts the delta chain is limited
527
            # to a fixed number of deltas.  This should minimize both
528
            # I/O and the time spend applying deltas.
529
            count = 0
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
530
            delta_parents = present_parents
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
531
            while count < 25:
532
                parent = delta_parents[0]
533
                method = self._index.get_method(parent)
534
                if method == 'fulltext':
535
                    break
536
                delta_parents = self._index.get_parents(parent)
537
                count = count + 1
538
            if method == 'line-delta':
539
                delta = False
540
541
        if delta:
542
            options.append('line-delta')
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
543
            content = self._get_content(present_parents[0])
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
544
            delta_hunks = content.line_delta(lines)
545
            store_lines = self.factory.lower_line_delta(delta_hunks)
546
        else:
547
            options.append('fulltext')
548
            store_lines = self.factory.lower_fulltext(lines)
549
550
        where, size = self._data.add_record(version_id, digest, store_lines)
551
        self._index.add_version(version_id, options, where, size, parents)
552
1563.2.19 by Robert Collins
stub out a check for knits.
553
    def check(self, progress_bar=None):
554
        """See VersionedFile.check()."""
555
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
556
    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.
557
        """See VersionedFile.clone_text()."""
558
        # FIXME RBC 20060228 make fast by only inserting an index with null delta.
559
        self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
560
561
    def get_lines(self, version_id):
562
        """See VersionedFile.get_lines()."""
563
        return self._get_content(version_id).text()
564
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
565
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
566
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
567
        if version_ids is None:
568
            version_ids = self.versions()
569
        # we dont care about inclusions, the caller cares.
570
        # but we need to setup a list of records to visit.
571
        # we need version_id, position, length
572
        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.
573
        requested_versions = list(version_ids)
574
        # filter for available versions
575
        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.
576
            if not self.has_version(version_id):
577
                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.
578
        # get a in-component-order queue:
579
        version_ids = []
580
        for version_id in self.versions():
581
            if version_id in requested_versions:
582
                version_ids.append(version_id)
583
                data_pos, length = self._index.get_position(version_id)
584
                version_id_records.append((version_id, data_pos, length))
585
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
586
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
587
        count = 0
588
        total = len(version_id_records)
589
        try:
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
590
            pb.update('Walking content.', count, total)
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
591
            for version_id, data, sha_value in \
592
                self._data.read_records_iter(version_id_records):
593
                pb.update('Walking content.', count, total)
594
                method = self._index.get_method(version_id)
595
                version_idx = self._index.lookup(version_id)
596
                assert method in ('fulltext', 'line-delta')
597
                if method == 'fulltext':
598
                    content = self.factory.parse_fulltext(data, version_idx)
599
                    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.
600
                        yield line
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
601
                else:
602
                    delta = self.factory.parse_line_delta(data, version_idx)
603
                    for start, end, count, lines in delta:
604
                        for origin, line in lines:
605
                            yield line
606
                count +=1
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
607
            pb.update('Walking content.', total, total)
608
            pb.finished()
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
609
        except:
610
            pb.update('Walking content.', total, total)
611
            pb.finished()
612
            raise
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
613
        
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
614
    def num_versions(self):
615
        """See VersionedFile.num_versions()."""
616
        return self._index.num_versions()
617
618
    __len__ = num_versions
619
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
620
    def annotate_iter(self, version_id):
621
        """See VersionedFile.annotate_iter."""
622
        content = self._get_content(version_id)
623
        for origin, text in content.annotate_iter():
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
624
            yield origin, text
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
625
626
    def get_parents(self, version_id):
627
        """See VersionedFile.get_parents."""
628
        self._check_versions_present([version_id])
629
        return list(self._index.get_parents(version_id))
630
1594.2.8 by Robert Collins
add ghost aware apis to knits.
631
    def get_parents_with_ghosts(self, version_id):
632
        """See VersionedFile.get_parents."""
633
        self._check_versions_present([version_id])
634
        return list(self._index.get_parents_with_ghosts(version_id))
635
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
636
    def get_ancestry(self, versions):
637
        """See VersionedFile.get_ancestry."""
638
        if isinstance(versions, basestring):
639
            versions = [versions]
640
        if not versions:
641
            return []
642
        self._check_versions_present(versions)
643
        return self._index.get_ancestry(versions)
644
1594.2.8 by Robert Collins
add ghost aware apis to knits.
645
    def get_ancestry_with_ghosts(self, versions):
646
        """See VersionedFile.get_ancestry_with_ghosts."""
647
        if isinstance(versions, basestring):
648
            versions = [versions]
649
        if not versions:
650
            return []
651
        self._check_versions_present(versions)
652
        return self._index.get_ancestry_with_ghosts(versions)
653
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
654
    #@deprecated_method(zero_eight)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
655
    def walk(self, version_ids):
656
        """See VersionedFile.walk."""
657
        # We take the short path here, and extract all relevant texts
658
        # and put them in a weave and let that do all the work.  Far
659
        # from optimal, but is much simpler.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
660
        # FIXME RB 20060228 this really is inefficient!
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
661
        from bzrlib.weave import Weave
662
663
        w = Weave(self.filename)
664
        ancestry = self.get_ancestry(version_ids)
665
        sorted_graph = topo_sort(self._index.get_graph())
666
        version_list = [vid for vid in sorted_graph if vid in ancestry]
667
        
668
        for version_id in version_list:
669
            lines = self.get_lines(version_id)
670
            w.add_lines(version_id, self.get_parents(version_id), lines)
671
672
        for lineno, insert_id, dset, line in w.walk(version_ids):
673
            yield lineno, insert_id, dset, line
674
675
676
class _KnitComponentFile(object):
677
    """One of the files used to implement a knit database"""
678
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
679
    def __init__(self, transport, filename, mode):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
680
        self._transport = transport
681
        self._filename = filename
682
        self._mode = mode
683
684
    def write_header(self):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
685
        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.
686
        if old_len != 0:
687
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
688
689
    def check_header(self, fp):
690
        line = fp.read(len(self.HEADER))
691
        if line != self.HEADER:
692
            raise KnitHeaderError(badline=line)
693
694
    def commit(self):
695
        """Commit is a nop."""
696
697
    def __repr__(self):
698
        return '%s(%s)' % (self.__class__.__name__, self._filename)
699
700
701
class _KnitIndex(_KnitComponentFile):
702
    """Manages knit index file.
703
704
    The index is already kept in memory and read on startup, to enable
705
    fast lookups of revision information.  The cursor of the index
706
    file is always pointing to the end, making it easy to append
707
    entries.
708
709
    _cache is a cache for fast mapping from version id to a Index
710
    object.
711
712
    _history is a cache for fast mapping from indexes to version ids.
713
714
    The index data format is dictionary compressed when it comes to
715
    parent references; a index entry may only have parents that with a
716
    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.
717
718
    Duplicate entries may be written to the index for a single version id
719
    if this is done then the latter one completely replaces the former:
720
    this allows updates to correct version and parent information. 
721
    Note that the two entries may share the delta, and that successive
722
    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.
723
    """
724
725
    HEADER = "# bzr knit index 7\n"
726
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
727
    # speed of knit parsing went from 280 ms to 280 ms with slots addition.
728
    # __slots__ = ['_cache', '_history', '_transport', '_filename']
729
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
730
    def _cache_version(self, version_id, options, pos, size, parents):
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
731
        """Cache a version record in the history array and index cache.
732
        
733
        This is inlined into __init__ for performance. KEEP IN SYNC.
734
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
735
         indexes).
736
        """
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
737
        # only want the _history index to reference the 1st index entry
738
        # for version_id
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
739
        if version_id not in self._cache:
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
740
            self._history.append(version_id)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
741
        self._cache[version_id] = (version_id, options, pos, size, parents)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
742
1563.2.25 by Robert Collins
Merge in upstream.
743
    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.
744
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
745
        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.
746
        # position in _history is the 'official' index for a revision
747
        # but the values may have come from a newer entry.
748
        # so - wc -l of a knit index is != the number of uniqe names
749
        # in the weave.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
750
        self._history = []
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
751
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
752
        try:
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
753
            count = 0
754
            total = 1
755
            try:
756
                pb.update('read knit index', count, total)
757
                fp = self._transport.get(self._filename)
758
                self.check_header(fp)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
759
                # readlines reads the whole file at once:
760
                # bad for transports like http, good for local disk
761
                # we save 60 ms doing this one change (
762
                # from calling readline each time to calling
763
                # readlines once.
764
                # probably what we want for nice behaviour on
765
                # http is a incremental readlines that yields, or
766
                # a check for local vs non local indexes,
767
                for l in fp.readlines():
768
                    rec = l.split()
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
769
                    count += 1
770
                    total += 1
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
771
                    #pb.update('read knit index', count, total)
772
                    # See self._parse_parents
773
                    parents = []
774
                    for value in rec[4:]:
1596.2.19 by Robert Collins
Shave 20% off id2path.
775
                        if '.' == value[0]:
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
776
                            # uncompressed reference
777
                            parents.append(value[1:])
778
                        else:
779
                            # this is 15/4000ms faster than isinstance,
780
                            # (in lsprof)
781
                            # this function is called thousands of times a 
782
                            # second so small variations add up.
783
                            assert value.__class__ is str
784
                            parents.append(self._history[int(value)])
785
                    # end self._parse_parents
786
                    # self._cache_version(rec[0], 
787
                    #                     rec[1].split(','),
788
                    #                     int(rec[2]),
789
                    #                     int(rec[3]),
790
                    #                     parents)
791
                    # --- self._cache_version
792
                    # only want the _history index to reference the 1st 
793
                    # index entry for version_id
794
                    version_id = rec[0]
795
                    if version_id not in self._cache:
796
                        self._history.append(version_id)
797
                    self._cache[version_id] = (version_id,
798
                                               rec[1].split(','),
799
                                               int(rec[2]),
800
                                               int(rec[3]),
801
                                               parents)
802
                    # --- self._cache_version 
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
803
            except NoSuchFile, e:
804
                if mode != 'w' or not create:
805
                    raise
806
                self.write_header()
807
        finally:
808
            pb.update('read knit index', total, total)
809
            pb.finished()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
810
1594.2.8 by Robert Collins
add ghost aware apis to knits.
811
    def _parse_parents(self, compressed_parents):
812
        """convert a list of string parent values into version ids.
813
814
        ints are looked up in the index.
815
        .FOO values are ghosts and converted in to FOO.
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
816
817
        NOTE: the function is retained here for clarity, and for possible
818
              use in partial index reads. However bulk processing now has
819
              it inlined in __init__ for inner-loop optimisation.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
820
        """
821
        result = []
822
        for value in compressed_parents:
1596.2.15 by Robert Collins
Microprofiling of knit parsing.
823
            if value[-1] == '.':
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
824
                # uncompressed reference
1594.2.8 by Robert Collins
add ghost aware apis to knits.
825
                result.append(value[1:])
826
            else:
1596.2.15 by Robert Collins
Microprofiling of knit parsing.
827
                # this is 15/4000ms faster than isinstance,
828
                # this function is called thousands of times a 
829
                # second so small variations add up.
830
                assert value.__class__ is str
1596.2.11 by Robert Collins
Remove utf8 debugging code
831
                result.append(self._history[int(value)])
1594.2.8 by Robert Collins
add ghost aware apis to knits.
832
        return result
833
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
834
    def get_graph(self):
835
        graph = []
836
        for version_id, index in self._cache.iteritems():
837
            graph.append((version_id, index[4]))
838
        return graph
839
840
    def get_ancestry(self, versions):
841
        """See VersionedFile.get_ancestry."""
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
842
        # get a graph of all the mentioned versions:
843
        graph = {}
844
        pending = set(versions)
845
        while len(pending):
846
            version = pending.pop()
847
            parents = self._cache[version][4]
1594.2.8 by Robert Collins
add ghost aware apis to knits.
848
            # got the parents ok
849
            # trim ghosts
850
            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.
851
            for parent in parents:
1594.2.8 by Robert Collins
add ghost aware apis to knits.
852
                # 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.
853
                if parent not in graph:
854
                    pending.add(parent)
855
            graph[version] = parents
856
        return topo_sort(graph.items())
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
857
1594.2.8 by Robert Collins
add ghost aware apis to knits.
858
    def get_ancestry_with_ghosts(self, versions):
859
        """See VersionedFile.get_ancestry_with_ghosts."""
860
        # get a graph of all the mentioned versions:
861
        graph = {}
862
        pending = set(versions)
863
        while len(pending):
864
            version = pending.pop()
865
            try:
866
                parents = self._cache[version][4]
867
            except KeyError:
868
                # ghost, fake it
869
                graph[version] = []
870
                pass
871
            else:
872
                # got the parents ok
873
                for parent in parents:
874
                    if parent not in graph:
875
                        pending.add(parent)
876
                graph[version] = parents
877
        return topo_sort(graph.items())
878
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
879
    def num_versions(self):
880
        return len(self._history)
881
882
    __len__ = num_versions
883
884
    def get_versions(self):
885
        return self._history
886
887
    def idx_to_name(self, idx):
888
        return self._history[idx]
889
890
    def lookup(self, version_id):
891
        assert version_id in self._cache
892
        return self._history.index(version_id)
893
1594.2.8 by Robert Collins
add ghost aware apis to knits.
894
    def _version_list_to_index(self, versions):
895
        result_list = []
896
        for version in versions:
897
            if version in self._cache:
898
                result_list.append(str(self._history.index(version)))
899
            else:
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
900
                result_list.append('.' + version.encode('utf-8'))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
901
        return ' '.join(result_list)
902
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
903
    def add_version(self, version_id, options, pos, size, parents):
904
        """Add a version record to the index."""
905
        self._cache_version(version_id, options, pos, size, parents)
906
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
907
        content = "%s %s %s %s %s\n" % (version_id.encode('utf-8'),
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
908
                                        ','.join(options),
909
                                        pos,
910
                                        size,
1594.2.8 by Robert Collins
add ghost aware apis to knits.
911
                                        self._version_list_to_index(parents))
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
912
        assert isinstance(content, str), 'content must be utf-8 encoded'
1563.2.13 by Robert Collins
InterVersionedFile implemented.
913
        self._transport.append(self._filename, StringIO(content))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
914
915
    def has_version(self, version_id):
916
        """True if the version is in the index."""
917
        return self._cache.has_key(version_id)
918
919
    def get_position(self, version_id):
920
        """Return data position and size of specified version."""
921
        return (self._cache[version_id][2], \
922
                self._cache[version_id][3])
923
924
    def get_method(self, version_id):
925
        """Return compression method of specified version."""
926
        options = self._cache[version_id][1]
927
        if 'fulltext' in options:
928
            return 'fulltext'
929
        else:
930
            assert 'line-delta' in options
931
            return 'line-delta'
932
933
    def get_options(self, version_id):
934
        return self._cache[version_id][1]
935
936
    def get_parents(self, version_id):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
937
        """Return parents of specified version ignoring ghosts."""
938
        return [parent for parent in self._cache[version_id][4] 
939
                if parent in self._cache]
940
941
    def get_parents_with_ghosts(self, version_id):
942
        """Return parents of specified version wth ghosts."""
943
        return self._cache[version_id][4] 
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
944
945
    def check_versions_present(self, version_ids):
946
        """Check that all specified versions are present."""
947
        version_ids = set(version_ids)
948
        for version_id in list(version_ids):
949
            if version_id in self._cache:
950
                version_ids.remove(version_id)
951
        if version_ids:
952
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
953
954
955
class _KnitData(_KnitComponentFile):
956
    """Contents of the knit data file"""
957
958
    HEADER = "# bzr knit data 7\n"
959
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
960
    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.
961
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
962
        self._file = None
963
        self._checked = False
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
964
        if create:
965
            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.
966
        self._records = {}
967
968
    def clear_cache(self):
969
        """Clear the record cache."""
970
        self._records = {}
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
971
972
    def _open_file(self):
973
        if self._file is None:
974
            try:
975
                self._file = self._transport.get(self._filename)
976
            except NoSuchFile:
977
                pass
978
        return self._file
979
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
980
    def _record_to_data(self, version_id, digest, lines):
981
        """Convert version_id, digest, lines into a raw data block.
982
        
983
        :return: (len, a StringIO instance with the raw data ready to read.)
984
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
985
        sio = StringIO()
986
        data_file = GzipFile(None, mode='wb', fileobj=sio)
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
987
        print >>data_file, "version %s %d %s" % (version_id.encode('utf-8'), len(lines), digest)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
988
        data_file.writelines(lines)
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
989
        print >>data_file, "end %s\n" % version_id.encode('utf-8')
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
990
        data_file.close()
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
991
        length= sio.tell()
992
        sio.seek(0)
993
        return length, sio
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
994
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
995
    def add_raw_record(self, raw_data):
996
        """Append a prepared record to the data file."""
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
997
        assert isinstance(raw_data, str), 'data must be plain bytes'
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
998
        start_pos = self._transport.append(self._filename, StringIO(raw_data))
999
        return start_pos, len(raw_data)
1000
        
1001
    def add_record(self, version_id, digest, lines):
1002
        """Write new text record to disk.  Returns the position in the
1003
        file where it was written."""
1004
        size, sio = self._record_to_data(version_id, digest, lines)
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1005
        # cache
1006
        self._records[version_id] = (digest, lines)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1007
        # write to disk
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1008
        start_pos = self._transport.append(self._filename, sio)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1009
        return start_pos, size
1010
1011
    def _parse_record_header(self, version_id, raw_data):
1012
        """Parse a record header for consistency.
1013
1014
        :return: the header and the decompressor stream.
1015
                 as (stream, header_record)
1016
        """
1017
        df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1018
        rec = df.readline().split()
1019
        if len(rec) != 4:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1020
            raise KnitCorrupt(self._filename, 'unexpected number of elements in record header')
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1021
        if rec[1].decode('utf-8')!= version_id:
1594.3.3 by Robert Collins
Bugfix error message output in knit error raising.
1022
            raise KnitCorrupt(self._filename, 
1594.3.4 by Robert Collins
Change urllib ranges implementation to be one coalesced range per http request.
1023
                              'unexpected version, wanted %r, got %r' % (
1024
                                version_id, rec[1]))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1025
        return df, rec
1026
1027
    def _parse_record(self, version_id, data):
1028
        df, rec = self._parse_record_header(version_id, data)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1029
        lines = int(rec[2])
1030
        record_contents = self._read_record_contents(df, lines)
1031
        l = df.readline()
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1032
        if l.decode('utf-8') != 'end %s\n' % version_id:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1033
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
1034
                        % (l, version_id))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1035
        df.close()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1036
        return record_contents, rec[3]
1037
1038
    def _read_record_contents(self, df, record_lines):
1039
        """Read and return n lines from datafile."""
1040
        r = []
1041
        for i in range(record_lines):
1042
            r.append(df.readline())
1043
        return r
1044
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1045
    def read_records_iter_raw(self, records):
1046
        """Read text records from data file and yield raw data.
1047
1048
        This unpacks enough of the text record to validate the id is
1049
        as expected but thats all.
1050
1051
        It will actively recompress currently cached records on the
1052
        basis that that is cheaper than I/O activity.
1053
        """
1054
        needed_records = []
1055
        for version_id, pos, size in records:
1056
            if version_id not in self._records:
1057
                needed_records.append((version_id, pos, size))
1058
1059
        # setup an iterator of the external records:
1060
        # uses readv so nice and fast we hope.
1061
        if len(needed_records):
1062
            # grab the disk data needed.
1063
            raw_records = self._transport.readv(self._filename,
1064
                [(pos, size) for version_id, pos, size in needed_records])
1065
1066
        for version_id, pos, size in records:
1067
            if version_id in self._records:
1068
                # compress a new version
1069
                size, sio = self._record_to_data(version_id,
1070
                                                 self._records[version_id][0],
1071
                                                 self._records[version_id][1])
1072
                yield version_id, sio.getvalue()
1073
            else:
1074
                pos, data = raw_records.next()
1075
                # validate the header
1076
                df, rec = self._parse_record_header(version_id, data)
1077
                df.close()
1078
                yield version_id, data
1079
1080
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1081
    def read_records_iter(self, records):
1082
        """Read text records from data file and yield result.
1083
1084
        Each passed record is a tuple of (version_id, pos, len) and
1085
        will be read in the given order.  Yields (version_id,
1086
        contents, digest).
1087
        """
1088
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1089
        needed_records = []
1090
        for version_id, pos, size in records:
1091
            if version_id not in self._records:
1092
                needed_records.append((version_id, pos, size))
1093
1094
        if len(needed_records):
1095
            # We take it that the transport optimizes the fetching as good
1096
            # as possible (ie, reads continous ranges.)
1097
            response = self._transport.readv(self._filename,
1098
                [(pos, size) for version_id, pos, size in needed_records])
1099
1594.3.5 by Robert Collins
Bugfix knit caching implementation.
1100
            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.
1101
                content, digest = self._parse_record(record_id, data)
1102
                self._records[record_id] = (digest, content)
1103
    
1104
        for version_id, pos, size in records:
1105
            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.
1106
1107
    def read_records(self, records):
1108
        """Read records into a dictionary."""
1109
        components = {}
1110
        for record_id, content, digest in self.read_records_iter(records):
1111
            components[record_id] = (content, digest)
1112
        return components
1113
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1114
1115
class InterKnit(InterVersionedFile):
1116
    """Optimised code paths for knit to knit operations."""
1117
    
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1118
    _matching_file_factory = KnitVersionedFile
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1119
    
1120
    @staticmethod
1121
    def is_compatible(source, target):
1122
        """Be compatible with knits.  """
1123
        try:
1124
            return (isinstance(source, KnitVersionedFile) and
1125
                    isinstance(target, KnitVersionedFile))
1126
        except AttributeError:
1127
            return False
1128
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1129
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1130
        """See InterVersionedFile.join."""
1131
        assert isinstance(self.source, KnitVersionedFile)
1132
        assert isinstance(self.target, KnitVersionedFile)
1133
1134
        if version_ids is None:
1135
            version_ids = self.source.versions()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1136
        else:
1137
            if not ignore_missing:
1138
                self.source._check_versions_present(version_ids)
1139
            else:
1140
                version_ids = set(self.source.versions()).intersection(
1141
                    set(version_ids))
1142
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1143
        if not version_ids:
1144
            return 0
1145
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1146
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1147
        try:
1148
            version_ids = list(version_ids)
1149
            if None in version_ids:
1150
                version_ids.remove(None)
1151
    
1152
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
1153
            this_versions = set(self.target._index.get_versions())
1154
            needed_versions = self.source_ancestry - this_versions
1155
            cross_check_versions = self.source_ancestry.intersection(this_versions)
1156
            mismatched_versions = set()
1157
            for version in cross_check_versions:
1158
                # scan to include needed parents.
1159
                n1 = set(self.target.get_parents_with_ghosts(version))
1160
                n2 = set(self.source.get_parents_with_ghosts(version))
1161
                if n1 != n2:
1162
                    # FIXME TEST this check for cycles being introduced works
1163
                    # the logic is we have a cycle if in our graph we are an
1164
                    # ancestor of any of the n2 revisions.
1165
                    for parent in n2:
1166
                        if parent in n1:
1167
                            # safe
1168
                            continue
1169
                        else:
1170
                            parent_ancestors = self.source.get_ancestry(parent)
1171
                            if version in parent_ancestors:
1172
                                raise errors.GraphCycleError([parent, version])
1173
                    # ensure this parent will be available later.
1174
                    new_parents = n2.difference(n1)
1175
                    needed_versions.update(new_parents.difference(this_versions))
1176
                    mismatched_versions.add(version)
1177
    
1178
            if not needed_versions and not cross_check_versions:
1179
                return 0
1180
            full_list = topo_sort(self.source.get_graph())
1181
    
1182
            version_list = [i for i in full_list if (not self.target.has_version(i)
1183
                            and i in needed_versions)]
1184
    
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1185
            # plan the join:
1186
            copy_queue = []
1187
            copy_queue_records = []
1188
            copy_set = set()
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1189
            for version_id in version_list:
1190
                options = self.source._index.get_options(version_id)
1191
                parents = self.source._index.get_parents_with_ghosts(version_id)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1192
                # check that its will be a consistent copy:
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1193
                for parent in parents:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1194
                    # if source has the parent, we must :
1195
                    # * already have it or
1196
                    # * have it scheduled already
1197
                    # otherwise we dont care
1198
                    assert (self.target.has_version(parent) or
1199
                            parent in copy_set or
1200
                            not self.source.has_version(parent))
1201
                data_pos, data_size = self.source._index.get_position(version_id)
1202
                copy_queue_records.append((version_id, data_pos, data_size))
1203
                copy_queue.append((version_id, options, parents))
1204
                copy_set.add(version_id)
1205
1206
            # data suck the join:
1207
            count = 0
1208
            total = len(version_list)
1209
            # we want the raw gzip for bulk copying, but the record validated
1210
            # just enough to be sure its the right one.
1211
            # TODO: consider writev or write combining to reduce 
1212
            # death of a thousand cuts feeling.
1213
            for (version_id, raw_data), \
1214
                (version_id2, options, parents) in \
1215
                izip(self.source._data.read_records_iter_raw(copy_queue_records),
1216
                     copy_queue):
1217
                assert version_id == version_id2, 'logic error, inconsistent results'
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1218
                count = count + 1
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1219
                pb.update("Joining knit", count, total)
1220
                pos, size = self.target._data.add_raw_record(raw_data)
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1221
                self.target._index.add_version(version_id, options, pos, size, parents)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1222
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1223
            for version in mismatched_versions:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1224
                # FIXME RBC 20060309 is this needed?
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1225
                n1 = set(self.target.get_parents_with_ghosts(version))
1226
                n2 = set(self.source.get_parents_with_ghosts(version))
1227
                # write a combined record to our history preserving the current 
1228
                # parents as first in the list
1229
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1230
                self.target.fix_parents(version, new_parents)
1231
            return count
1232
        finally:
1233
            pb.finished()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1234
1235
1236
InterVersionedFile.register_optimiser(InterKnit)
1596.2.24 by Robert Collins
Gzipfile was slightly slower than ideal.
1237
1238
1239
# make GzipFile faster:
1240
import zlib
1241
class GzipFile(gzip.GzipFile):
1242
    """Knit tuned version of GzipFile.
1243
1244
    This is based on the following lsprof stats:
1245
    python 2.4 stock GzipFile write:
1246
    58971      0   5644.3090   2721.4730   gzip:193(write)
1247
    +58971     0   1159.5530   1159.5530   +<built-in method compress>
1248
    +176913    0    987.0320    987.0320   +<len>
1249
    +58971     0    423.1450    423.1450   +<zlib.crc32>
1250
    +58971     0    353.1060    353.1060   +<method 'write' of 'cStringIO.
1251
                                            StringO' objects>
1252
    tuned GzipFile write:
1253
    58971      0   4477.2590   2103.1120   bzrlib.knit:1250(write)
1254
    +58971     0   1297.7620   1297.7620   +<built-in method compress>
1255
    +58971     0    406.2160    406.2160   +<zlib.crc32>
1256
    +58971     0    341.9020    341.9020   +<method 'write' of 'cStringIO.
1257
                                            StringO' objects>
1258
    +58971     0    328.2670    328.2670   +<len>
1259
1260
1261
    Yes, its only 1.6 seconds, but they add up.
1262
    """
1263
1264
1265
    def write(self, data):
1266
        if self.mode != gzip.WRITE:
1267
            import errno
1268
            raise IOError(errno.EBADF, "write() on read-only GzipFile object")
1269
1270
        if self.fileobj is None:
1271
            raise ValueError, "write() on closed GzipFile object"
1272
        data_len = len(data)
1273
        if data_len > 0:
1274
            self.size = self.size + data_len
1275
            self.crc = zlib.crc32(data, self.crc)
1276
            self.fileobj.write( self.compress.compress(data) )
1277
            self.offset += data_len
1278
1596.2.26 by Robert Collins
gzip.writelines was unreasonably slow.
1279
    def writelines(self, lines):
1280
        # profiling indicated a significant overhead 
1281
        # calling write for each line.
1282
        # this batch call is a lot faster :).
1283
        # (4 seconds to 1 seconds for the sample upgrades I was testing).
1284
        self.write(''.join(lines))