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>
 
 
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.
 
 
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.
 
 
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
 
 
20
"""Knit versionedfile implementation.
 
 
22
A knit is a versioned file implementation that supports efficient append only
 
 
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"
 
 
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
 
 
37
8             e.set('executable', 'yes')
 
 
39
8         if elt.get('executable') == 'yes':
 
 
40
8             ie.executable = True
 
 
41
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 
 
 
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
 
 
52
so the index sequence is the dictionary compressed sequence number used
 
 
53
in the deltas to provide line annotation
 
 
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 
 
 
62
# move sha1 out of the content so that join is faster at verifying parents
 
 
63
# record content length ?
 
 
67
from cStringIO import StringIO
 
 
70
from itertools import izip, chain
 
 
75
import bzrlib.errors as errors
 
 
76
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
 
 
77
        InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
 
 
78
        RevisionNotPresent, RevisionAlreadyPresent
 
 
79
from bzrlib.trace import mutter
 
 
80
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
 
 
82
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
 
 
83
from bzrlib.tsort import topo_sort
 
 
86
# TODO: Split out code specific to this format into an associated object.
 
 
88
# TODO: Can we put in some kind of value to check that the index and data
 
 
89
# files belong together?
 
 
91
# TODO: accomodate binaries, perhaps by storing a byte count
 
 
93
# TODO: function to check whole file
 
 
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.
 
 
100
INDEX_SUFFIX = '.kndx'
 
 
103
class KnitContent(object):
 
 
104
    """Content of a knit version to which deltas can be applied."""
 
 
106
    def __init__(self, lines):
 
 
109
    def annotate_iter(self):
 
 
110
        """Yield tuples of (origin, text) for each content line."""
 
 
111
        for origin, text in self._lines:
 
 
115
        """Return a list of (origin, text) tuples."""
 
 
116
        return list(self.annotate_iter())
 
 
118
    def line_delta_iter(self, new_lines):
 
 
119
        """Generate line-based delta from this content to new_lines."""
 
 
120
        new_texts = [text for origin, text in new_lines._lines]
 
 
121
        old_texts = [text for origin, text in self._lines]
 
 
122
        s = SequenceMatcher(None, old_texts, new_texts)
 
 
123
        for op in s.get_opcodes():
 
 
126
            #     ofrom   oto   length        data
 
 
127
            yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
 
 
129
    def line_delta(self, new_lines):
 
 
130
        return list(self.line_delta_iter(new_lines))
 
 
133
        return [text for origin, text in self._lines]
 
 
136
class _KnitFactory(object):
 
 
137
    """Base factory for creating content objects."""
 
 
139
    def make(self, lines, version):
 
 
140
        num_lines = len(lines)
 
 
141
        return KnitContent(zip([version] * num_lines, lines))
 
 
144
class KnitAnnotateFactory(_KnitFactory):
 
 
145
    """Factory for creating annotated Content objects."""
 
 
149
    def parse_fulltext(self, content, version):
 
 
150
        """Convert fulltext to internal representation
 
 
152
        fulltext content is of the format
 
 
153
        revid(utf8) plaintext\n
 
 
154
        internal representation is of the format:
 
 
159
            origin, text = line.split(' ', 1)
 
 
160
            lines.append((origin.decode('utf-8'), text))
 
 
161
        return KnitContent(lines)
 
 
163
    def parse_line_delta_iter(self, lines):
 
 
164
        for result_item in self.parse_line_delta[lines]:
 
 
167
    def parse_line_delta(self, lines, version):
 
 
168
        """Convert a line based delta into internal representation.
 
 
170
        line delta is in the form of:
 
 
171
        intstart intend intcount
 
 
173
        revid(utf8) newline\n
 
 
174
        internal represnetation is
 
 
175
        (start, end, count, [1..count tuples (revid, newline)])
 
 
180
        # walk through the lines parsing.
 
 
182
            start, end, count = [int(n) for n in header.split(',')]
 
 
186
                origin, text = next().split(' ', 1)
 
 
188
                contents.append((origin.decode('utf-8'), text))
 
 
189
            result.append((start, end, count, contents))
 
 
192
    def lower_fulltext(self, content):
 
 
193
        """convert a fulltext content record into a serializable form.
 
 
195
        see parse_fulltext which this inverts.
 
 
197
        return ['%s %s' % (o.encode('utf-8'), t) for o, t in content._lines]
 
 
199
    def lower_line_delta(self, delta):
 
 
200
        """convert a delta into a serializable form.
 
 
202
        See parse_line_delta which this inverts.
 
 
205
        for start, end, c, lines in delta:
 
 
206
            out.append('%d,%d,%d\n' % (start, end, c))
 
 
207
            for origin, text in lines:
 
 
208
                out.append('%s %s' % (origin.encode('utf-8'), text))
 
 
212
class KnitPlainFactory(_KnitFactory):
 
 
213
    """Factory for creating plain Content objects."""
 
 
217
    def parse_fulltext(self, content, version):
 
 
218
        """This parses an unannotated fulltext.
 
 
220
        Note that this is not a noop - the internal representation
 
 
221
        has (versionid, line) - its just a constant versionid.
 
 
223
        return self.make(content, version)
 
 
225
    def parse_line_delta_iter(self, lines, version):
 
 
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])
 
 
232
    def parse_line_delta(self, lines, version):
 
 
233
        return list(self.parse_line_delta_iter(lines, version))
 
 
235
    def lower_fulltext(self, content):
 
 
236
        return content.text()
 
 
238
    def lower_line_delta(self, delta):
 
 
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])
 
 
246
def make_empty_knit(transport, relpath):
 
 
247
    """Construct a empty knit at the specified location."""
 
 
248
    k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
 
 
252
class KnitVersionedFile(VersionedFile):
 
 
253
    """Weave-like structure with faster random access.
 
 
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.
 
 
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.
 
 
267
    def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
 
 
268
                 basis_knit=None, delta=True, create=False):
 
 
269
        """Construct a knit at location specified by relpath.
 
 
271
        :param create: If not True, only open an existing knit.
 
 
273
        if access_mode is None:
 
 
275
        super(KnitVersionedFile, self).__init__(access_mode)
 
 
276
        assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
 
 
277
        assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
 
 
280
        self.transport = transport
 
 
281
        self.filename = relpath
 
 
282
        self.basis_knit = basis_knit
 
 
283
        self.factory = factory or KnitAnnotateFactory()
 
 
284
        self.writable = (access_mode == 'w')
 
 
287
        self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
 
 
288
            access_mode, create=create)
 
 
289
        self._data = _KnitData(transport, relpath + DATA_SUFFIX,
 
 
290
            access_mode, create=not len(self.versions()))
 
 
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)
 
 
299
        for parent in parents:
 
 
300
            if not self.has_version(parent):
 
 
301
                ghosts.append(parent)
 
 
303
                present_parents.append(parent)
 
 
305
        if delta_parent is None:
 
 
306
            # reconstitute as full text.
 
 
307
            assert len(delta) == 1 or len(delta) == 0
 
 
309
                assert delta[0][0] == 0
 
 
310
                assert delta[0][1] == 0, delta[0][1]
 
 
311
            return super(KnitVersionedFile, self)._add_delta(version_id,
 
 
322
            options.append('no-eol')
 
 
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.
 
 
330
            delta_parents = [delta_parent]
 
 
332
                parent = delta_parents[0]
 
 
333
                method = self._index.get_method(parent)
 
 
334
                if method == 'fulltext':
 
 
336
                delta_parents = self._index.get_parents(parent)
 
 
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,
 
 
348
        options.append('line-delta')
 
 
349
        store_lines = self.factory.lower_line_delta(delta)
 
 
351
        where, size = self._data.add_record(version_id, digest, store_lines)
 
 
352
        self._index.add_version(version_id, options, where, size, parents)
 
 
354
    def clear_cache(self):
 
 
355
        """Clear the data cache only."""
 
 
356
        self._data.clear_cache()
 
 
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
 
 
362
        transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
 
 
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)
 
 
368
    def create_empty(self, name, transport, mode=None):
 
 
369
        return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
 
 
371
    def _fix_parents(self, version, new_parents):
 
 
372
        """Fix the parents list for version.
 
 
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
 
 
379
        current_values = self._index._cache[version]
 
 
380
        assert set(current_values[4]).difference(set(new_parents)) == set()
 
 
381
        self._index.add_version(version,
 
 
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)
 
 
392
        parents = self.get_parents(version_id)
 
 
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)
 
 
400
        noeol = 'no-eol' in self._index.get_options(version_id)
 
 
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()
 
 
408
            new_texts = new_content.text()
 
 
409
            delta_seq = SequenceMatcher(None, old_texts, new_texts)
 
 
410
            return parent, sha1, noeol, self._make_line_delta(delta_seq, new_content)
 
 
412
            delta = self.factory.parse_line_delta(data, version_idx)
 
 
413
            return parent, sha1, noeol, delta
 
 
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)
 
 
422
        """See VersionedFile.get_suffixes()."""
 
 
423
        return [DATA_SUFFIX, INDEX_SUFFIX]
 
 
425
    def has_ghost(self, version_id):
 
 
426
        """True if there is a ghost reference in the file to version_id."""
 
 
428
        if self.has_version(version_id):
 
 
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:
 
 
440
        """See VersionedFile.versions."""
 
 
441
        return self._index.get_versions()
 
 
443
    def has_version(self, version_id):
 
 
444
        """See VersionedFile.has_version."""
 
 
445
        return self._index.has_version(version_id)
 
 
447
    __contains__ = has_version
 
 
449
    def _merge_annotations(self, content, parents, parent_texts={},
 
 
450
                           delta=None, annotated=None):
 
 
451
        """Merge annotations for content.  This is done by comparing
 
 
452
        the annotations based on changed to the text.
 
 
456
            for parent_id in parents:
 
 
457
                merge_content = self._get_content(parent_id, parent_texts)
 
 
458
                seq = SequenceMatcher(None, merge_content.text(), content.text())
 
 
459
                if delta_seq is None:
 
 
460
                    # setup a delta seq to reuse.
 
 
462
                for i, j, n in seq.get_matching_blocks():
 
 
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]
 
 
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)
 
 
478
    def _make_line_delta(self, delta_seq, new_content):
 
 
479
        """Generate a line delta from delta_seq and new_content."""
 
 
481
        for op in delta_seq.get_opcodes():
 
 
484
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
 
 
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.
 
 
491
        The components should be applied in the order of the returned
 
 
494
        The basis knit will be used to the largest extent possible
 
 
495
        since it is assumed that accesses to it is faster.
 
 
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
 
 
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.
 
 
507
        # basis_revisions is a list of versions that needs to be
 
 
508
        # fetched but exists in the basis knit.
 
 
510
        basis = self.basis_knit
 
 
517
            if basis and basis._index.has_version(cursor):
 
 
519
                basis_versions.append(cursor)
 
 
520
            method = picked_knit._index.get_method(cursor)
 
 
521
            needed_versions.append((method, cursor))
 
 
522
            if method == 'fulltext':
 
 
524
            cursor = picked_knit.get_parents(cursor)[0]
 
 
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))
 
 
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))
 
 
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).
 
 
545
        for method, comp_id in reversed(needed_versions):
 
 
546
            out.append((comp_id, method, components[comp_id]))
 
 
550
    def _get_content(self, version_id, parent_texts={}):
 
 
551
        """Returns a content object that makes up the specified
 
 
553
        if not self.has_version(version_id):
 
 
554
            raise RevisionNotPresent(version_id, self.filename)
 
 
556
        cached_version = parent_texts.get(version_id, None)
 
 
557
        if cached_version is not None:
 
 
558
            return cached_version
 
 
560
        if self.basis_knit and version_id in self.basis_knit:
 
 
561
            return self.basis_knit._get_content(version_id)
 
 
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)
 
 
572
                content._lines = self._apply_delta(content._lines, delta)
 
 
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)
 
 
578
        if sha_strings(content.text()) != digest:
 
 
579
            import pdb;pdb.set_trace()
 
 
580
            raise KnitCorrupt(self.filename, 'sha-1 does not match %s' % version_id)
 
 
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)
 
 
591
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
 
593
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
 
 
594
        """See VersionedFile.add_lines_with_ghosts()."""
 
 
595
        self._check_add(version_id, lines)
 
 
596
        return self._add(version_id, lines[:], parents, self.delta, parent_texts)
 
 
598
    def _add_lines(self, version_id, parents, lines, parent_texts):
 
 
599
        """See VersionedFile.add_lines."""
 
 
600
        self._check_add(version_id, lines)
 
 
601
        self._check_versions_present(parents)
 
 
602
        return self._add(version_id, lines[:], parents, self.delta, parent_texts)
 
 
604
    def _check_add(self, version_id, lines):
 
 
605
        """check that version_id and lines are safe to add."""
 
 
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)
 
 
613
        if False or __debug__:
 
 
615
                assert '\n' not in l[:-1]
 
 
617
    def _add(self, version_id, lines, parents, delta, parent_texts):
 
 
618
        """Add a set of lines on top of version specified by parents.
 
 
620
        If delta is true, compress the text as a line-delta against
 
 
623
        Any versions not present will be converted into ghosts.
 
 
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)
 
 
639
        if parent_texts is None:
 
 
641
        for parent in parents:
 
 
642
            if not self.has_version(parent):
 
 
643
                ghosts.append(parent)
 
 
645
                present_parents.append(parent)
 
 
647
        if delta and not len(present_parents):
 
 
650
        digest = sha_strings(lines)
 
 
653
            if lines[-1][-1] != '\n':
 
 
654
                options.append('no-eol')
 
 
655
                lines[-1] = lines[-1] + '\n'
 
 
657
        if len(present_parents) and delta:
 
 
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.
 
 
662
            delta_parents = present_parents
 
 
664
                parent = delta_parents[0]
 
 
665
                method = self._index.get_method(parent)
 
 
666
                if method == 'fulltext':
 
 
668
                delta_parents = self._index.get_parents(parent)
 
 
670
            if method == 'line-delta':
 
 
673
        lines = self.factory.make(lines, version_id)
 
 
674
        if delta or (self.factory.annotated and len(present_parents) > 0):
 
 
675
            # Merge annotations from parent texts if so is needed.
 
 
676
            delta_hunks = self._merge_annotations(lines, present_parents, parent_texts,
 
 
677
                                                  delta, self.factory.annotated)
 
 
680
            options.append('line-delta')
 
 
681
            store_lines = self.factory.lower_line_delta(delta_hunks)
 
 
683
            options.append('fulltext')
 
 
684
            store_lines = self.factory.lower_fulltext(lines)
 
 
686
        where, size = self._data.add_record(version_id, digest, store_lines)
 
 
687
        self._index.add_version(version_id, options, where, size, parents)
 
 
690
    def check(self, progress_bar=None):
 
 
691
        """See VersionedFile.check()."""
 
 
693
    def _clone_text(self, new_version_id, old_version_id, parents):
 
 
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))
 
 
698
    def get_lines(self, version_id):
 
 
699
        """See VersionedFile.get_lines()."""
 
 
700
        return self._get_content(version_id).text()
 
 
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 = []
 
 
710
        requested_versions = list(version_ids)
 
 
711
        # filter for available versions
 
 
712
        for version_id in requested_versions:
 
 
713
            if not self.has_version(version_id):
 
 
714
                raise RevisionNotPresent(version_id, self.filename)
 
 
715
        # get a in-component-order queue:
 
 
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))
 
 
723
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
 
725
        total = len(version_id_records)
 
 
727
            pb.update('Walking content.', count, total)
 
 
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():
 
 
739
                    delta = self.factory.parse_line_delta(data, version_idx)
 
 
740
                    for start, end, count, lines in delta:
 
 
741
                        for origin, line in lines:
 
 
744
            pb.update('Walking content.', total, total)
 
 
747
            pb.update('Walking content.', total, total)
 
 
751
    def num_versions(self):
 
 
752
        """See VersionedFile.num_versions()."""
 
 
753
        return self._index.num_versions()
 
 
755
    __len__ = num_versions
 
 
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():
 
 
763
    def get_parents(self, version_id):
 
 
764
        """See VersionedFile.get_parents."""
 
 
767
        # 52554 calls in 1264 872 internal down from 3674
 
 
769
            return self._index.get_parents(version_id)
 
 
771
            raise RevisionNotPresent(version_id, self.filename)
 
 
773
    def get_parents_with_ghosts(self, version_id):
 
 
774
        """See VersionedFile.get_parents."""
 
 
776
            return self._index.get_parents_with_ghosts(version_id)
 
 
778
            raise RevisionNotPresent(version_id, self.filename)
 
 
780
    def get_ancestry(self, versions):
 
 
781
        """See VersionedFile.get_ancestry."""
 
 
782
        if isinstance(versions, basestring):
 
 
783
            versions = [versions]
 
 
786
        self._check_versions_present(versions)
 
 
787
        return self._index.get_ancestry(versions)
 
 
789
    def get_ancestry_with_ghosts(self, versions):
 
 
790
        """See VersionedFile.get_ancestry_with_ghosts."""
 
 
791
        if isinstance(versions, basestring):
 
 
792
            versions = [versions]
 
 
795
        self._check_versions_present(versions)
 
 
796
        return self._index.get_ancestry_with_ghosts(versions)
 
 
798
    #@deprecated_method(zero_eight)
 
 
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.
 
 
804
        # FIXME RB 20060228 this really is inefficient!
 
 
805
        from bzrlib.weave import Weave
 
 
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]
 
 
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)
 
 
816
        for lineno, insert_id, dset, line in w.walk(version_ids):
 
 
817
            yield lineno, insert_id, dset, line
 
 
820
class _KnitComponentFile(object):
 
 
821
    """One of the files used to implement a knit database"""
 
 
823
    def __init__(self, transport, filename, mode):
 
 
824
        self._transport = transport
 
 
825
        self._filename = filename
 
 
828
    def write_header(self):
 
 
829
        if self._transport.append(self._filename, StringIO(self.HEADER)):
 
 
830
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
 
 
832
    def check_header(self, fp):
 
 
833
        line = fp.read(len(self.HEADER))
 
 
834
        if line != self.HEADER:
 
 
835
            raise KnitHeaderError(badline=line)
 
 
838
        """Commit is a nop."""
 
 
841
        return '%s(%s)' % (self.__class__.__name__, self._filename)
 
 
844
class _KnitIndex(_KnitComponentFile):
 
 
845
    """Manages knit index file.
 
 
847
    The index is already kept in memory and read on startup, to enable
 
 
848
    fast lookups of revision information.  The cursor of the index
 
 
849
    file is always pointing to the end, making it easy to append
 
 
852
    _cache is a cache for fast mapping from version id to a Index
 
 
855
    _history is a cache for fast mapping from indexes to version ids.
 
 
857
    The index data format is dictionary compressed when it comes to
 
 
858
    parent references; a index entry may only have parents that with a
 
 
859
    lover index number.  As a result, the index is topological sorted.
 
 
861
    Duplicate entries may be written to the index for a single version id
 
 
862
    if this is done then the latter one completely replaces the former:
 
 
863
    this allows updates to correct version and parent information. 
 
 
864
    Note that the two entries may share the delta, and that successive
 
 
865
    annotations and references MUST point to the first entry.
 
 
868
    HEADER = "# bzr knit index 7\n"
 
 
870
    # speed of knit parsing went from 280 ms to 280 ms with slots addition.
 
 
871
    # __slots__ = ['_cache', '_history', '_transport', '_filename']
 
 
873
    def _cache_version(self, version_id, options, pos, size, parents):
 
 
874
        """Cache a version record in the history array and index cache.
 
 
876
        This is inlined into __init__ for performance. KEEP IN SYNC.
 
 
877
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
 
 
880
        # only want the _history index to reference the 1st index entry
 
 
882
        if version_id not in self._cache:
 
 
883
            index = len(self._history)
 
 
884
            self._history.append(version_id)
 
 
886
            index = self._cache[version_id][5]
 
 
887
        self._cache[version_id] = (version_id, 
 
 
894
    def __init__(self, transport, filename, mode, create=False):
 
 
895
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
 
897
        # position in _history is the 'official' index for a revision
 
 
898
        # but the values may have come from a newer entry.
 
 
899
        # so - wc -l of a knit index is != the number of uniqe names
 
 
902
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
 
907
                pb.update('read knit index', count, total)
 
 
908
                fp = self._transport.get(self._filename)
 
 
909
                self.check_header(fp)
 
 
910
                # readlines reads the whole file at once:
 
 
911
                # bad for transports like http, good for local disk
 
 
912
                # we save 60 ms doing this one change (
 
 
913
                # from calling readline each time to calling
 
 
915
                # probably what we want for nice behaviour on
 
 
916
                # http is a incremental readlines that yields, or
 
 
917
                # a check for local vs non local indexes,
 
 
918
                for l in fp.readlines():
 
 
922
                    #pb.update('read knit index', count, total)
 
 
923
                    # See self._parse_parents
 
 
925
                    for value in rec[4:]:
 
 
927
                            # uncompressed reference
 
 
928
                            parents.append(value[1:])
 
 
930
                            # this is 15/4000ms faster than isinstance,
 
 
932
                            # this function is called thousands of times a 
 
 
933
                            # second so small variations add up.
 
 
934
                            assert value.__class__ is str
 
 
935
                            parents.append(self._history[int(value)])
 
 
936
                    # end self._parse_parents
 
 
937
                    # self._cache_version(rec[0], 
 
 
942
                    # --- self._cache_version
 
 
943
                    # only want the _history index to reference the 1st 
 
 
944
                    # index entry for version_id
 
 
946
                    if version_id not in self._cache:
 
 
947
                        index = len(self._history)
 
 
948
                        self._history.append(version_id)
 
 
950
                        index = self._cache[version_id][5]
 
 
951
                    self._cache[version_id] = (version_id,
 
 
957
                    # --- self._cache_version 
 
 
958
            except NoSuchFile, e:
 
 
959
                if mode != 'w' or not create:
 
 
963
            pb.update('read knit index', total, total)
 
 
966
    def _parse_parents(self, compressed_parents):
 
 
967
        """convert a list of string parent values into version ids.
 
 
969
        ints are looked up in the index.
 
 
970
        .FOO values are ghosts and converted in to FOO.
 
 
972
        NOTE: the function is retained here for clarity, and for possible
 
 
973
              use in partial index reads. However bulk processing now has
 
 
974
              it inlined in __init__ for inner-loop optimisation.
 
 
977
        for value in compressed_parents:
 
 
979
                # uncompressed reference
 
 
980
                result.append(value[1:])
 
 
982
                # this is 15/4000ms faster than isinstance,
 
 
983
                # this function is called thousands of times a 
 
 
984
                # second so small variations add up.
 
 
985
                assert value.__class__ is str
 
 
986
                result.append(self._history[int(value)])
 
 
991
        for version_id, index in self._cache.iteritems():
 
 
992
            graph.append((version_id, index[4]))
 
 
995
    def get_ancestry(self, versions):
 
 
996
        """See VersionedFile.get_ancestry."""
 
 
997
        # get a graph of all the mentioned versions:
 
 
999
        pending = set(versions)
 
 
1001
            version = pending.pop()
 
 
1002
            parents = self._cache[version][4]
 
 
1003
            # got the parents ok
 
 
1005
            parents = [parent for parent in parents if parent in self._cache]
 
 
1006
            for parent in parents:
 
 
1007
                # if not completed and not a ghost
 
 
1008
                if parent not in graph:
 
 
1010
            graph[version] = parents
 
 
1011
        return topo_sort(graph.items())
 
 
1013
    def get_ancestry_with_ghosts(self, versions):
 
 
1014
        """See VersionedFile.get_ancestry_with_ghosts."""
 
 
1015
        # get a graph of all the mentioned versions:
 
 
1017
        pending = set(versions)
 
 
1019
            version = pending.pop()
 
 
1021
                parents = self._cache[version][4]
 
 
1027
                # got the parents ok
 
 
1028
                for parent in parents:
 
 
1029
                    if parent not in graph:
 
 
1031
                graph[version] = parents
 
 
1032
        return topo_sort(graph.items())
 
 
1034
    def num_versions(self):
 
 
1035
        return len(self._history)
 
 
1037
    __len__ = num_versions
 
 
1039
    def get_versions(self):
 
 
1040
        return self._history
 
 
1042
    def idx_to_name(self, idx):
 
 
1043
        return self._history[idx]
 
 
1045
    def lookup(self, version_id):
 
 
1046
        assert version_id in self._cache
 
 
1047
        return self._cache[version_id][5]
 
 
1049
    def _version_list_to_index(self, versions):
 
 
1051
        for version in versions:
 
 
1052
            if version in self._cache:
 
 
1053
                # -- inlined lookup() --
 
 
1054
                result_list.append(str(self._cache[version][5]))
 
 
1055
                # -- end lookup () --
 
 
1057
                result_list.append('.' + version.encode('utf-8'))
 
 
1058
        return ' '.join(result_list)
 
 
1060
    def add_version(self, version_id, options, pos, size, parents):
 
 
1061
        """Add a version record to the index."""
 
 
1062
        self._cache_version(version_id, options, pos, size, parents)
 
 
1064
        content = "%s %s %s %s %s\n" % (version_id.encode('utf-8'),
 
 
1068
                                        self._version_list_to_index(parents))
 
 
1069
        assert isinstance(content, str), 'content must be utf-8 encoded'
 
 
1070
        self._transport.append(self._filename, StringIO(content))
 
 
1072
    def has_version(self, version_id):
 
 
1073
        """True if the version is in the index."""
 
 
1074
        return self._cache.has_key(version_id)
 
 
1076
    def get_position(self, version_id):
 
 
1077
        """Return data position and size of specified version."""
 
 
1078
        return (self._cache[version_id][2], \
 
 
1079
                self._cache[version_id][3])
 
 
1081
    def get_method(self, version_id):
 
 
1082
        """Return compression method of specified version."""
 
 
1083
        options = self._cache[version_id][1]
 
 
1084
        if 'fulltext' in options:
 
 
1087
            assert 'line-delta' in options
 
 
1090
    def get_options(self, version_id):
 
 
1091
        return self._cache[version_id][1]
 
 
1093
    def get_parents(self, version_id):
 
 
1094
        """Return parents of specified version ignoring ghosts."""
 
 
1095
        return [parent for parent in self._cache[version_id][4] 
 
 
1096
                if parent in self._cache]
 
 
1098
    def get_parents_with_ghosts(self, version_id):
 
 
1099
        """Return parents of specified version wth ghosts."""
 
 
1100
        return self._cache[version_id][4] 
 
 
1102
    def check_versions_present(self, version_ids):
 
 
1103
        """Check that all specified versions are present."""
 
 
1104
        version_ids = set(version_ids)
 
 
1105
        for version_id in list(version_ids):
 
 
1106
            if version_id in self._cache:
 
 
1107
                version_ids.remove(version_id)
 
 
1109
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
 
1112
class _KnitData(_KnitComponentFile):
 
 
1113
    """Contents of the knit data file"""
 
 
1115
    HEADER = "# bzr knit data 7\n"
 
 
1117
    def __init__(self, transport, filename, mode, create=False):
 
 
1118
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
 
1120
        self._checked = False
 
 
1122
            self._transport.put(self._filename, StringIO(''))
 
 
1125
    def clear_cache(self):
 
 
1126
        """Clear the record cache."""
 
 
1129
    def _open_file(self):
 
 
1130
        if self._file is None:
 
 
1132
                self._file = self._transport.get(self._filename)
 
 
1137
    def _record_to_data(self, version_id, digest, lines):
 
 
1138
        """Convert version_id, digest, lines into a raw data block.
 
 
1140
        :return: (len, a StringIO instance with the raw data ready to read.)
 
 
1143
        data_file = GzipFile(None, mode='wb', fileobj=sio)
 
 
1144
        data_file.writelines(chain(
 
 
1145
            ["version %s %d %s\n" % (version_id.encode('utf-8'), 
 
 
1149
            ["end %s\n" % version_id.encode('utf-8')]))
 
 
1156
    def add_raw_record(self, raw_data):
 
 
1157
        """Append a prepared record to the data file."""
 
 
1158
        assert isinstance(raw_data, str), 'data must be plain bytes'
 
 
1159
        start_pos = self._transport.append(self._filename, StringIO(raw_data))
 
 
1160
        return start_pos, len(raw_data)
 
 
1162
    def add_record(self, version_id, digest, lines):
 
 
1163
        """Write new text record to disk.  Returns the position in the
 
 
1164
        file where it was written."""
 
 
1165
        size, sio = self._record_to_data(version_id, digest, lines)
 
 
1167
        self._records[version_id] = (digest, lines)
 
 
1169
        start_pos = self._transport.append(self._filename, sio)
 
 
1170
        return start_pos, size
 
 
1172
    def _parse_record_header(self, version_id, raw_data):
 
 
1173
        """Parse a record header for consistency.
 
 
1175
        :return: the header and the decompressor stream.
 
 
1176
                 as (stream, header_record)
 
 
1178
        df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
 
 
1179
        rec = df.readline().split()
 
 
1181
            raise KnitCorrupt(self._filename, 'unexpected number of elements in record header')
 
 
1182
        if rec[1].decode('utf-8')!= version_id:
 
 
1183
            raise KnitCorrupt(self._filename, 
 
 
1184
                              'unexpected version, wanted %r, got %r' % (
 
 
1185
                                version_id, rec[1]))
 
 
1188
    def _parse_record(self, version_id, data):
 
 
1190
        # 4168 calls in 2880 217 internal
 
 
1191
        # 4168 calls to _parse_record_header in 2121
 
 
1192
        # 4168 calls to readlines in 330
 
 
1193
        df, rec = self._parse_record_header(version_id, data)
 
 
1194
        record_contents = df.readlines()
 
 
1195
        l = record_contents.pop()
 
 
1196
        assert len(record_contents) == int(rec[2])
 
 
1197
        if l.decode('utf-8') != 'end %s\n' % version_id:
 
 
1198
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
 
 
1201
        return record_contents, rec[3]
 
 
1203
    def read_records_iter_raw(self, records):
 
 
1204
        """Read text records from data file and yield raw data.
 
 
1206
        This unpacks enough of the text record to validate the id is
 
 
1207
        as expected but thats all.
 
 
1209
        It will actively recompress currently cached records on the
 
 
1210
        basis that that is cheaper than I/O activity.
 
 
1213
        for version_id, pos, size in records:
 
 
1214
            if version_id not in self._records:
 
 
1215
                needed_records.append((version_id, pos, size))
 
 
1217
        # setup an iterator of the external records:
 
 
1218
        # uses readv so nice and fast we hope.
 
 
1219
        if len(needed_records):
 
 
1220
            # grab the disk data needed.
 
 
1221
            raw_records = self._transport.readv(self._filename,
 
 
1222
                [(pos, size) for version_id, pos, size in needed_records])
 
 
1224
        for version_id, pos, size in records:
 
 
1225
            if version_id in self._records:
 
 
1226
                # compress a new version
 
 
1227
                size, sio = self._record_to_data(version_id,
 
 
1228
                                                 self._records[version_id][0],
 
 
1229
                                                 self._records[version_id][1])
 
 
1230
                yield version_id, sio.getvalue()
 
 
1232
                pos, data = raw_records.next()
 
 
1233
                # validate the header
 
 
1234
                df, rec = self._parse_record_header(version_id, data)
 
 
1236
                yield version_id, data
 
 
1239
    def read_records_iter(self, records):
 
 
1240
        """Read text records from data file and yield result.
 
 
1242
        Each passed record is a tuple of (version_id, pos, len) and
 
 
1243
        will be read in the given order.  Yields (version_id,
 
 
1247
        # 60890  calls for 4168 extractions in 5045, 683 internal.
 
 
1248
        # 4168   calls to readv              in 1411
 
 
1249
        # 4168   calls to parse_record       in 2880
 
 
1252
        for version_id, pos, size in records:
 
 
1253
            if version_id not in self._records:
 
 
1254
                needed_records.append((version_id, pos, size))
 
 
1256
        if len(needed_records):
 
 
1257
            # We take it that the transport optimizes the fetching as good
 
 
1258
            # as possible (ie, reads continous ranges.)
 
 
1259
            response = self._transport.readv(self._filename,
 
 
1260
                [(pos, size) for version_id, pos, size in needed_records])
 
 
1262
            for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
 
 
1263
                content, digest = self._parse_record(record_id, data)
 
 
1264
                self._records[record_id] = (digest, content)
 
 
1266
        for version_id, pos, size in records:
 
 
1267
            yield version_id, list(self._records[version_id][1]), self._records[version_id][0]
 
 
1269
    def read_records(self, records):
 
 
1270
        """Read records into a dictionary."""
 
 
1272
        for record_id, content, digest in self.read_records_iter(records):
 
 
1273
            components[record_id] = (content, digest)
 
 
1277
class InterKnit(InterVersionedFile):
 
 
1278
    """Optimised code paths for knit to knit operations."""
 
 
1280
    _matching_file_factory = KnitVersionedFile
 
 
1283
    def is_compatible(source, target):
 
 
1284
        """Be compatible with knits.  """
 
 
1286
            return (isinstance(source, KnitVersionedFile) and
 
 
1287
                    isinstance(target, KnitVersionedFile))
 
 
1288
        except AttributeError:
 
 
1291
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
 
1292
        """See InterVersionedFile.join."""
 
 
1293
        assert isinstance(self.source, KnitVersionedFile)
 
 
1294
        assert isinstance(self.target, KnitVersionedFile)
 
 
1296
        if version_ids is None:
 
 
1297
            version_ids = self.source.versions()
 
 
1299
            if not ignore_missing:
 
 
1300
                self.source._check_versions_present(version_ids)
 
 
1302
                version_ids = set(self.source.versions()).intersection(
 
 
1308
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
 
1310
            version_ids = list(version_ids)
 
 
1311
            if None in version_ids:
 
 
1312
                version_ids.remove(None)
 
 
1314
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
 
 
1315
            this_versions = set(self.target._index.get_versions())
 
 
1316
            needed_versions = self.source_ancestry - this_versions
 
 
1317
            cross_check_versions = self.source_ancestry.intersection(this_versions)
 
 
1318
            mismatched_versions = set()
 
 
1319
            for version in cross_check_versions:
 
 
1320
                # scan to include needed parents.
 
 
1321
                n1 = set(self.target.get_parents_with_ghosts(version))
 
 
1322
                n2 = set(self.source.get_parents_with_ghosts(version))
 
 
1324
                    # FIXME TEST this check for cycles being introduced works
 
 
1325
                    # the logic is we have a cycle if in our graph we are an
 
 
1326
                    # ancestor of any of the n2 revisions.
 
 
1332
                            parent_ancestors = self.source.get_ancestry(parent)
 
 
1333
                            if version in parent_ancestors:
 
 
1334
                                raise errors.GraphCycleError([parent, version])
 
 
1335
                    # ensure this parent will be available later.
 
 
1336
                    new_parents = n2.difference(n1)
 
 
1337
                    needed_versions.update(new_parents.difference(this_versions))
 
 
1338
                    mismatched_versions.add(version)
 
 
1340
            if not needed_versions and not cross_check_versions:
 
 
1342
            full_list = topo_sort(self.source.get_graph())
 
 
1344
            version_list = [i for i in full_list if (not self.target.has_version(i)
 
 
1345
                            and i in needed_versions)]
 
 
1349
            copy_queue_records = []
 
 
1351
            for version_id in version_list:
 
 
1352
                options = self.source._index.get_options(version_id)
 
 
1353
                parents = self.source._index.get_parents_with_ghosts(version_id)
 
 
1354
                # check that its will be a consistent copy:
 
 
1355
                for parent in parents:
 
 
1356
                    # if source has the parent, we must :
 
 
1357
                    # * already have it or
 
 
1358
                    # * have it scheduled already
 
 
1359
                    # otherwise we dont care
 
 
1360
                    assert (self.target.has_version(parent) or
 
 
1361
                            parent in copy_set or
 
 
1362
                            not self.source.has_version(parent))
 
 
1363
                data_pos, data_size = self.source._index.get_position(version_id)
 
 
1364
                copy_queue_records.append((version_id, data_pos, data_size))
 
 
1365
                copy_queue.append((version_id, options, parents))
 
 
1366
                copy_set.add(version_id)
 
 
1368
            # data suck the join:
 
 
1370
            total = len(version_list)
 
 
1371
            # we want the raw gzip for bulk copying, but the record validated
 
 
1372
            # just enough to be sure its the right one.
 
 
1373
            # TODO: consider writev or write combining to reduce 
 
 
1374
            # death of a thousand cuts feeling.
 
 
1375
            for (version_id, raw_data), \
 
 
1376
                (version_id2, options, parents) in \
 
 
1377
                izip(self.source._data.read_records_iter_raw(copy_queue_records),
 
 
1379
                assert version_id == version_id2, 'logic error, inconsistent results'
 
 
1381
                pb.update("Joining knit", count, total)
 
 
1382
                pos, size = self.target._data.add_raw_record(raw_data)
 
 
1383
                self.target._index.add_version(version_id, options, pos, size, parents)
 
 
1385
            for version in mismatched_versions:
 
 
1386
                # FIXME RBC 20060309 is this needed?
 
 
1387
                n1 = set(self.target.get_parents_with_ghosts(version))
 
 
1388
                n2 = set(self.source.get_parents_with_ghosts(version))
 
 
1389
                # write a combined record to our history preserving the current 
 
 
1390
                # parents as first in the list
 
 
1391
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
 
 
1392
                self.target.fix_parents(version, new_parents)
 
 
1398
InterVersionedFile.register_optimiser(InterKnit)
 
 
1401
# make GzipFile faster:
 
 
1404
from gzip import U32, LOWU32, FEXTRA, FCOMMENT, FNAME, FHCRC
 
 
1405
class GzipFile(gzip.GzipFile):
 
 
1406
    """Knit tuned version of GzipFile.
 
 
1408
    This is based on the following lsprof stats:
 
 
1409
    python 2.4 stock GzipFile write:
 
 
1410
    58971      0   5644.3090   2721.4730   gzip:193(write)
 
 
1411
    +58971     0   1159.5530   1159.5530   +<built-in method compress>
 
 
1412
    +176913    0    987.0320    987.0320   +<len>
 
 
1413
    +58971     0    423.1450    423.1450   +<zlib.crc32>
 
 
1414
    +58971     0    353.1060    353.1060   +<method 'write' of 'cStringIO.
 
 
1416
    tuned GzipFile write:
 
 
1417
    58971      0   4477.2590   2103.1120   bzrlib.knit:1250(write)
 
 
1418
    +58971     0   1297.7620   1297.7620   +<built-in method compress>
 
 
1419
    +58971     0    406.2160    406.2160   +<zlib.crc32>
 
 
1420
    +58971     0    341.9020    341.9020   +<method 'write' of 'cStringIO.
 
 
1422
    +58971     0    328.2670    328.2670   +<len>
 
 
1425
    Yes, its only 1.6 seconds, but they add up.
 
 
1428
    def _add_read_data(self, data):
 
 
1430
        # temp var for len(data) and switch to +='s.
 
 
1432
        len_data = len(data)
 
 
1433
        self.crc = zlib.crc32(data, self.crc)
 
 
1434
        self.extrabuf += data
 
 
1435
        self.extrasize += len_data
 
 
1436
        self.size += len_data
 
 
1438
    def _read(self, size=1024):
 
 
1439
        # various optimisations:
 
 
1440
        # reduces lsprof count from 2500 to 
 
 
1441
        # 8337 calls in 1272, 365 internal
 
 
1442
        if self.fileobj is None:
 
 
1443
            raise EOFError, "Reached EOF"
 
 
1445
        if self._new_member:
 
 
1446
            # If the _new_member flag is set, we have to
 
 
1447
            # jump to the next member, if there is one.
 
 
1449
            # First, check if we're at the end of the file;
 
 
1450
            # if so, it's time to stop; no more members to read.
 
 
1451
            next_header_bytes = self.fileobj.read(10)
 
 
1452
            if next_header_bytes == '':
 
 
1453
                raise EOFError, "Reached EOF"
 
 
1456
            self._read_gzip_header(next_header_bytes)
 
 
1457
            self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
 
 
1458
            self._new_member = False
 
 
1460
        # Read a chunk of data from the file
 
 
1461
        buf = self.fileobj.read(size)
 
 
1463
        # If the EOF has been reached, flush the decompression object
 
 
1464
        # and mark this object as finished.
 
 
1467
            self._add_read_data(self.decompress.flush())
 
 
1468
            assert len(self.decompress.unused_data) >= 8, "what does flush do?"
 
 
1470
            # tell the driving read() call we have stuffed all the data
 
 
1472
            raise EOFError, 'Reached EOF'
 
 
1474
        self._add_read_data(self.decompress.decompress(buf))
 
 
1476
        if self.decompress.unused_data != "":
 
 
1477
            # Ending case: we've come to the end of a member in the file,
 
 
1478
            # so seek back to the start of the data for the next member which
 
 
1479
            # is the length of the decompress objects unused data - the first
 
 
1480
            # 8 bytes for the end crc and size records.
 
 
1482
            # so seek back to the start of the unused data, finish up
 
 
1483
            # this member, and read a new gzip header.
 
 
1484
            # (The number of bytes to seek back is the length of the unused
 
 
1485
            # data, minus 8 because those 8 bytes are part of this member.
 
 
1486
            seek_length = len (self.decompress.unused_data) - 8
 
 
1488
                assert seek_length > 0
 
 
1489
                self.fileobj.seek(-seek_length, 1)
 
 
1491
            # Check the CRC and file size, and set the flag so we read
 
 
1492
            # a new member on the next call
 
 
1494
            self._new_member = True
 
 
1496
    def _read_eof(self):
 
 
1497
        """tuned to reduce function calls and eliminate file seeking:
 
 
1499
        reduces lsprof count from 800 to 288
 
 
1501
        avoid U32 call by using struct format L
 
 
1504
        # We've read to the end of the file, so we should have 8 bytes of 
 
 
1505
        # unused data in the decompressor. If we dont, there is a corrupt file.
 
 
1506
        # We use these 8 bytes to calculate the CRC and the recorded file size.
 
 
1507
        # We then check the that the computed CRC and size of the
 
 
1508
        # uncompressed data matches the stored values.  Note that the size
 
 
1509
        # stored is the true file size mod 2**32.
 
 
1510
        crc32, isize = struct.unpack("<LL", self.decompress.unused_data[0:8])
 
 
1511
        # note that isize is unsigned - it can exceed 2GB
 
 
1512
        if crc32 != U32(self.crc):
 
 
1513
            raise IOError, "CRC check failed"
 
 
1514
        elif isize != LOWU32(self.size):
 
 
1515
            raise IOError, "Incorrect length of data produced"
 
 
1517
    def _read_gzip_header(self, bytes=None):
 
 
1518
        """Supply bytes if the minimum header size is already read.
 
 
1520
        :param bytes: 10 bytes of header data.
 
 
1522
        """starting cost: 300 in 3998
 
 
1523
        15998 reads from 3998 calls
 
 
1527
            bytes = self.fileobj.read(10)
 
 
1529
        if magic != '\037\213':
 
 
1530
            raise IOError, 'Not a gzipped file'
 
 
1531
        method = ord(bytes[2:3])
 
 
1533
            raise IOError, 'Unknown compression method'
 
 
1534
        flag = ord(bytes[3:4])
 
 
1535
        # modtime = self.fileobj.read(4) (bytes [4:8])
 
 
1536
        # extraflag = self.fileobj.read(1) (bytes[8:9])
 
 
1537
        # os = self.fileobj.read(1) (bytes[9:10])
 
 
1538
        # self.fileobj.read(6)
 
 
1541
            # Read & discard the extra field, if present
 
 
1542
            xlen = ord(self.fileobj.read(1))
 
 
1543
            xlen = xlen + 256*ord(self.fileobj.read(1))
 
 
1544
            self.fileobj.read(xlen)
 
 
1546
            # Read and discard a null-terminated string containing the filename
 
 
1548
                s = self.fileobj.read(1)
 
 
1549
                if not s or s=='\000':
 
 
1552
            # Read and discard a null-terminated string containing a comment
 
 
1554
                s = self.fileobj.read(1)
 
 
1555
                if not s or s=='\000':
 
 
1558
            self.fileobj.read(2)     # Read & discard the 16-bit header CRC
 
 
1560
    def readline(self, size=-1):
 
 
1561
        """Tuned to remove buffer length calls in _unread and...
 
 
1563
        also removes multiple len(c) calls, inlines _unread,
 
 
1564
        total savings - lsprof 5800 to 5300
 
 
1567
        8176 calls to read() in 1684
 
 
1568
        changing the min chunk size to 200 halved all the cache misses
 
 
1569
        leading to a drop to:
 
 
1571
        4168 call to read() in 1646
 
 
1572
        - i.e. just reduced the function call overhead. May be worth 
 
 
1575
        if size < 0: size = sys.maxint
 
 
1577
        readsize = min(200, size)    # Read from the file in small chunks
 
 
1580
                return "".join(bufs) # Return resulting line
 
 
1583
            c = self.read(readsize)
 
 
1584
            # number of bytes read
 
 
1587
            if size is not None:
 
 
1588
                # We set i=size to break out of the loop under two
 
 
1589
                # conditions: 1) there's no newline, and the chunk is
 
 
1590
                # larger than size, or 2) there is a newline, but the
 
 
1591
                # resulting line would be longer than 'size'.
 
 
1592
                if i==-1 and len_c > size: i=size-1
 
 
1593
                elif size <= i: i = size -1
 
 
1595
            if i >= 0 or c == '':
 
 
1596
                # if i>= 0 we have a newline or have triggered the above
 
 
1597
                # if size is not None condition.
 
 
1598
                # if c == '' its EOF.
 
 
1599
                bufs.append(c[:i+1])    # Add portion of last chunk
 
 
1600
                # -- inlined self._unread --
 
 
1601
                ## self._unread(c[i+1:], len_c - i)   # Push back rest of chunk
 
 
1602
                self.extrabuf = c[i+1:] + self.extrabuf
 
 
1603
                self.extrasize = len_c - i + self.extrasize
 
 
1604
                self.offset -= len_c - i
 
 
1605
                # -- end inlined self._unread --
 
 
1606
                return ''.join(bufs)    # Return resulting line
 
 
1608
            # Append chunk to list, decrease 'size',
 
 
1611
            readsize = min(size, readsize * 2)
 
 
1613
    def readlines(self, sizehint=0):
 
 
1614
        # optimise to avoid all the buffer manipulation
 
 
1615
        # lsprof changed from:
 
 
1616
        # 4168 calls in 5472 with 32000 calls to readline()
 
 
1618
        # 4168 calls in 417.
 
 
1619
        # Negative numbers result in reading all the lines
 
 
1622
        content = self.read(sizehint)
 
 
1623
        return content.splitlines(True)
 
 
1625
    def _unread(self, buf, len_buf=None):
 
 
1626
        """tuned to remove unneeded len calls.
 
 
1628
        because this is such an inner routine in readline, and readline is
 
 
1629
        in many inner loops, this has been inlined into readline().
 
 
1631
        The len_buf parameter combined with the reduction in len calls dropped
 
 
1632
        the lsprof ms count for this routine on my test data from 800 to 200 - 
 
 
1637
        self.extrabuf = buf + self.extrabuf
 
 
1638
        self.extrasize = len_buf + self.extrasize
 
 
1639
        self.offset -= len_buf
 
 
1641
    def write(self, data):
 
 
1642
        if self.mode != gzip.WRITE:
 
 
1644
            raise IOError(errno.EBADF, "write() on read-only GzipFile object")
 
 
1646
        if self.fileobj is None:
 
 
1647
            raise ValueError, "write() on closed GzipFile object"
 
 
1648
        data_len = len(data)
 
 
1650
            self.size = self.size + data_len
 
 
1651
            self.crc = zlib.crc32(data, self.crc)
 
 
1652
            self.fileobj.write( self.compress.compress(data) )
 
 
1653
            self.offset += data_len
 
 
1655
    def writelines(self, lines):
 
 
1656
        # profiling indicated a significant overhead 
 
 
1657
        # calling write for each line.
 
 
1658
        # this batch call is a lot faster :).
 
 
1659
        # (4 seconds to 1 seconds for the sample upgrades I was testing).
 
 
1660
        self.write(''.join(lines))
 
 
1663
class SequenceMatcher(difflib.SequenceMatcher):
 
 
1664
    """Knit tuned sequence matcher.
 
 
1666
    This is based on profiling of difflib which indicated some improvements
 
 
1667
    for our usage pattern.
 
 
1670
    def find_longest_match(self, alo, ahi, blo, bhi):
 
 
1671
        """Find longest matching block in a[alo:ahi] and b[blo:bhi].
 
 
1673
        If isjunk is not defined:
 
 
1675
        Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
 
 
1676
            alo <= i <= i+k <= ahi
 
 
1677
            blo <= j <= j+k <= bhi
 
 
1678
        and for all (i',j',k') meeting those conditions,
 
 
1681
            and if i == i', j <= j'
 
 
1683
        In other words, of all maximal matching blocks, return one that
 
 
1684
        starts earliest in a, and of all those maximal matching blocks that
 
 
1685
        start earliest in a, return the one that starts earliest in b.
 
 
1687
        >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
 
 
1688
        >>> s.find_longest_match(0, 5, 0, 9)
 
 
1691
        If isjunk is defined, first the longest matching block is
 
 
1692
        determined as above, but with the additional restriction that no
 
 
1693
        junk element appears in the block.  Then that block is extended as
 
 
1694
        far as possible by matching (only) junk elements on both sides.  So
 
 
1695
        the resulting block never matches on junk except as identical junk
 
 
1696
        happens to be adjacent to an "interesting" match.
 
 
1698
        Here's the same example as before, but considering blanks to be
 
 
1699
        junk.  That prevents " abcd" from matching the " abcd" at the tail
 
 
1700
        end of the second sequence directly.  Instead only the "abcd" can
 
 
1701
        match, and matches the leftmost "abcd" in the second sequence:
 
 
1703
        >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
 
 
1704
        >>> s.find_longest_match(0, 5, 0, 9)
 
 
1707
        If no blocks match, return (alo, blo, 0).
 
 
1709
        >>> s = SequenceMatcher(None, "ab", "c")
 
 
1710
        >>> s.find_longest_match(0, 2, 0, 1)
 
 
1714
        # CAUTION:  stripping common prefix or suffix would be incorrect.
 
 
1718
        # Longest matching block is "ab", but if common prefix is
 
 
1719
        # stripped, it's "a" (tied with "b").  UNIX(tm) diff does so
 
 
1720
        # strip, so ends up claiming that ab is changed to acab by
 
 
1721
        # inserting "ca" in the middle.  That's minimal but unintuitive:
 
 
1722
        # "it's obvious" that someone inserted "ac" at the front.
 
 
1723
        # Windiff ends up at the same place as diff, but by pairing up
 
 
1724
        # the unique 'b's and then matching the first two 'a's.
 
 
1726
        a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
 
 
1727
        besti, bestj, bestsize = alo, blo, 0
 
 
1728
        # find longest junk-free match
 
 
1729
        # during an iteration of the loop, j2len[j] = length of longest
 
 
1730
        # junk-free match ending with a[i-1] and b[j]
 
 
1734
        for i in xrange(alo, ahi):
 
 
1735
            # look at all instances of a[i] in b; note that because
 
 
1736
            # b2j has no junk keys, the loop is skipped if a[i] is junk
 
 
1737
            j2lenget = j2len.get
 
 
1740
            # changing b2j.get(a[i], nothing) to a try:Keyerror pair produced the
 
 
1741
            # following improvement
 
 
1742
            #     704  0   4650.5320   2620.7410   bzrlib.knit:1336(find_longest_match)
 
 
1743
            # +326674  0   1655.1210   1655.1210   +<method 'get' of 'dict' objects>
 
 
1744
            #  +76519  0    374.6700    374.6700   +<method 'has_key' of 'dict' objects>
 
 
1746
            #     704  0   3733.2820   2209.6520   bzrlib.knit:1336(find_longest_match)
 
 
1747
            #  +211400 0   1147.3520   1147.3520   +<method 'get' of 'dict' objects>
 
 
1748
            #  +76519  0    376.2780    376.2780   +<method 'has_key' of 'dict' objects>
 
 
1760
                        k = newj2len[j] = 1 + j2lenget(-1 + j, 0)
 
 
1762
                            besti, bestj, bestsize = 1 + i-k, 1 + j-k, k
 
 
1765
        # Extend the best by non-junk elements on each end.  In particular,
 
 
1766
        # "popular" non-junk elements aren't in b2j, which greatly speeds
 
 
1767
        # the inner loop above, but also means "the best" match so far
 
 
1768
        # doesn't contain any junk *or* popular non-junk elements.
 
 
1769
        while besti > alo and bestj > blo and \
 
 
1770
              not isbjunk(b[bestj-1]) and \
 
 
1771
              a[besti-1] == b[bestj-1]:
 
 
1772
            besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
 
 
1773
        while besti+bestsize < ahi and bestj+bestsize < bhi and \
 
 
1774
              not isbjunk(b[bestj+bestsize]) and \
 
 
1775
              a[besti+bestsize] == b[bestj+bestsize]:
 
 
1778
        # Now that we have a wholly interesting match (albeit possibly
 
 
1779
        # empty!), we may as well suck up the matching junk on each
 
 
1780
        # side of it too.  Can't think of a good reason not to, and it
 
 
1781
        # saves post-processing the (possibly considerable) expense of
 
 
1782
        # figuring out what to do with it.  In the case of an empty
 
 
1783
        # interesting match, this is clearly the right thing to do,
 
 
1784
        # because no other kind of match is possible in the regions.
 
 
1785
        while besti > alo and bestj > blo and \
 
 
1786
              isbjunk(b[bestj-1]) and \
 
 
1787
              a[besti-1] == b[bestj-1]:
 
 
1788
            besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
 
 
1789
        while besti+bestsize < ahi and bestj+bestsize < bhi and \
 
 
1790
              isbjunk(b[bestj+bestsize]) and \
 
 
1791
              a[besti+bestsize] == b[bestj+bestsize]:
 
 
1792
            bestsize = bestsize + 1
 
 
1794
        return besti, bestj, bestsize