/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
# Written by Martin Pool.
3
# Modified by Johan Rydberg <jrydberg@gnu.org>
4
# Modified by Robert Collins <robert.collins@canonical.com>
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20
"""Knit versionedfile implementation.
21
22
A knit is a versioned file implementation that supports efficient append only
23
updates.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
24
25
Knit file layout:
26
lifeless: the data file is made up of "delta records".  each delta record has a delta header 
27
that contains; (1) a version id, (2) the size of the delta (in lines), and (3)  the digest of 
28
the -expanded data- (ie, the delta applied to the parent).  the delta also ends with a 
29
end-marker; simply "end VERSION"
30
31
delta can be line or full contents.a
32
... the 8's there are the index number of the annotation.
33
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
34
59,59,3
35
8
36
8         if ie.executable:
37
8             e.set('executable', 'yes')
38
130,130,2
39
8         if elt.get('executable') == 'yes':
40
8             ie.executable = True
41
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 
42
43
44
whats in an index:
45
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
46
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
47
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
48
09:33 < lifeless> right
49
09:33 < jrydberg> lifeless: the position and size is the range in the data file
50
51
52
so the index sequence is the dictionary compressed sequence number used
53
in the deltas to provide line annotation
54
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
55
"""
56
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
57
# TODOS:
58
# 10:16 < lifeless> make partial index writes safe
59
# 10:16 < lifeless> implement 'knit.check()' like weave.check()
60
# 10:17 < lifeless> record known ghosts so we can detect when they are filled in rather than the current 'reweave 
61
#                    always' approach.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
62
# move sha1 out of the content so that join is faster at verifying parents
63
# record content length ?
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
64
                  
65
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
66
from copy import copy
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
67
from cStringIO import StringIO
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
68
import difflib
1596.2.28 by Robert Collins
more knit profile based tuning.
69
from itertools import izip, chain
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
70
import os
1628.1.2 by Robert Collins
More knit micro-optimisations.
71
import sys
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
72
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
73
import bzrlib
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
74
import bzrlib.errors as errors
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
75
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
76
        InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
77
        RevisionNotPresent, RevisionAlreadyPresent
1641.1.1 by Robert Collins
* Various microoptimisations to knit and gzip - reducing function call
78
from bzrlib.tuned_gzip import *
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
79
from bzrlib.trace import mutter
80
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
81
     sha_strings
1563.2.13 by Robert Collins
InterVersionedFile implemented.
82
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
83
from bzrlib.tsort import topo_sort
84
85
86
# TODO: Split out code specific to this format into an associated object.
87
88
# TODO: Can we put in some kind of value to check that the index and data
89
# files belong together?
90
91
# TODO: accomodate binaries, perhaps by storing a byte count
92
93
# TODO: function to check whole file
94
95
# TODO: atomically append data, then measure backwards from the cursor
96
# position after writing to work out where it was located.  we may need to
97
# bypass python file buffering.
98
99
DATA_SUFFIX = '.knit'
100
INDEX_SUFFIX = '.kndx'
101
102
103
class KnitContent(object):
104
    """Content of a knit version to which deltas can be applied."""
105
106
    def __init__(self, lines):
107
        self._lines = lines
108
109
    def annotate_iter(self):
110
        """Yield tuples of (origin, text) for each content line."""
111
        for origin, text in self._lines:
112
            yield origin, text
113
114
    def annotate(self):
115
        """Return a list of (origin, text) tuples."""
116
        return list(self.annotate_iter())
117
118
    def line_delta_iter(self, new_lines):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
119
        """Generate line-based delta from this content to new_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
120
        new_texts = [text for origin, text in new_lines._lines]
121
        old_texts = [text for origin, text in self._lines]
1596.2.35 by Robert Collins
Subclass SequenceMatcher to get a slightly faster (in our case) find_longest_match routine.
122
        s = SequenceMatcher(None, old_texts, new_texts)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
123
        for op in s.get_opcodes():
124
            if op[0] == 'equal':
125
                continue
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
126
            #     ofrom   oto   length        data
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
127
            yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
128
129
    def line_delta(self, new_lines):
130
        return list(self.line_delta_iter(new_lines))
131
132
    def text(self):
133
        return [text for origin, text in self._lines]
134
135
136
class _KnitFactory(object):
137
    """Base factory for creating content objects."""
138
139
    def make(self, lines, version):
140
        num_lines = len(lines)
141
        return KnitContent(zip([version] * num_lines, lines))
142
143
144
class KnitAnnotateFactory(_KnitFactory):
145
    """Factory for creating annotated Content objects."""
146
147
    annotated = True
148
149
    def parse_fulltext(self, content, version):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
150
        """Convert fulltext to internal representation
151
152
        fulltext content is of the format
153
        revid(utf8) plaintext\n
154
        internal representation is of the format:
155
        (revid, plaintext)
156
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
157
        lines = []
158
        for line in content:
159
            origin, text = line.split(' ', 1)
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
160
            lines.append((origin.decode('utf-8'), text))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
161
        return KnitContent(lines)
162
163
    def parse_line_delta_iter(self, lines):
1628.1.2 by Robert Collins
More knit micro-optimisations.
164
        for result_item in self.parse_line_delta[lines]:
165
            yield result_item
166
167
    def parse_line_delta(self, lines, version):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
168
        """Convert a line based delta into internal representation.
169
170
        line delta is in the form of:
171
        intstart intend intcount
172
        1..count lines:
173
        revid(utf8) newline\n
174
        internal represnetation is
175
        (start, end, count, [1..count tuples (revid, newline)])
176
        """
1628.1.2 by Robert Collins
More knit micro-optimisations.
177
        result = []
178
        lines = iter(lines)
179
        next = lines.next
180
        # walk through the lines parsing.
181
        for header in lines:
182
            start, end, count = [int(n) for n in header.split(',')]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
183
            contents = []
1628.1.2 by Robert Collins
More knit micro-optimisations.
184
            remaining = count
185
            while remaining:
186
                origin, text = next().split(' ', 1)
187
                remaining -= 1
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
188
                contents.append((origin.decode('utf-8'), text))
1628.1.2 by Robert Collins
More knit micro-optimisations.
189
            result.append((start, end, count, contents))
190
        return result
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
1628.1.2 by Robert Collins
More knit micro-optimisations.
202
        See parse_line_delta which this inverts.
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
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
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
292
    def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
293
        """See VersionedFile._add_delta()."""
294
        self._check_add(version_id, []) # should we check the lines ?
295
        self._check_versions_present(parents)
296
        present_parents = []
297
        ghosts = []
298
        parent_texts = {}
299
        for parent in parents:
300
            if not self.has_version(parent):
301
                ghosts.append(parent)
302
            else:
303
                present_parents.append(parent)
304
305
        if delta_parent is None:
306
            # reconstitute as full text.
307
            assert len(delta) == 1 or len(delta) == 0
308
            if len(delta):
309
                assert delta[0][0] == 0
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
310
                assert delta[0][1] == 0, delta[0][1]
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
311
            return super(KnitVersionedFile, self)._add_delta(version_id,
312
                                                             parents,
313
                                                             delta_parent,
314
                                                             sha1,
315
                                                             noeol,
316
                                                             delta)
317
318
        digest = sha1
319
320
        options = []
321
        if noeol:
322
            options.append('no-eol')
323
324
        if delta_parent is not None:
325
            # determine the current delta chain length.
326
            # To speed the extract of texts the delta chain is limited
327
            # to a fixed number of deltas.  This should minimize both
328
            # I/O and the time spend applying deltas.
329
            count = 0
330
            delta_parents = [delta_parent]
331
            while count < 25:
332
                parent = delta_parents[0]
333
                method = self._index.get_method(parent)
334
                if method == 'fulltext':
335
                    break
336
                delta_parents = self._index.get_parents(parent)
337
                count = count + 1
338
            if method == 'line-delta':
339
                # did not find a fulltext in the delta limit.
340
                # just do a normal insertion.
341
                return super(KnitVersionedFile, self)._add_delta(version_id,
342
                                                                 parents,
343
                                                                 delta_parent,
344
                                                                 sha1,
345
                                                                 noeol,
346
                                                                 delta)
347
348
        options.append('line-delta')
349
        store_lines = self.factory.lower_line_delta(delta)
350
351
        where, size = self._data.add_record(version_id, digest, store_lines)
352
        self._index.add_version(version_id, options, where, size, parents)
353
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
354
    def clear_cache(self):
355
        """Clear the data cache only."""
356
        self._data.clear_cache()
357
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
358
    def copy_to(self, name, transport):
359
        """See VersionedFile.copy_to()."""
360
        # copy the current index to a temp index to avoid racing with local
361
        # writes
362
        transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
363
        # copy the data file
364
        transport.put(name + DATA_SUFFIX, self._data._open_file())
365
        # rename the copied index into place
366
        transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
367
1563.2.13 by Robert Collins
InterVersionedFile implemented.
368
    def create_empty(self, name, transport, mode=None):
1563.2.25 by Robert Collins
Merge in upstream.
369
        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.
370
    
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
371
    def _fix_parents(self, version, new_parents):
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
372
        """Fix the parents list for version.
373
        
374
        This is done by appending a new version to the index
375
        with identical data except for the parents list.
376
        the parents list must be a superset of the current
377
        list.
378
        """
379
        current_values = self._index._cache[version]
380
        assert set(current_values[4]).difference(set(new_parents)) == set()
381
        self._index.add_version(version,
382
                                current_values[1], 
383
                                current_values[2],
384
                                current_values[3],
385
                                new_parents)
386
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
387
    def get_delta(self, version_id):
388
        """Get a delta for constructing version from some other version."""
389
        if not self.has_version(version_id):
390
            raise RevisionNotPresent(version_id, self.filename)
391
        
392
        parents = self.get_parents(version_id)
393
        if len(parents):
394
            parent = parents[0]
395
        else:
396
            parent = None
397
        data_pos, data_size = self._index.get_position(version_id)
398
        data, sha1 = self._data.read_records(((version_id, data_pos, data_size),))[version_id]
399
        version_idx = self._index.lookup(version_id)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
400
        noeol = 'no-eol' in self._index.get_options(version_id)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
401
        if 'fulltext' == self._index.get_method(version_id):
402
            new_content = self.factory.parse_fulltext(data, version_idx)
403
            if parent is not None:
404
                reference_content = self._get_content(parent)
405
                old_texts = reference_content.text()
406
            else:
407
                old_texts = []
408
            new_texts = new_content.text()
409
            delta_seq = SequenceMatcher(None, old_texts, new_texts)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
410
            return parent, sha1, noeol, self._make_line_delta(delta_seq, new_content)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
411
        else:
412
            delta = self.factory.parse_line_delta(data, version_idx)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
413
            return parent, sha1, noeol, delta
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
414
        
1594.2.8 by Robert Collins
add ghost aware apis to knits.
415
    def get_graph_with_ghosts(self):
416
        """See VersionedFile.get_graph_with_ghosts()."""
417
        graph_items = self._index.get_graph()
418
        return dict(graph_items)
419
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
420
    @staticmethod
421
    def get_suffixes():
422
        """See VersionedFile.get_suffixes()."""
423
        return [DATA_SUFFIX, INDEX_SUFFIX]
1563.2.13 by Robert Collins
InterVersionedFile implemented.
424
1594.2.8 by Robert Collins
add ghost aware apis to knits.
425
    def has_ghost(self, version_id):
426
        """True if there is a ghost reference in the file to version_id."""
427
        # maybe we have it
428
        if self.has_version(version_id):
429
            return False
430
        # optimisable if needed by memoising the _ghosts set.
431
        items = self._index.get_graph()
432
        for node, parents in items:
433
            for parent in parents:
434
                if parent not in self._index._cache:
435
                    if parent == version_id:
436
                        return True
437
        return False
438
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
439
    def versions(self):
440
        """See VersionedFile.versions."""
441
        return self._index.get_versions()
442
443
    def has_version(self, version_id):
444
        """See VersionedFile.has_version."""
445
        return self._index.has_version(version_id)
446
447
    __contains__ = has_version
448
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
449
    def _merge_annotations(self, content, parents, parent_texts={},
450
                           delta=None, annotated=None):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
451
        """Merge annotations for content.  This is done by comparing
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
452
        the annotations based on changed to the text.
453
        """
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
454
        if annotated:
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
455
            delta_seq = None
456
            for parent_id in parents:
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
457
                merge_content = self._get_content(parent_id, parent_texts)
458
                seq = SequenceMatcher(None, merge_content.text(), content.text())
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
459
                if delta_seq is None:
460
                    # setup a delta seq to reuse.
461
                    delta_seq = seq
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
462
                for i, j, n in seq.get_matching_blocks():
463
                    if n == 0:
464
                        continue
465
                    # this appears to copy (origin, text) pairs across to the new
466
                    # content for any line that matches the last-checked parent.
467
                    # FIXME: save the sequence control data for delta compression
468
                    # against the most relevant parent rather than rediffing.
469
                    content._lines[j:j+n] = merge_content._lines[i:i+n]
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
470
        if delta:
471
            if not annotated:
472
                reference_content = self._get_content(parents[0], parent_texts)
473
                new_texts = content.text()
474
                old_texts = reference_content.text()
475
                delta_seq = SequenceMatcher(None, old_texts, new_texts)
476
            return self._make_line_delta(delta_seq, content)
477
478
    def _make_line_delta(self, delta_seq, new_content):
479
        """Generate a line delta from delta_seq and new_content."""
480
        diff_hunks = []
481
        for op in delta_seq.get_opcodes():
482
            if op[0] == 'equal':
483
                continue
484
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
485
        return diff_hunks
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
486
487
    def _get_components(self, version_id):
488
        """Return a list of (version_id, method, data) tuples that
489
        makes up version specified by version_id of the knit.
490
491
        The components should be applied in the order of the returned
492
        list.
493
494
        The basis knit will be used to the largest extent possible
495
        since it is assumed that accesses to it is faster.
496
        """
1628.1.2 by Robert Collins
More knit micro-optimisations.
497
        #profile notes:
498
        # 4168 calls in 14912, 2289 internal
499
        # 4168 in 9711 to read_records
500
        # 52554 in 1250 to get_parents
501
        # 170166 in 865 to list.append
502
        
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
503
        # needed_revisions holds a list of (method, version_id) of
504
        # versions that is needed to be fetched to construct the final
505
        # version of the file.
506
        #
507
        # basis_revisions is a list of versions that needs to be
508
        # fetched but exists in the basis knit.
509
510
        basis = self.basis_knit
511
        needed_versions = []
512
        basis_versions = []
513
        cursor = version_id
514
515
        while 1:
516
            picked_knit = self
517
            if basis and basis._index.has_version(cursor):
518
                picked_knit = basis
519
                basis_versions.append(cursor)
520
            method = picked_knit._index.get_method(cursor)
521
            needed_versions.append((method, cursor))
522
            if method == 'fulltext':
523
                break
524
            cursor = picked_knit.get_parents(cursor)[0]
525
526
        components = {}
527
        if basis_versions:
528
            records = []
529
            for comp_id in basis_versions:
530
                data_pos, data_size = basis._index.get_data_position(comp_id)
531
                records.append((piece_id, data_pos, data_size))
532
            components.update(basis._data.read_records(records))
533
534
        records = []
535
        for comp_id in [vid for method, vid in needed_versions
536
                        if vid not in basis_versions]:
537
            data_pos, data_size = self._index.get_position(comp_id)
538
            records.append((comp_id, data_pos, data_size))
539
        components.update(self._data.read_records(records))
540
541
        # get_data_records returns a mapping with the version id as
542
        # index and the value as data.  The order the components need
543
        # to be applied is held by needed_versions (reversed).
544
        out = []
545
        for method, comp_id in reversed(needed_versions):
546
            out.append((comp_id, method, components[comp_id]))
547
548
        return out
549
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
550
    def _get_content(self, version_id, parent_texts={}):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
551
        """Returns a content object that makes up the specified
552
        version."""
553
        if not self.has_version(version_id):
554
            raise RevisionNotPresent(version_id, self.filename)
555
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
556
        cached_version = parent_texts.get(version_id, None)
557
        if cached_version is not None:
558
            return cached_version
559
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
560
        if self.basis_knit and version_id in self.basis_knit:
561
            return self.basis_knit._get_content(version_id)
562
563
        content = None
564
        components = self._get_components(version_id)
565
        for component_id, method, (data, digest) in components:
566
            version_idx = self._index.lookup(component_id)
567
            if method == 'fulltext':
568
                assert content is None
569
                content = self.factory.parse_fulltext(data, version_idx)
570
            elif method == 'line-delta':
571
                delta = self.factory.parse_line_delta(data, version_idx)
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
572
                content._lines = self._apply_delta(content._lines, delta)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
573
574
        if 'no-eol' in self._index.get_options(version_id):
575
            line = content._lines[-1][1].rstrip('\n')
576
            content._lines[-1] = (content._lines[-1][0], line)
577
578
        if sha_strings(content.text()) != digest:
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
579
            import pdb;pdb.set_trace()
580
            raise KnitCorrupt(self.filename, 'sha-1 does not match %s' % version_id)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
581
582
        return content
583
584
    def _check_versions_present(self, version_ids):
585
        """Check that all specified versions are present."""
586
        version_ids = set(version_ids)
587
        for r in list(version_ids):
588
            if self._index.has_version(r):
589
                version_ids.remove(r)
590
        if version_ids:
591
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
592
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
593
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
594
        """See VersionedFile.add_lines_with_ghosts()."""
595
        self._check_add(version_id, lines)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
596
        return self._add(version_id, lines[:], parents, self.delta, parent_texts)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
597
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
598
    def _add_lines(self, version_id, parents, lines, parent_texts):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
599
        """See VersionedFile.add_lines."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
600
        self._check_add(version_id, lines)
601
        self._check_versions_present(parents)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
602
        return self._add(version_id, lines[:], parents, self.delta, parent_texts)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
603
604
    def _check_add(self, version_id, lines):
605
        """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.
606
        assert self.writable, "knit is not opened for write"
607
        ### FIXME escape. RBC 20060228
608
        if contains_whitespace(version_id):
609
            raise InvalidRevisionId(version_id)
610
        if self.has_version(version_id):
611
            raise RevisionAlreadyPresent(version_id, self.filename)
612
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
613
        if False or __debug__:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
614
            for l in lines:
615
                assert '\n' not in l[:-1]
616
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
617
    def _add(self, version_id, lines, parents, delta, parent_texts):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
618
        """Add a set of lines on top of version specified by parents.
619
620
        If delta is true, compress the text as a line-delta against
621
        the first parent.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
622
623
        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.
624
        """
1596.2.28 by Robert Collins
more knit profile based tuning.
625
        #  461    0   6546.0390     43.9100   bzrlib.knit:489(_add)
626
        # +400    0    889.4890    418.9790   +bzrlib.knit:192(lower_fulltext)
627
        # +461    0   1364.8070    108.8030   +bzrlib.knit:996(add_record)
628
        # +461    0    193.3940     41.5720   +bzrlib.knit:898(add_version)
629
        # +461    0    134.0590     18.3810   +bzrlib.osutils:361(sha_strings)
630
        # +461    0     36.3420     15.4540   +bzrlib.knit:146(make)
631
        # +1383   0      8.0370      8.0370   +<len>
632
        # +61     0     13.5770      7.9190   +bzrlib.knit:199(lower_line_delta)
633
        # +61     0    963.3470      7.8740   +bzrlib.knit:427(_get_content)
634
        # +61     0    973.9950      5.2950   +bzrlib.knit:136(line_delta)
635
        # +61     0   1918.1800      5.2640   +bzrlib.knit:359(_merge_annotations)
636
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
637
        present_parents = []
1594.2.8 by Robert Collins
add ghost aware apis to knits.
638
        ghosts = []
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
639
        if parent_texts is None:
640
            parent_texts = {}
1594.2.8 by Robert Collins
add ghost aware apis to knits.
641
        for parent in parents:
642
            if not self.has_version(parent):
643
                ghosts.append(parent)
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
644
            else:
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
645
                present_parents.append(parent)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
646
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
647
        if delta and not len(present_parents):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
648
            delta = False
649
650
        digest = sha_strings(lines)
651
        options = []
652
        if lines:
653
            if lines[-1][-1] != '\n':
654
                options.append('no-eol')
655
                lines[-1] = lines[-1] + '\n'
656
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
657
        if len(present_parents) and delta:
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
658
            # To speed the extract of texts the delta chain is limited
659
            # to a fixed number of deltas.  This should minimize both
660
            # I/O and the time spend applying deltas.
661
            count = 0
1596.2.10 by Robert Collins
Reviewer feedback on knit branches.
662
            delta_parents = present_parents
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
663
            while count < 25:
664
                parent = delta_parents[0]
665
                method = self._index.get_method(parent)
666
                if method == 'fulltext':
667
                    break
668
                delta_parents = self._index.get_parents(parent)
669
                count = count + 1
670
            if method == 'line-delta':
671
                delta = False
672
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
673
        lines = self.factory.make(lines, version_id)
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
674
        if delta or (self.factory.annotated and len(present_parents) > 0):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
675
            # Merge annotations from parent texts if so is needed.
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
676
            delta_hunks = self._merge_annotations(lines, present_parents, parent_texts,
677
                                                  delta, self.factory.annotated)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
678
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
679
        if delta:
680
            options.append('line-delta')
681
            store_lines = self.factory.lower_line_delta(delta_hunks)
682
        else:
683
            options.append('fulltext')
684
            store_lines = self.factory.lower_fulltext(lines)
685
686
        where, size = self._data.add_record(version_id, digest, store_lines)
687
        self._index.add_version(version_id, options, where, size, parents)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
688
        return lines
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
689
1563.2.19 by Robert Collins
stub out a check for knits.
690
    def check(self, progress_bar=None):
691
        """See VersionedFile.check()."""
692
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
693
    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.
694
        """See VersionedFile.clone_text()."""
695
        # FIXME RBC 20060228 make fast by only inserting an index with null delta.
696
        self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
697
698
    def get_lines(self, version_id):
699
        """See VersionedFile.get_lines()."""
700
        return self._get_content(version_id).text()
701
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
702
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
703
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
704
        if version_ids is None:
705
            version_ids = self.versions()
706
        # we dont care about inclusions, the caller cares.
707
        # but we need to setup a list of records to visit.
708
        # we need version_id, position, length
709
        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.
710
        requested_versions = list(version_ids)
711
        # filter for available versions
712
        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.
713
            if not self.has_version(version_id):
714
                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.
715
        # get a in-component-order queue:
716
        version_ids = []
717
        for version_id in self.versions():
718
            if version_id in requested_versions:
719
                version_ids.append(version_id)
720
                data_pos, length = self._index.get_position(version_id)
721
                version_id_records.append((version_id, data_pos, length))
722
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
723
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
724
        count = 0
725
        total = len(version_id_records)
726
        try:
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
727
            pb.update('Walking content.', count, total)
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
728
            for version_id, data, sha_value in \
729
                self._data.read_records_iter(version_id_records):
730
                pb.update('Walking content.', count, total)
731
                method = self._index.get_method(version_id)
732
                version_idx = self._index.lookup(version_id)
733
                assert method in ('fulltext', 'line-delta')
734
                if method == 'fulltext':
735
                    content = self.factory.parse_fulltext(data, version_idx)
736
                    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.
737
                        yield line
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
738
                else:
739
                    delta = self.factory.parse_line_delta(data, version_idx)
740
                    for start, end, count, lines in delta:
741
                        for origin, line in lines:
742
                            yield line
743
                count +=1
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
744
            pb.update('Walking content.', total, total)
745
            pb.finished()
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
746
        except:
747
            pb.update('Walking content.', total, total)
748
            pb.finished()
749
            raise
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
750
        
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
751
    def num_versions(self):
752
        """See VersionedFile.num_versions()."""
753
        return self._index.num_versions()
754
755
    __len__ = num_versions
756
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
757
    def annotate_iter(self, version_id):
758
        """See VersionedFile.annotate_iter."""
759
        content = self._get_content(version_id)
760
        for origin, text in content.annotate_iter():
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
761
            yield origin, text
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
762
763
    def get_parents(self, version_id):
764
        """See VersionedFile.get_parents."""
1628.1.2 by Robert Collins
More knit micro-optimisations.
765
        # perf notes:
766
        # optimism counts!
767
        # 52554 calls in 1264 872 internal down from 3674
768
        try:
769
            return self._index.get_parents(version_id)
770
        except KeyError:
771
            raise RevisionNotPresent(version_id, self.filename)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
772
1594.2.8 by Robert Collins
add ghost aware apis to knits.
773
    def get_parents_with_ghosts(self, version_id):
774
        """See VersionedFile.get_parents."""
1628.1.2 by Robert Collins
More knit micro-optimisations.
775
        try:
776
            return self._index.get_parents_with_ghosts(version_id)
777
        except KeyError:
778
            raise RevisionNotPresent(version_id, self.filename)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
779
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
780
    def get_ancestry(self, versions):
781
        """See VersionedFile.get_ancestry."""
782
        if isinstance(versions, basestring):
783
            versions = [versions]
784
        if not versions:
785
            return []
786
        self._check_versions_present(versions)
787
        return self._index.get_ancestry(versions)
788
1594.2.8 by Robert Collins
add ghost aware apis to knits.
789
    def get_ancestry_with_ghosts(self, versions):
790
        """See VersionedFile.get_ancestry_with_ghosts."""
791
        if isinstance(versions, basestring):
792
            versions = [versions]
793
        if not versions:
794
            return []
795
        self._check_versions_present(versions)
796
        return self._index.get_ancestry_with_ghosts(versions)
797
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
798
    #@deprecated_method(zero_eight)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
799
    def walk(self, version_ids):
800
        """See VersionedFile.walk."""
801
        # We take the short path here, and extract all relevant texts
802
        # and put them in a weave and let that do all the work.  Far
803
        # from optimal, but is much simpler.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
804
        # FIXME RB 20060228 this really is inefficient!
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
805
        from bzrlib.weave import Weave
806
807
        w = Weave(self.filename)
808
        ancestry = self.get_ancestry(version_ids)
809
        sorted_graph = topo_sort(self._index.get_graph())
810
        version_list = [vid for vid in sorted_graph if vid in ancestry]
811
        
812
        for version_id in version_list:
813
            lines = self.get_lines(version_id)
814
            w.add_lines(version_id, self.get_parents(version_id), lines)
815
816
        for lineno, insert_id, dset, line in w.walk(version_ids):
817
            yield lineno, insert_id, dset, line
818
1664.2.3 by Aaron Bentley
Add failing test case
819
    def plan_merge(self, ver_a, ver_b):
820
        return []
821
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
822
823
class _KnitComponentFile(object):
824
    """One of the files used to implement a knit database"""
825
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
826
    def __init__(self, transport, filename, mode):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
827
        self._transport = transport
828
        self._filename = filename
829
        self._mode = mode
830
831
    def write_header(self):
1596.2.33 by Robert Collins
Do not cause construction of temporary knits when we are fetching and the target does not exist.
832
        if self._transport.append(self._filename, StringIO(self.HEADER)):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
833
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
834
835
    def check_header(self, fp):
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
836
        line = fp.readline()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
837
        if line != self.HEADER:
838
            raise KnitHeaderError(badline=line)
839
840
    def commit(self):
841
        """Commit is a nop."""
842
843
    def __repr__(self):
844
        return '%s(%s)' % (self.__class__.__name__, self._filename)
845
846
847
class _KnitIndex(_KnitComponentFile):
848
    """Manages knit index file.
849
850
    The index is already kept in memory and read on startup, to enable
851
    fast lookups of revision information.  The cursor of the index
852
    file is always pointing to the end, making it easy to append
853
    entries.
854
855
    _cache is a cache for fast mapping from version id to a Index
856
    object.
857
858
    _history is a cache for fast mapping from indexes to version ids.
859
860
    The index data format is dictionary compressed when it comes to
861
    parent references; a index entry may only have parents that with a
862
    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.
863
864
    Duplicate entries may be written to the index for a single version id
865
    if this is done then the latter one completely replaces the former:
866
    this allows updates to correct version and parent information. 
867
    Note that the two entries may share the delta, and that successive
868
    annotations and references MUST point to the first entry.
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
869
870
    The index file on disc contains a header, followed by one line per knit
871
    record. The same revision can be present in an index file more than once.
872
    The first occurence gets assigned a sequence number starting from 0. 
873
    
874
    The format of a single line is
875
    REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
876
    REVISION_ID is a utf8-encoded revision id
877
    FLAGS is a comma separated list of flags about the record. Values include 
878
        no-eol, line-delta, fulltext.
879
    BYTE_OFFSET is the ascii representation of the byte offset in the data file
880
        that the the compressed data starts at.
881
    LENGTH is the ascii representation of the length of the data file.
882
    PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
883
        REVISION_ID.
884
    PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
885
        revision id already in the knit that is a parent of REVISION_ID.
886
    The ' :' marker is the end of record marker.
887
    
888
    partial writes:
889
    when a write is interrupted to the index file, it will result in a line that
890
    does not end in ' :'. If the ' :' is not present at the end of a line, or at
891
    the end of the file, then the record that is missing it will be ignored by
892
    the parser.
893
894
    When writing new records to the index file, the data is preceeded by '\n'
895
    to ensure that records always start on new lines even if the last write was
896
    interrupted. As a result its normal for the last line in the index to be
897
    missing a trailing newline. One can be added with no harmful effects.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
898
    """
899
900
    HEADER = "# bzr knit index 7\n"
901
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
902
    # speed of knit parsing went from 280 ms to 280 ms with slots addition.
903
    # __slots__ = ['_cache', '_history', '_transport', '_filename']
904
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
905
    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.
906
        """Cache a version record in the history array and index cache.
907
        
908
        This is inlined into __init__ for performance. KEEP IN SYNC.
909
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
910
         indexes).
911
        """
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
912
        # only want the _history index to reference the 1st index entry
913
        # for version_id
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
914
        if version_id not in self._cache:
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
915
            index = len(self._history)
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
916
            self._history.append(version_id)
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
917
        else:
918
            index = self._cache[version_id][5]
919
        self._cache[version_id] = (version_id, 
920
                                   options,
921
                                   pos,
922
                                   size,
923
                                   parents,
924
                                   index)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
925
1563.2.25 by Robert Collins
Merge in upstream.
926
    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.
927
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
928
        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.
929
        # position in _history is the 'official' index for a revision
930
        # but the values may have come from a newer entry.
931
        # so - wc -l of a knit index is != the number of uniqe names
932
        # in the weave.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
933
        self._history = []
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
934
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
935
        try:
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
936
            count = 0
937
            total = 1
938
            try:
939
                pb.update('read knit index', count, total)
940
                fp = self._transport.get(self._filename)
941
                self.check_header(fp)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
942
                # readlines reads the whole file at once:
943
                # bad for transports like http, good for local disk
944
                # we save 60 ms doing this one change (
945
                # from calling readline each time to calling
946
                # readlines once.
947
                # probably what we want for nice behaviour on
948
                # http is a incremental readlines that yields, or
949
                # a check for local vs non local indexes,
950
                for l in fp.readlines():
951
                    rec = l.split()
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
952
                    if len(rec) < 5 or rec[-1] != ':':
953
                        # corrupt line.
954
                        # FIXME: in the future we should determine if its a
955
                        # short write - and ignore it 
956
                        # or a different failure, and raise. RBC 20060407
957
                        continue
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
958
                    count += 1
959
                    total += 1
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
960
                    #pb.update('read knit index', count, total)
961
                    # See self._parse_parents
962
                    parents = []
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
963
                    for value in rec[4:-1]:
1596.2.19 by Robert Collins
Shave 20% off id2path.
964
                        if '.' == value[0]:
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
965
                            # uncompressed reference
966
                            parents.append(value[1:])
967
                        else:
968
                            # this is 15/4000ms faster than isinstance,
969
                            # (in lsprof)
970
                            # this function is called thousands of times a 
971
                            # second so small variations add up.
972
                            assert value.__class__ is str
973
                            parents.append(self._history[int(value)])
974
                    # end self._parse_parents
975
                    # self._cache_version(rec[0], 
976
                    #                     rec[1].split(','),
977
                    #                     int(rec[2]),
978
                    #                     int(rec[3]),
979
                    #                     parents)
980
                    # --- self._cache_version
981
                    # only want the _history index to reference the 1st 
982
                    # index entry for version_id
983
                    version_id = rec[0]
984
                    if version_id not in self._cache:
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
985
                        index = len(self._history)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
986
                        self._history.append(version_id)
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
987
                    else:
988
                        index = self._cache[version_id][5]
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
989
                    self._cache[version_id] = (version_id,
990
                                               rec[1].split(','),
991
                                               int(rec[2]),
992
                                               int(rec[3]),
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
993
                                               parents,
994
                                               index)
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
995
                    # --- self._cache_version 
1594.2.17 by Robert Collins
Better readv coalescing, now with test, and progress during knit index reading.
996
            except NoSuchFile, e:
997
                if mode != 'w' or not create:
998
                    raise
999
                self.write_header()
1000
        finally:
1001
            pb.update('read knit index', total, total)
1002
            pb.finished()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1003
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1004
    def _parse_parents(self, compressed_parents):
1005
        """convert a list of string parent values into version ids.
1006
1007
        ints are looked up in the index.
1008
        .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.
1009
1010
        NOTE: the function is retained here for clarity, and for possible
1011
              use in partial index reads. However bulk processing now has
1012
              it inlined in __init__ for inner-loop optimisation.
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1013
        """
1014
        result = []
1015
        for value in compressed_parents:
1596.2.15 by Robert Collins
Microprofiling of knit parsing.
1016
            if value[-1] == '.':
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
1017
                # uncompressed reference
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1018
                result.append(value[1:])
1019
            else:
1596.2.15 by Robert Collins
Microprofiling of knit parsing.
1020
                # this is 15/4000ms faster than isinstance,
1021
                # this function is called thousands of times a 
1022
                # second so small variations add up.
1023
                assert value.__class__ is str
1596.2.11 by Robert Collins
Remove utf8 debugging code
1024
                result.append(self._history[int(value)])
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1025
        return result
1026
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1027
    def get_graph(self):
1028
        graph = []
1029
        for version_id, index in self._cache.iteritems():
1030
            graph.append((version_id, index[4]))
1031
        return graph
1032
1033
    def get_ancestry(self, versions):
1034
        """See VersionedFile.get_ancestry."""
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1035
        # get a graph of all the mentioned versions:
1036
        graph = {}
1037
        pending = set(versions)
1038
        while len(pending):
1039
            version = pending.pop()
1040
            parents = self._cache[version][4]
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1041
            # got the parents ok
1042
            # trim ghosts
1043
            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.
1044
            for parent in parents:
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1045
                # 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.
1046
                if parent not in graph:
1047
                    pending.add(parent)
1048
            graph[version] = parents
1049
        return topo_sort(graph.items())
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1050
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1051
    def get_ancestry_with_ghosts(self, versions):
1052
        """See VersionedFile.get_ancestry_with_ghosts."""
1053
        # get a graph of all the mentioned versions:
1054
        graph = {}
1055
        pending = set(versions)
1056
        while len(pending):
1057
            version = pending.pop()
1058
            try:
1059
                parents = self._cache[version][4]
1060
            except KeyError:
1061
                # ghost, fake it
1062
                graph[version] = []
1063
                pass
1064
            else:
1065
                # got the parents ok
1066
                for parent in parents:
1067
                    if parent not in graph:
1068
                        pending.add(parent)
1069
                graph[version] = parents
1070
        return topo_sort(graph.items())
1071
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1072
    def num_versions(self):
1073
        return len(self._history)
1074
1075
    __len__ = num_versions
1076
1077
    def get_versions(self):
1078
        return self._history
1079
1080
    def idx_to_name(self, idx):
1081
        return self._history[idx]
1082
1083
    def lookup(self, version_id):
1084
        assert version_id in self._cache
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1085
        return self._cache[version_id][5]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1086
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1087
    def _version_list_to_index(self, versions):
1088
        result_list = []
1089
        for version in versions:
1090
            if version in self._cache:
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
1091
                # -- inlined lookup() --
1092
                result_list.append(str(self._cache[version][5]))
1093
                # -- end lookup () --
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1094
            else:
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
1095
                result_list.append('.' + version.encode('utf-8'))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1096
        return ' '.join(result_list)
1097
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1098
    def add_version(self, version_id, options, pos, size, parents):
1099
        """Add a version record to the index."""
1100
        self._cache_version(version_id, options, pos, size, parents)
1101
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1102
        content = "\n%s %s %s %s %s :" % (version_id.encode('utf-8'),
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1103
                                        ','.join(options),
1104
                                        pos,
1105
                                        size,
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1106
                                        self._version_list_to_index(parents))
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1107
        assert isinstance(content, str), 'content must be utf-8 encoded'
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1108
        self._transport.append(self._filename, StringIO(content))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1109
1110
    def has_version(self, version_id):
1111
        """True if the version is in the index."""
1112
        return self._cache.has_key(version_id)
1113
1114
    def get_position(self, version_id):
1115
        """Return data position and size of specified version."""
1116
        return (self._cache[version_id][2], \
1117
                self._cache[version_id][3])
1118
1119
    def get_method(self, version_id):
1120
        """Return compression method of specified version."""
1121
        options = self._cache[version_id][1]
1122
        if 'fulltext' in options:
1123
            return 'fulltext'
1124
        else:
1125
            assert 'line-delta' in options
1126
            return 'line-delta'
1127
1128
    def get_options(self, version_id):
1129
        return self._cache[version_id][1]
1130
1131
    def get_parents(self, version_id):
1594.2.8 by Robert Collins
add ghost aware apis to knits.
1132
        """Return parents of specified version ignoring ghosts."""
1133
        return [parent for parent in self._cache[version_id][4] 
1134
                if parent in self._cache]
1135
1136
    def get_parents_with_ghosts(self, version_id):
1137
        """Return parents of specified version wth ghosts."""
1138
        return self._cache[version_id][4] 
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1139
1140
    def check_versions_present(self, version_ids):
1141
        """Check that all specified versions are present."""
1142
        version_ids = set(version_ids)
1143
        for version_id in list(version_ids):
1144
            if version_id in self._cache:
1145
                version_ids.remove(version_id)
1146
        if version_ids:
1147
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
1148
1149
1150
class _KnitData(_KnitComponentFile):
1151
    """Contents of the knit data file"""
1152
1153
    HEADER = "# bzr knit data 7\n"
1154
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1155
    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.
1156
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1157
        self._file = None
1158
        self._checked = False
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
1159
        if create:
1160
            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.
1161
        self._records = {}
1162
1163
    def clear_cache(self):
1164
        """Clear the record cache."""
1165
        self._records = {}
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1166
1167
    def _open_file(self):
1168
        if self._file is None:
1169
            try:
1170
                self._file = self._transport.get(self._filename)
1171
            except NoSuchFile:
1172
                pass
1173
        return self._file
1174
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1175
    def _record_to_data(self, version_id, digest, lines):
1176
        """Convert version_id, digest, lines into a raw data block.
1177
        
1178
        :return: (len, a StringIO instance with the raw data ready to read.)
1179
        """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1180
        sio = StringIO()
1181
        data_file = GzipFile(None, mode='wb', fileobj=sio)
1596.2.28 by Robert Collins
more knit profile based tuning.
1182
        data_file.writelines(chain(
1183
            ["version %s %d %s\n" % (version_id.encode('utf-8'), 
1184
                                     len(lines),
1185
                                     digest)],
1186
            lines,
1628.1.2 by Robert Collins
More knit micro-optimisations.
1187
            ["end %s\n" % version_id.encode('utf-8')]))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1188
        data_file.close()
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1189
        length= sio.tell()
1596.2.28 by Robert Collins
more knit profile based tuning.
1190
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1191
        sio.seek(0)
1192
        return length, sio
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1193
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1194
    def add_raw_record(self, raw_data):
1195
        """Append a prepared record to the data file."""
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1196
        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.
1197
        start_pos = self._transport.append(self._filename, StringIO(raw_data))
1198
        return start_pos, len(raw_data)
1199
        
1200
    def add_record(self, version_id, digest, lines):
1201
        """Write new text record to disk.  Returns the position in the
1202
        file where it was written."""
1203
        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.
1204
        # cache
1205
        self._records[version_id] = (digest, lines)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1206
        # write to disk
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1207
        start_pos = self._transport.append(self._filename, sio)
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1208
        return start_pos, size
1209
1210
    def _parse_record_header(self, version_id, raw_data):
1211
        """Parse a record header for consistency.
1212
1213
        :return: the header and the decompressor stream.
1214
                 as (stream, header_record)
1215
        """
1216
        df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1217
        rec = df.readline().split()
1218
        if len(rec) != 4:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1219
            raise KnitCorrupt(self._filename, 'unexpected number of elements in record header')
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1220
        if rec[1].decode('utf-8')!= version_id:
1594.3.3 by Robert Collins
Bugfix error message output in knit error raising.
1221
            raise KnitCorrupt(self._filename, 
1594.3.4 by Robert Collins
Change urllib ranges implementation to be one coalesced range per http request.
1222
                              'unexpected version, wanted %r, got %r' % (
1223
                                version_id, rec[1]))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1224
        return df, rec
1225
1226
    def _parse_record(self, version_id, data):
1628.1.2 by Robert Collins
More knit micro-optimisations.
1227
        # profiling notes:
1228
        # 4168 calls in 2880 217 internal
1229
        # 4168 calls to _parse_record_header in 2121
1230
        # 4168 calls to readlines in 330
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1231
        df, rec = self._parse_record_header(version_id, data)
1628.1.2 by Robert Collins
More knit micro-optimisations.
1232
        record_contents = df.readlines()
1233
        l = record_contents.pop()
1234
        assert len(record_contents) == int(rec[2])
1596.2.9 by Robert Collins
Utf8 safety in knit indexes.
1235
        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.
1236
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
1237
                        % (l, version_id))
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1238
        df.close()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1239
        return record_contents, rec[3]
1240
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1241
    def read_records_iter_raw(self, records):
1242
        """Read text records from data file and yield raw data.
1243
1244
        This unpacks enough of the text record to validate the id is
1245
        as expected but thats all.
1246
1247
        It will actively recompress currently cached records on the
1248
        basis that that is cheaper than I/O activity.
1249
        """
1250
        needed_records = []
1251
        for version_id, pos, size in records:
1252
            if version_id not in self._records:
1253
                needed_records.append((version_id, pos, size))
1254
1255
        # setup an iterator of the external records:
1256
        # uses readv so nice and fast we hope.
1257
        if len(needed_records):
1258
            # grab the disk data needed.
1259
            raw_records = self._transport.readv(self._filename,
1260
                [(pos, size) for version_id, pos, size in needed_records])
1261
1262
        for version_id, pos, size in records:
1263
            if version_id in self._records:
1264
                # compress a new version
1265
                size, sio = self._record_to_data(version_id,
1266
                                                 self._records[version_id][0],
1267
                                                 self._records[version_id][1])
1268
                yield version_id, sio.getvalue()
1269
            else:
1270
                pos, data = raw_records.next()
1271
                # validate the header
1272
                df, rec = self._parse_record_header(version_id, data)
1273
                df.close()
1274
                yield version_id, data
1275
1276
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1277
    def read_records_iter(self, records):
1278
        """Read text records from data file and yield result.
1279
1280
        Each passed record is a tuple of (version_id, pos, len) and
1281
        will be read in the given order.  Yields (version_id,
1282
        contents, digest).
1283
        """
1628.1.2 by Robert Collins
More knit micro-optimisations.
1284
        # profiling notes:
1285
        # 60890  calls for 4168 extractions in 5045, 683 internal.
1286
        # 4168   calls to readv              in 1411
1287
        # 4168   calls to parse_record       in 2880
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1288
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1289
        needed_records = []
1290
        for version_id, pos, size in records:
1291
            if version_id not in self._records:
1292
                needed_records.append((version_id, pos, size))
1293
1294
        if len(needed_records):
1295
            # We take it that the transport optimizes the fetching as good
1296
            # as possible (ie, reads continous ranges.)
1297
            response = self._transport.readv(self._filename,
1298
                [(pos, size) for version_id, pos, size in needed_records])
1299
1594.3.5 by Robert Collins
Bugfix knit caching implementation.
1300
            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.
1301
                content, digest = self._parse_record(record_id, data)
1302
                self._records[record_id] = (digest, content)
1303
    
1304
        for version_id, pos, size in records:
1628.1.2 by Robert Collins
More knit micro-optimisations.
1305
            yield version_id, list(self._records[version_id][1]), self._records[version_id][0]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1306
1307
    def read_records(self, records):
1308
        """Read records into a dictionary."""
1309
        components = {}
1310
        for record_id, content, digest in self.read_records_iter(records):
1311
            components[record_id] = (content, digest)
1312
        return components
1313
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1314
1315
class InterKnit(InterVersionedFile):
1316
    """Optimised code paths for knit to knit operations."""
1317
    
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1318
    _matching_file_factory = KnitVersionedFile
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1319
    
1320
    @staticmethod
1321
    def is_compatible(source, target):
1322
        """Be compatible with knits.  """
1323
        try:
1324
            return (isinstance(source, KnitVersionedFile) and
1325
                    isinstance(target, KnitVersionedFile))
1326
        except AttributeError:
1327
            return False
1328
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1329
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1330
        """See InterVersionedFile.join."""
1331
        assert isinstance(self.source, KnitVersionedFile)
1332
        assert isinstance(self.target, KnitVersionedFile)
1333
1334
        if version_ids is None:
1335
            version_ids = self.source.versions()
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
1336
        else:
1337
            if not ignore_missing:
1338
                self.source._check_versions_present(version_ids)
1339
            else:
1340
                version_ids = set(self.source.versions()).intersection(
1341
                    set(version_ids))
1342
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1343
        if not version_ids:
1344
            return 0
1345
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1346
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1347
        try:
1348
            version_ids = list(version_ids)
1349
            if None in version_ids:
1350
                version_ids.remove(None)
1351
    
1352
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
1353
            this_versions = set(self.target._index.get_versions())
1354
            needed_versions = self.source_ancestry - this_versions
1355
            cross_check_versions = self.source_ancestry.intersection(this_versions)
1356
            mismatched_versions = set()
1357
            for version in cross_check_versions:
1358
                # scan to include needed parents.
1359
                n1 = set(self.target.get_parents_with_ghosts(version))
1360
                n2 = set(self.source.get_parents_with_ghosts(version))
1361
                if n1 != n2:
1362
                    # FIXME TEST this check for cycles being introduced works
1363
                    # the logic is we have a cycle if in our graph we are an
1364
                    # ancestor of any of the n2 revisions.
1365
                    for parent in n2:
1366
                        if parent in n1:
1367
                            # safe
1368
                            continue
1369
                        else:
1370
                            parent_ancestors = self.source.get_ancestry(parent)
1371
                            if version in parent_ancestors:
1372
                                raise errors.GraphCycleError([parent, version])
1373
                    # ensure this parent will be available later.
1374
                    new_parents = n2.difference(n1)
1375
                    needed_versions.update(new_parents.difference(this_versions))
1376
                    mismatched_versions.add(version)
1377
    
1378
            if not needed_versions and not cross_check_versions:
1379
                return 0
1380
            full_list = topo_sort(self.source.get_graph())
1381
    
1382
            version_list = [i for i in full_list if (not self.target.has_version(i)
1383
                            and i in needed_versions)]
1384
    
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1385
            # plan the join:
1386
            copy_queue = []
1387
            copy_queue_records = []
1388
            copy_set = set()
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1389
            for version_id in version_list:
1390
                options = self.source._index.get_options(version_id)
1391
                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.
1392
                # 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.
1393
                for parent in parents:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1394
                    # if source has the parent, we must :
1395
                    # * already have it or
1396
                    # * have it scheduled already
1397
                    # otherwise we dont care
1398
                    assert (self.target.has_version(parent) or
1399
                            parent in copy_set or
1400
                            not self.source.has_version(parent))
1401
                data_pos, data_size = self.source._index.get_position(version_id)
1402
                copy_queue_records.append((version_id, data_pos, data_size))
1403
                copy_queue.append((version_id, options, parents))
1404
                copy_set.add(version_id)
1405
1406
            # data suck the join:
1407
            count = 0
1408
            total = len(version_list)
1409
            # we want the raw gzip for bulk copying, but the record validated
1410
            # just enough to be sure its the right one.
1411
            # TODO: consider writev or write combining to reduce 
1412
            # death of a thousand cuts feeling.
1413
            for (version_id, raw_data), \
1414
                (version_id2, options, parents) in \
1415
                izip(self.source._data.read_records_iter_raw(copy_queue_records),
1416
                     copy_queue):
1417
                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.
1418
                count = count + 1
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1419
                pb.update("Joining knit", count, total)
1420
                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.
1421
                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.
1422
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1423
            for version in mismatched_versions:
1596.2.8 by Robert Collins
Join knits with the original gzipped data avoiding recompression.
1424
                # 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.
1425
                n1 = set(self.target.get_parents_with_ghosts(version))
1426
                n2 = set(self.source.get_parents_with_ghosts(version))
1427
                # write a combined record to our history preserving the current 
1428
                # parents as first in the list
1429
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
1430
                self.target.fix_parents(version, new_parents)
1431
            return count
1432
        finally:
1433
            pb.finished()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1434
1435
1436
InterVersionedFile.register_optimiser(InterKnit)
1596.2.24 by Robert Collins
Gzipfile was slightly slower than ideal.
1437
1438
1596.2.35 by Robert Collins
Subclass SequenceMatcher to get a slightly faster (in our case) find_longest_match routine.
1439
class SequenceMatcher(difflib.SequenceMatcher):
1440
    """Knit tuned sequence matcher.
1441
1442
    This is based on profiling of difflib which indicated some improvements
1443
    for our usage pattern.
1444
    """
1445
1446
    def find_longest_match(self, alo, ahi, blo, bhi):
1447
        """Find longest matching block in a[alo:ahi] and b[blo:bhi].
1448
1449
        If isjunk is not defined:
1450
1451
        Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
1452
            alo <= i <= i+k <= ahi
1453
            blo <= j <= j+k <= bhi
1454
        and for all (i',j',k') meeting those conditions,
1455
            k >= k'
1456
            i <= i'
1457
            and if i == i', j <= j'
1458
1459
        In other words, of all maximal matching blocks, return one that
1460
        starts earliest in a, and of all those maximal matching blocks that
1461
        start earliest in a, return the one that starts earliest in b.
1462
1463
        >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
1464
        >>> s.find_longest_match(0, 5, 0, 9)
1465
        (0, 4, 5)
1466
1467
        If isjunk is defined, first the longest matching block is
1468
        determined as above, but with the additional restriction that no
1469
        junk element appears in the block.  Then that block is extended as
1470
        far as possible by matching (only) junk elements on both sides.  So
1471
        the resulting block never matches on junk except as identical junk
1472
        happens to be adjacent to an "interesting" match.
1473
1474
        Here's the same example as before, but considering blanks to be
1475
        junk.  That prevents " abcd" from matching the " abcd" at the tail
1476
        end of the second sequence directly.  Instead only the "abcd" can
1477
        match, and matches the leftmost "abcd" in the second sequence:
1478
1479
        >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
1480
        >>> s.find_longest_match(0, 5, 0, 9)
1481
        (1, 0, 4)
1482
1483
        If no blocks match, return (alo, blo, 0).
1484
1485
        >>> s = SequenceMatcher(None, "ab", "c")
1486
        >>> s.find_longest_match(0, 2, 0, 1)
1487
        (0, 0, 0)
1488
        """
1489
1490
        # CAUTION:  stripping common prefix or suffix would be incorrect.
1491
        # E.g.,
1492
        #    ab
1493
        #    acab
1494
        # Longest matching block is "ab", but if common prefix is
1495
        # stripped, it's "a" (tied with "b").  UNIX(tm) diff does so
1496
        # strip, so ends up claiming that ab is changed to acab by
1497
        # inserting "ca" in the middle.  That's minimal but unintuitive:
1498
        # "it's obvious" that someone inserted "ac" at the front.
1499
        # Windiff ends up at the same place as diff, but by pairing up
1500
        # the unique 'b's and then matching the first two 'a's.
1501
1502
        a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
1503
        besti, bestj, bestsize = alo, blo, 0
1504
        # find longest junk-free match
1505
        # during an iteration of the loop, j2len[j] = length of longest
1506
        # junk-free match ending with a[i-1] and b[j]
1507
        j2len = {}
1508
        # nothing = []
1509
        b2jget = b2j.get
1510
        for i in xrange(alo, ahi):
1511
            # look at all instances of a[i] in b; note that because
1512
            # b2j has no junk keys, the loop is skipped if a[i] is junk
1513
            j2lenget = j2len.get
1514
            newj2len = {}
1515
            
1516
            # changing b2j.get(a[i], nothing) to a try:Keyerror pair produced the
1517
            # following improvement
1518
            #     704  0   4650.5320   2620.7410   bzrlib.knit:1336(find_longest_match)
1519
            # +326674  0   1655.1210   1655.1210   +<method 'get' of 'dict' objects>
1520
            #  +76519  0    374.6700    374.6700   +<method 'has_key' of 'dict' objects>
1521
            # to 
1522
            #     704  0   3733.2820   2209.6520   bzrlib.knit:1336(find_longest_match)
1523
            #  +211400 0   1147.3520   1147.3520   +<method 'get' of 'dict' objects>
1524
            #  +76519  0    376.2780    376.2780   +<method 'has_key' of 'dict' objects>
1525
1526
            try:
1527
                js = b2j[a[i]]
1528
            except KeyError:
1529
                pass
1530
            else:
1531
                for j in js:
1532
                    # a[i] matches b[j]
1533
                    if j >= blo:
1534
                        if j >= bhi:
1535
                            break
1536
                        k = newj2len[j] = 1 + j2lenget(-1 + j, 0)
1537
                        if k > bestsize:
1538
                            besti, bestj, bestsize = 1 + i-k, 1 + j-k, k
1539
            j2len = newj2len
1540
1541
        # Extend the best by non-junk elements on each end.  In particular,
1542
        # "popular" non-junk elements aren't in b2j, which greatly speeds
1543
        # the inner loop above, but also means "the best" match so far
1544
        # doesn't contain any junk *or* popular non-junk elements.
1545
        while besti > alo and bestj > blo and \
1546
              not isbjunk(b[bestj-1]) and \
1547
              a[besti-1] == b[bestj-1]:
1548
            besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1549
        while besti+bestsize < ahi and bestj+bestsize < bhi and \
1550
              not isbjunk(b[bestj+bestsize]) and \
1551
              a[besti+bestsize] == b[bestj+bestsize]:
1552
            bestsize += 1
1553
1554
        # Now that we have a wholly interesting match (albeit possibly
1555
        # empty!), we may as well suck up the matching junk on each
1556
        # side of it too.  Can't think of a good reason not to, and it
1557
        # saves post-processing the (possibly considerable) expense of
1558
        # figuring out what to do with it.  In the case of an empty
1559
        # interesting match, this is clearly the right thing to do,
1560
        # because no other kind of match is possible in the regions.
1561
        while besti > alo and bestj > blo and \
1562
              isbjunk(b[bestj-1]) and \
1563
              a[besti-1] == b[bestj-1]:
1564
            besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
1565
        while besti+bestsize < ahi and bestj+bestsize < bhi and \
1566
              isbjunk(b[bestj+bestsize]) and \
1567
              a[besti+bestsize] == b[bestj+bestsize]:
1568
            bestsize = bestsize + 1
1569
1570
        return besti, bestj, bestsize
1571