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
 
 
69
from difflib import SequenceMatcher
 
 
70
from gzip import GzipFile
 
 
71
from itertools import izip
 
 
76
import bzrlib.errors as errors
 
 
77
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
 
 
78
        InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
 
 
79
        RevisionNotPresent, RevisionAlreadyPresent
 
 
80
from bzrlib.trace import mutter
 
 
81
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
 
 
83
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
 
 
84
from bzrlib.tsort import topo_sort
 
 
87
# TODO: Split out code specific to this format into an associated object.
 
 
89
# TODO: Can we put in some kind of value to check that the index and data
 
 
90
# files belong together?
 
 
92
# TODO: accomodate binaries, perhaps by storing a byte count
 
 
94
# TODO: function to check whole file
 
 
96
# TODO: atomically append data, then measure backwards from the cursor
 
 
97
# position after writing to work out where it was located.  we may need to
 
 
98
# bypass python file buffering.
 
 
100
DATA_SUFFIX = '.knit'
 
 
101
INDEX_SUFFIX = '.kndx'
 
 
104
class KnitContent(object):
 
 
105
    """Content of a knit version to which deltas can be applied."""
 
 
107
    def __init__(self, lines):
 
 
110
    def annotate_iter(self):
 
 
111
        """Yield tuples of (origin, text) for each content line."""
 
 
112
        for origin, text in self._lines:
 
 
116
        """Return a list of (origin, text) tuples."""
 
 
117
        return list(self.annotate_iter())
 
 
119
    def apply_delta(self, delta):
 
 
120
        """Apply delta to this content."""
 
 
122
        for start, end, count, lines in delta:
 
 
123
            self._lines[offset+start:offset+end] = lines
 
 
124
            offset = offset + (start - end) + count
 
 
126
    def line_delta_iter(self, new_lines):
 
 
127
        """Generate line-based delta from new_lines to this content."""
 
 
128
        new_texts = [text for origin, text in new_lines._lines]
 
 
129
        old_texts = [text for origin, text in self._lines]
 
 
130
        s = difflib.SequenceMatcher(None, old_texts, new_texts)
 
 
131
        for op in s.get_opcodes():
 
 
134
            yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
 
 
136
    def line_delta(self, new_lines):
 
 
137
        return list(self.line_delta_iter(new_lines))
 
 
140
        return [text for origin, text in self._lines]
 
 
143
class _KnitFactory(object):
 
 
144
    """Base factory for creating content objects."""
 
 
146
    def make(self, lines, version):
 
 
147
        num_lines = len(lines)
 
 
148
        return KnitContent(zip([version] * num_lines, lines))
 
 
151
class KnitAnnotateFactory(_KnitFactory):
 
 
152
    """Factory for creating annotated Content objects."""
 
 
156
    def parse_fulltext(self, content, version):
 
 
157
        """Convert fulltext to internal representation
 
 
159
        fulltext content is of the format
 
 
160
        revid(utf8) plaintext\n
 
 
161
        internal representation is of the format:
 
 
166
            origin, text = line.split(' ', 1)
 
 
167
            lines.append((origin.decode('utf-8'), text))
 
 
168
        return KnitContent(lines)
 
 
170
    def parse_line_delta_iter(self, lines):
 
 
171
        """Convert a line based delta into internal representation.
 
 
173
        line delta is in the form of:
 
 
174
        intstart intend intcount
 
 
176
        revid(utf8) newline\n
 
 
177
        internal represnetation is
 
 
178
        (start, end, count, [1..count tuples (revid, newline)])
 
 
181
            header = lines.pop(0)
 
 
182
            start, end, c = [int(n) for n in header.split(',')]
 
 
185
                origin, text = lines.pop(0).split(' ', 1)
 
 
186
                contents.append((origin.decode('utf-8'), text))
 
 
187
            yield start, end, c, contents
 
 
189
    def parse_line_delta(self, lines, version):
 
 
190
        return list(self.parse_line_delta_iter(lines))
 
 
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_iter 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 clear_cache(self):
 
 
293
        """Clear the data cache only."""
 
 
294
        self._data.clear_cache()
 
 
296
    def copy_to(self, name, transport):
 
 
297
        """See VersionedFile.copy_to()."""
 
 
298
        # copy the current index to a temp index to avoid racing with local
 
 
300
        transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
 
 
302
        transport.put(name + DATA_SUFFIX, self._data._open_file())
 
 
303
        # rename the copied index into place
 
 
304
        transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
 
 
306
    def create_empty(self, name, transport, mode=None):
 
 
307
        return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
 
 
309
    def _fix_parents(self, version, new_parents):
 
 
310
        """Fix the parents list for version.
 
 
312
        This is done by appending a new version to the index
 
 
313
        with identical data except for the parents list.
 
 
314
        the parents list must be a superset of the current
 
 
317
        current_values = self._index._cache[version]
 
 
318
        assert set(current_values[4]).difference(set(new_parents)) == set()
 
 
319
        self._index.add_version(version,
 
 
325
    def get_graph_with_ghosts(self):
 
 
326
        """See VersionedFile.get_graph_with_ghosts()."""
 
 
327
        graph_items = self._index.get_graph()
 
 
328
        return dict(graph_items)
 
 
332
        """See VersionedFile.get_suffixes()."""
 
 
333
        return [DATA_SUFFIX, INDEX_SUFFIX]
 
 
335
    def has_ghost(self, version_id):
 
 
336
        """True if there is a ghost reference in the file to version_id."""
 
 
338
        if self.has_version(version_id):
 
 
340
        # optimisable if needed by memoising the _ghosts set.
 
 
341
        items = self._index.get_graph()
 
 
342
        for node, parents in items:
 
 
343
            for parent in parents:
 
 
344
                if parent not in self._index._cache:
 
 
345
                    if parent == version_id:
 
 
350
        """See VersionedFile.versions."""
 
 
351
        return self._index.get_versions()
 
 
353
    def has_version(self, version_id):
 
 
354
        """See VersionedFile.has_version."""
 
 
355
        return self._index.has_version(version_id)
 
 
357
    __contains__ = has_version
 
 
359
    def _merge_annotations(self, content, parents):
 
 
360
        """Merge annotations for content.  This is done by comparing
 
 
361
        the annotations based on changed to the text."""
 
 
362
        for parent_id in parents:
 
 
363
            merge_content = self._get_content(parent_id)
 
 
364
            seq = SequenceMatcher(None, merge_content.text(), content.text())
 
 
365
            for i, j, n in seq.get_matching_blocks():
 
 
368
                content._lines[j:j+n] = merge_content._lines[i:i+n]
 
 
370
    def _get_components(self, version_id):
 
 
371
        """Return a list of (version_id, method, data) tuples that
 
 
372
        makes up version specified by version_id of the knit.
 
 
374
        The components should be applied in the order of the returned
 
 
377
        The basis knit will be used to the largest extent possible
 
 
378
        since it is assumed that accesses to it is faster.
 
 
380
        # needed_revisions holds a list of (method, version_id) of
 
 
381
        # versions that is needed to be fetched to construct the final
 
 
382
        # version of the file.
 
 
384
        # basis_revisions is a list of versions that needs to be
 
 
385
        # fetched but exists in the basis knit.
 
 
387
        basis = self.basis_knit
 
 
394
            if basis and basis._index.has_version(cursor):
 
 
396
                basis_versions.append(cursor)
 
 
397
            method = picked_knit._index.get_method(cursor)
 
 
398
            needed_versions.append((method, cursor))
 
 
399
            if method == 'fulltext':
 
 
401
            cursor = picked_knit.get_parents(cursor)[0]
 
 
406
            for comp_id in basis_versions:
 
 
407
                data_pos, data_size = basis._index.get_data_position(comp_id)
 
 
408
                records.append((piece_id, data_pos, data_size))
 
 
409
            components.update(basis._data.read_records(records))
 
 
412
        for comp_id in [vid for method, vid in needed_versions
 
 
413
                        if vid not in basis_versions]:
 
 
414
            data_pos, data_size = self._index.get_position(comp_id)
 
 
415
            records.append((comp_id, data_pos, data_size))
 
 
416
        components.update(self._data.read_records(records))
 
 
418
        # get_data_records returns a mapping with the version id as
 
 
419
        # index and the value as data.  The order the components need
 
 
420
        # to be applied is held by needed_versions (reversed).
 
 
422
        for method, comp_id in reversed(needed_versions):
 
 
423
            out.append((comp_id, method, components[comp_id]))
 
 
427
    def _get_content(self, version_id):
 
 
428
        """Returns a content object that makes up the specified
 
 
430
        if not self.has_version(version_id):
 
 
431
            raise RevisionNotPresent(version_id, self.filename)
 
 
433
        if self.basis_knit and version_id in self.basis_knit:
 
 
434
            return self.basis_knit._get_content(version_id)
 
 
437
        components = self._get_components(version_id)
 
 
438
        for component_id, method, (data, digest) in components:
 
 
439
            version_idx = self._index.lookup(component_id)
 
 
440
            if method == 'fulltext':
 
 
441
                assert content is None
 
 
442
                content = self.factory.parse_fulltext(data, version_idx)
 
 
443
            elif method == 'line-delta':
 
 
444
                delta = self.factory.parse_line_delta(data, version_idx)
 
 
445
                content.apply_delta(delta)
 
 
447
        if 'no-eol' in self._index.get_options(version_id):
 
 
448
            line = content._lines[-1][1].rstrip('\n')
 
 
449
            content._lines[-1] = (content._lines[-1][0], line)
 
 
451
        if sha_strings(content.text()) != digest:
 
 
452
            raise KnitCorrupt(self.filename, 'sha-1 does not match')
 
 
456
    def _check_versions_present(self, version_ids):
 
 
457
        """Check that all specified versions are present."""
 
 
458
        version_ids = set(version_ids)
 
 
459
        for r in list(version_ids):
 
 
460
            if self._index.has_version(r):
 
 
461
                version_ids.remove(r)
 
 
463
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
 
465
    def _add_lines_with_ghosts(self, version_id, parents, lines):
 
 
466
        """See VersionedFile.add_lines_with_ghosts()."""
 
 
467
        self._check_add(version_id, lines)
 
 
468
        return self._add(version_id, lines[:], parents, self.delta)
 
 
470
    def _add_lines(self, version_id, parents, lines):
 
 
471
        """See VersionedFile.add_lines."""
 
 
472
        self._check_add(version_id, lines)
 
 
473
        self._check_versions_present(parents)
 
 
474
        return self._add(version_id, lines[:], parents, self.delta)
 
 
476
    def _check_add(self, version_id, lines):
 
 
477
        """check that version_id and lines are safe to add."""
 
 
478
        assert self.writable, "knit is not opened for write"
 
 
479
        ### FIXME escape. RBC 20060228
 
 
480
        if contains_whitespace(version_id):
 
 
481
            raise InvalidRevisionId(version_id)
 
 
482
        if self.has_version(version_id):
 
 
483
            raise RevisionAlreadyPresent(version_id, self.filename)
 
 
485
        if False or __debug__:
 
 
487
                assert '\n' not in l[:-1]
 
 
489
    def _add(self, version_id, lines, parents, delta):
 
 
490
        """Add a set of lines on top of version specified by parents.
 
 
492
        If delta is true, compress the text as a line-delta against
 
 
495
        Any versions not present will be converted into ghosts.
 
 
497
        ghostless_parents = []
 
 
499
        for parent in parents:
 
 
500
            if not self.has_version(parent):
 
 
501
                ghosts.append(parent)
 
 
503
                ghostless_parents.append(parent)
 
 
505
        if delta and not len(ghostless_parents):
 
 
508
        digest = sha_strings(lines)
 
 
511
            if lines[-1][-1] != '\n':
 
 
512
                options.append('no-eol')
 
 
513
                lines[-1] = lines[-1] + '\n'
 
 
515
        lines = self.factory.make(lines, version_id) #len(self._index))
 
 
516
        if self.factory.annotated and len(ghostless_parents) > 0:
 
 
517
            # Merge annotations from parent texts if so is needed.
 
 
518
            self._merge_annotations(lines, ghostless_parents)
 
 
520
        if len(ghostless_parents) and delta:
 
 
521
            # To speed the extract of texts the delta chain is limited
 
 
522
            # to a fixed number of deltas.  This should minimize both
 
 
523
            # I/O and the time spend applying deltas.
 
 
525
            delta_parents = ghostless_parents
 
 
527
                parent = delta_parents[0]
 
 
528
                method = self._index.get_method(parent)
 
 
529
                if method == 'fulltext':
 
 
531
                delta_parents = self._index.get_parents(parent)
 
 
533
            if method == 'line-delta':
 
 
537
            options.append('line-delta')
 
 
538
            content = self._get_content(ghostless_parents[0])
 
 
539
            delta_hunks = content.line_delta(lines)
 
 
540
            store_lines = self.factory.lower_line_delta(delta_hunks)
 
 
542
            options.append('fulltext')
 
 
543
            store_lines = self.factory.lower_fulltext(lines)
 
 
545
        where, size = self._data.add_record(version_id, digest, store_lines)
 
 
546
        self._index.add_version(version_id, options, where, size, parents)
 
 
548
    def check(self, progress_bar=None):
 
 
549
        """See VersionedFile.check()."""
 
 
551
    def _clone_text(self, new_version_id, old_version_id, parents):
 
 
552
        """See VersionedFile.clone_text()."""
 
 
553
        # FIXME RBC 20060228 make fast by only inserting an index with null delta.
 
 
554
        self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
 
 
556
    def get_lines(self, version_id):
 
 
557
        """See VersionedFile.get_lines()."""
 
 
558
        return self._get_content(version_id).text()
 
 
560
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
 
 
561
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
 
 
562
        if version_ids is None:
 
 
563
            version_ids = self.versions()
 
 
564
        # we dont care about inclusions, the caller cares.
 
 
565
        # but we need to setup a list of records to visit.
 
 
566
        # we need version_id, position, length
 
 
567
        version_id_records = []
 
 
568
        requested_versions = list(version_ids)
 
 
569
        # filter for available versions
 
 
570
        for version_id in requested_versions:
 
 
571
            if not self.has_version(version_id):
 
 
572
                raise RevisionNotPresent(version_id, self.filename)
 
 
573
        # get a in-component-order queue:
 
 
575
        for version_id in self.versions():
 
 
576
            if version_id in requested_versions:
 
 
577
                version_ids.append(version_id)
 
 
578
                data_pos, length = self._index.get_position(version_id)
 
 
579
                version_id_records.append((version_id, data_pos, length))
 
 
581
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
 
583
        total = len(version_id_records)
 
 
585
            pb.update('Walking content.', count, total)
 
 
586
            for version_id, data, sha_value in \
 
 
587
                self._data.read_records_iter(version_id_records):
 
 
588
                pb.update('Walking content.', count, total)
 
 
589
                method = self._index.get_method(version_id)
 
 
590
                version_idx = self._index.lookup(version_id)
 
 
591
                assert method in ('fulltext', 'line-delta')
 
 
592
                if method == 'fulltext':
 
 
593
                    content = self.factory.parse_fulltext(data, version_idx)
 
 
594
                    for line in content.text():
 
 
597
                    delta = self.factory.parse_line_delta(data, version_idx)
 
 
598
                    for start, end, count, lines in delta:
 
 
599
                        for origin, line in lines:
 
 
602
            pb.update('Walking content.', total, total)
 
 
605
            pb.update('Walking content.', total, total)
 
 
609
    def num_versions(self):
 
 
610
        """See VersionedFile.num_versions()."""
 
 
611
        return self._index.num_versions()
 
 
613
    __len__ = num_versions
 
 
615
    def annotate_iter(self, version_id):
 
 
616
        """See VersionedFile.annotate_iter."""
 
 
617
        content = self._get_content(version_id)
 
 
618
        for origin, text in content.annotate_iter():
 
 
621
    def get_parents(self, version_id):
 
 
622
        """See VersionedFile.get_parents."""
 
 
623
        self._check_versions_present([version_id])
 
 
624
        return list(self._index.get_parents(version_id))
 
 
626
    def get_parents_with_ghosts(self, version_id):
 
 
627
        """See VersionedFile.get_parents."""
 
 
628
        self._check_versions_present([version_id])
 
 
629
        return list(self._index.get_parents_with_ghosts(version_id))
 
 
631
    def get_ancestry(self, versions):
 
 
632
        """See VersionedFile.get_ancestry."""
 
 
633
        if isinstance(versions, basestring):
 
 
634
            versions = [versions]
 
 
637
        self._check_versions_present(versions)
 
 
638
        return self._index.get_ancestry(versions)
 
 
640
    def get_ancestry_with_ghosts(self, versions):
 
 
641
        """See VersionedFile.get_ancestry_with_ghosts."""
 
 
642
        if isinstance(versions, basestring):
 
 
643
            versions = [versions]
 
 
646
        self._check_versions_present(versions)
 
 
647
        return self._index.get_ancestry_with_ghosts(versions)
 
 
649
    #@deprecated_method(zero_eight)
 
 
650
    def walk(self, version_ids):
 
 
651
        """See VersionedFile.walk."""
 
 
652
        # We take the short path here, and extract all relevant texts
 
 
653
        # and put them in a weave and let that do all the work.  Far
 
 
654
        # from optimal, but is much simpler.
 
 
655
        # FIXME RB 20060228 this really is inefficient!
 
 
656
        from bzrlib.weave import Weave
 
 
658
        w = Weave(self.filename)
 
 
659
        ancestry = self.get_ancestry(version_ids)
 
 
660
        sorted_graph = topo_sort(self._index.get_graph())
 
 
661
        version_list = [vid for vid in sorted_graph if vid in ancestry]
 
 
663
        for version_id in version_list:
 
 
664
            lines = self.get_lines(version_id)
 
 
665
            w.add_lines(version_id, self.get_parents(version_id), lines)
 
 
667
        for lineno, insert_id, dset, line in w.walk(version_ids):
 
 
668
            yield lineno, insert_id, dset, line
 
 
671
class _KnitComponentFile(object):
 
 
672
    """One of the files used to implement a knit database"""
 
 
674
    def __init__(self, transport, filename, mode):
 
 
675
        self._transport = transport
 
 
676
        self._filename = filename
 
 
679
    def write_header(self):
 
 
680
        old_len = self._transport.append(self._filename, StringIO(self.HEADER))
 
 
682
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
 
 
684
    def check_header(self, fp):
 
 
685
        line = fp.read(len(self.HEADER))
 
 
686
        if line != self.HEADER:
 
 
687
            raise KnitHeaderError(badline=line)
 
 
690
        """Commit is a nop."""
 
 
693
        return '%s(%s)' % (self.__class__.__name__, self._filename)
 
 
696
class _KnitIndex(_KnitComponentFile):
 
 
697
    """Manages knit index file.
 
 
699
    The index is already kept in memory and read on startup, to enable
 
 
700
    fast lookups of revision information.  The cursor of the index
 
 
701
    file is always pointing to the end, making it easy to append
 
 
704
    _cache is a cache for fast mapping from version id to a Index
 
 
707
    _history is a cache for fast mapping from indexes to version ids.
 
 
709
    The index data format is dictionary compressed when it comes to
 
 
710
    parent references; a index entry may only have parents that with a
 
 
711
    lover index number.  As a result, the index is topological sorted.
 
 
713
    Duplicate entries may be written to the index for a single version id
 
 
714
    if this is done then the latter one completely replaces the former:
 
 
715
    this allows updates to correct version and parent information. 
 
 
716
    Note that the two entries may share the delta, and that successive
 
 
717
    annotations and references MUST point to the first entry.
 
 
720
    HEADER = "# bzr knit index 7\n"
 
 
722
    def _cache_version(self, version_id, options, pos, size, parents):
 
 
723
        val = (version_id, options, pos, size, parents)
 
 
724
        self._cache[version_id] = val
 
 
725
        if not version_id in self._history:
 
 
726
            self._history.append(version_id)
 
 
728
    def _iter_index(self, fp):
 
 
734
        #for l in lines.splitlines(False):
 
 
737
    def __init__(self, transport, filename, mode, create=False):
 
 
738
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
 
740
        # position in _history is the 'official' index for a revision
 
 
741
        # but the values may have come from a newer entry.
 
 
742
        # so - wc -l of a knit index is != the number of uniqe names
 
 
745
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
 
750
                pb.update('read knit index', count, total)
 
 
751
                fp = self._transport.get(self._filename)
 
 
752
                self.check_header(fp)
 
 
753
                for rec in self._iter_index(fp):
 
 
756
                    pb.update('read knit index', count, total)
 
 
757
                    parents = self._parse_parents(rec[4:])
 
 
758
                    self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
 
 
760
            except NoSuchFile, e:
 
 
761
                if mode != 'w' or not create:
 
 
765
            pb.update('read knit index', total, total)
 
 
768
    def _parse_parents(self, compressed_parents):
 
 
769
        """convert a list of string parent values into version ids.
 
 
771
        ints are looked up in the index.
 
 
772
        .FOO values are ghosts and converted in to FOO.
 
 
775
        for value in compressed_parents:
 
 
776
            if value.startswith('.'):
 
 
777
                result.append(value[1:])
 
 
779
                assert isinstance(value, str)
 
 
781
                    result.append(self._history[int(value)])
 
 
783
                    import pdb;pdb.set_trace()
 
 
788
        for version_id, index in self._cache.iteritems():
 
 
789
            graph.append((version_id, index[4]))
 
 
792
    def get_ancestry(self, versions):
 
 
793
        """See VersionedFile.get_ancestry."""
 
 
794
        # get a graph of all the mentioned versions:
 
 
796
        pending = set(versions)
 
 
798
            version = pending.pop()
 
 
799
            parents = self._cache[version][4]
 
 
802
            parents = [parent for parent in parents if parent in self._cache]
 
 
803
            for parent in parents:
 
 
804
                # if not completed and not a ghost
 
 
805
                if parent not in graph:
 
 
807
            graph[version] = parents
 
 
808
        return topo_sort(graph.items())
 
 
810
    def get_ancestry_with_ghosts(self, versions):
 
 
811
        """See VersionedFile.get_ancestry_with_ghosts."""
 
 
812
        # get a graph of all the mentioned versions:
 
 
814
        pending = set(versions)
 
 
816
            version = pending.pop()
 
 
818
                parents = self._cache[version][4]
 
 
825
                for parent in parents:
 
 
826
                    if parent not in graph:
 
 
828
                graph[version] = parents
 
 
829
        return topo_sort(graph.items())
 
 
831
    def num_versions(self):
 
 
832
        return len(self._history)
 
 
834
    __len__ = num_versions
 
 
836
    def get_versions(self):
 
 
839
    def idx_to_name(self, idx):
 
 
840
        return self._history[idx]
 
 
842
    def lookup(self, version_id):
 
 
843
        assert version_id in self._cache
 
 
844
        return self._history.index(version_id)
 
 
846
    def _version_list_to_index(self, versions):
 
 
848
        for version in versions:
 
 
849
            if version in self._cache:
 
 
850
                result_list.append(str(self._history.index(version)))
 
 
852
                result_list.append('.' + version.encode('utf-8'))
 
 
853
        return ' '.join(result_list)
 
 
855
    def add_version(self, version_id, options, pos, size, parents):
 
 
856
        """Add a version record to the index."""
 
 
857
        self._cache_version(version_id, options, pos, size, parents)
 
 
859
        content = "%s %s %s %s %s\n" % (version_id.encode('utf-8'),
 
 
863
                                        self._version_list_to_index(parents))
 
 
864
        assert isinstance(content, str), 'content must be utf-8 encoded'
 
 
865
        self._transport.append(self._filename, StringIO(content))
 
 
867
    def has_version(self, version_id):
 
 
868
        """True if the version is in the index."""
 
 
869
        return self._cache.has_key(version_id)
 
 
871
    def get_position(self, version_id):
 
 
872
        """Return data position and size of specified version."""
 
 
873
        return (self._cache[version_id][2], \
 
 
874
                self._cache[version_id][3])
 
 
876
    def get_method(self, version_id):
 
 
877
        """Return compression method of specified version."""
 
 
878
        options = self._cache[version_id][1]
 
 
879
        if 'fulltext' in options:
 
 
882
            assert 'line-delta' in options
 
 
885
    def get_options(self, version_id):
 
 
886
        return self._cache[version_id][1]
 
 
888
    def get_parents(self, version_id):
 
 
889
        """Return parents of specified version ignoring ghosts."""
 
 
890
        return [parent for parent in self._cache[version_id][4] 
 
 
891
                if parent in self._cache]
 
 
893
    def get_parents_with_ghosts(self, version_id):
 
 
894
        """Return parents of specified version wth ghosts."""
 
 
895
        return self._cache[version_id][4] 
 
 
897
    def check_versions_present(self, version_ids):
 
 
898
        """Check that all specified versions are present."""
 
 
899
        version_ids = set(version_ids)
 
 
900
        for version_id in list(version_ids):
 
 
901
            if version_id in self._cache:
 
 
902
                version_ids.remove(version_id)
 
 
904
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
 
907
class _KnitData(_KnitComponentFile):
 
 
908
    """Contents of the knit data file"""
 
 
910
    HEADER = "# bzr knit data 7\n"
 
 
912
    def __init__(self, transport, filename, mode, create=False):
 
 
913
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
 
915
        self._checked = False
 
 
917
            self._transport.put(self._filename, StringIO(''))
 
 
920
    def clear_cache(self):
 
 
921
        """Clear the record cache."""
 
 
924
    def _open_file(self):
 
 
925
        if self._file is None:
 
 
927
                self._file = self._transport.get(self._filename)
 
 
932
    def _record_to_data(self, version_id, digest, lines):
 
 
933
        """Convert version_id, digest, lines into a raw data block.
 
 
935
        :return: (len, a StringIO instance with the raw data ready to read.)
 
 
938
        data_file = GzipFile(None, mode='wb', fileobj=sio)
 
 
939
        print >>data_file, "version %s %d %s" % (version_id.encode('utf-8'), len(lines), digest)
 
 
940
        data_file.writelines(lines)
 
 
941
        print >>data_file, "end %s\n" % version_id.encode('utf-8')
 
 
947
    def add_raw_record(self, raw_data):
 
 
948
        """Append a prepared record to the data file."""
 
 
949
        assert isinstance(raw_data, str), 'data must be plain bytes'
 
 
950
        start_pos = self._transport.append(self._filename, StringIO(raw_data))
 
 
951
        return start_pos, len(raw_data)
 
 
953
    def add_record(self, version_id, digest, lines):
 
 
954
        """Write new text record to disk.  Returns the position in the
 
 
955
        file where it was written."""
 
 
956
        size, sio = self._record_to_data(version_id, digest, lines)
 
 
958
        self._records[version_id] = (digest, lines)
 
 
960
        start_pos = self._transport.append(self._filename, sio)
 
 
961
        return start_pos, size
 
 
963
    def _parse_record_header(self, version_id, raw_data):
 
 
964
        """Parse a record header for consistency.
 
 
966
        :return: the header and the decompressor stream.
 
 
967
                 as (stream, header_record)
 
 
969
        df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
 
 
970
        rec = df.readline().split()
 
 
972
            raise KnitCorrupt(self._filename, 'unexpected number of elements in record header')
 
 
973
        if rec[1].decode('utf-8')!= version_id:
 
 
974
            raise KnitCorrupt(self._filename, 
 
 
975
                              'unexpected version, wanted %r, got %r' % (
 
 
979
    def _parse_record(self, version_id, data):
 
 
980
        df, rec = self._parse_record_header(version_id, data)
 
 
982
        record_contents = self._read_record_contents(df, lines)
 
 
984
        if l.decode('utf-8') != 'end %s\n' % version_id:
 
 
985
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
 
 
988
        return record_contents, rec[3]
 
 
990
    def _read_record_contents(self, df, record_lines):
 
 
991
        """Read and return n lines from datafile."""
 
 
993
        for i in range(record_lines):
 
 
994
            r.append(df.readline())
 
 
997
    def read_records_iter_raw(self, records):
 
 
998
        """Read text records from data file and yield raw data.
 
 
1000
        This unpacks enough of the text record to validate the id is
 
 
1001
        as expected but thats all.
 
 
1003
        It will actively recompress currently cached records on the
 
 
1004
        basis that that is cheaper than I/O activity.
 
 
1007
        for version_id, pos, size in records:
 
 
1008
            if version_id not in self._records:
 
 
1009
                needed_records.append((version_id, pos, size))
 
 
1011
        # setup an iterator of the external records:
 
 
1012
        # uses readv so nice and fast we hope.
 
 
1013
        if len(needed_records):
 
 
1014
            # grab the disk data needed.
 
 
1015
            raw_records = self._transport.readv(self._filename,
 
 
1016
                [(pos, size) for version_id, pos, size in needed_records])
 
 
1018
        for version_id, pos, size in records:
 
 
1019
            if version_id in self._records:
 
 
1020
                # compress a new version
 
 
1021
                size, sio = self._record_to_data(version_id,
 
 
1022
                                                 self._records[version_id][0],
 
 
1023
                                                 self._records[version_id][1])
 
 
1024
                yield version_id, sio.getvalue()
 
 
1026
                pos, data = raw_records.next()
 
 
1027
                # validate the header
 
 
1028
                df, rec = self._parse_record_header(version_id, data)
 
 
1030
                yield version_id, data
 
 
1033
    def read_records_iter(self, records):
 
 
1034
        """Read text records from data file and yield result.
 
 
1036
        Each passed record is a tuple of (version_id, pos, len) and
 
 
1037
        will be read in the given order.  Yields (version_id,
 
 
1042
        for version_id, pos, size in records:
 
 
1043
            if version_id not in self._records:
 
 
1044
                needed_records.append((version_id, pos, size))
 
 
1046
        if len(needed_records):
 
 
1047
            # We take it that the transport optimizes the fetching as good
 
 
1048
            # as possible (ie, reads continous ranges.)
 
 
1049
            response = self._transport.readv(self._filename,
 
 
1050
                [(pos, size) for version_id, pos, size in needed_records])
 
 
1052
            for (record_id, pos, size), (pos, data) in izip(iter(needed_records), response):
 
 
1053
                content, digest = self._parse_record(record_id, data)
 
 
1054
                self._records[record_id] = (digest, content)
 
 
1056
        for version_id, pos, size in records:
 
 
1057
            yield version_id, copy(self._records[version_id][1]), copy(self._records[version_id][0])
 
 
1059
    def read_records(self, records):
 
 
1060
        """Read records into a dictionary."""
 
 
1062
        for record_id, content, digest in self.read_records_iter(records):
 
 
1063
            components[record_id] = (content, digest)
 
 
1067
class InterKnit(InterVersionedFile):
 
 
1068
    """Optimised code paths for knit to knit operations."""
 
 
1070
    _matching_file_factory = KnitVersionedFile
 
 
1073
    def is_compatible(source, target):
 
 
1074
        """Be compatible with knits.  """
 
 
1076
            return (isinstance(source, KnitVersionedFile) and
 
 
1077
                    isinstance(target, KnitVersionedFile))
 
 
1078
        except AttributeError:
 
 
1081
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
 
1082
        """See InterVersionedFile.join."""
 
 
1083
        assert isinstance(self.source, KnitVersionedFile)
 
 
1084
        assert isinstance(self.target, KnitVersionedFile)
 
 
1086
        if version_ids is None:
 
 
1087
            version_ids = self.source.versions()
 
 
1089
            if not ignore_missing:
 
 
1090
                self.source._check_versions_present(version_ids)
 
 
1092
                version_ids = set(self.source.versions()).intersection(
 
 
1098
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
 
1100
            version_ids = list(version_ids)
 
 
1101
            if None in version_ids:
 
 
1102
                version_ids.remove(None)
 
 
1104
            self.source_ancestry = set(self.source.get_ancestry(version_ids))
 
 
1105
            this_versions = set(self.target._index.get_versions())
 
 
1106
            needed_versions = self.source_ancestry - this_versions
 
 
1107
            cross_check_versions = self.source_ancestry.intersection(this_versions)
 
 
1108
            mismatched_versions = set()
 
 
1109
            for version in cross_check_versions:
 
 
1110
                # scan to include needed parents.
 
 
1111
                n1 = set(self.target.get_parents_with_ghosts(version))
 
 
1112
                n2 = set(self.source.get_parents_with_ghosts(version))
 
 
1114
                    # FIXME TEST this check for cycles being introduced works
 
 
1115
                    # the logic is we have a cycle if in our graph we are an
 
 
1116
                    # ancestor of any of the n2 revisions.
 
 
1122
                            parent_ancestors = self.source.get_ancestry(parent)
 
 
1123
                            if version in parent_ancestors:
 
 
1124
                                raise errors.GraphCycleError([parent, version])
 
 
1125
                    # ensure this parent will be available later.
 
 
1126
                    new_parents = n2.difference(n1)
 
 
1127
                    needed_versions.update(new_parents.difference(this_versions))
 
 
1128
                    mismatched_versions.add(version)
 
 
1130
            if not needed_versions and not cross_check_versions:
 
 
1132
            full_list = topo_sort(self.source.get_graph())
 
 
1134
            version_list = [i for i in full_list if (not self.target.has_version(i)
 
 
1135
                            and i in needed_versions)]
 
 
1139
            copy_queue_records = []
 
 
1141
            for version_id in version_list:
 
 
1142
                options = self.source._index.get_options(version_id)
 
 
1143
                parents = self.source._index.get_parents_with_ghosts(version_id)
 
 
1144
                # check that its will be a consistent copy:
 
 
1145
                for parent in parents:
 
 
1146
                    # if source has the parent, we must :
 
 
1147
                    # * already have it or
 
 
1148
                    # * have it scheduled already
 
 
1149
                    # otherwise we dont care
 
 
1150
                    assert (self.target.has_version(parent) or
 
 
1151
                            parent in copy_set or
 
 
1152
                            not self.source.has_version(parent))
 
 
1153
                data_pos, data_size = self.source._index.get_position(version_id)
 
 
1154
                copy_queue_records.append((version_id, data_pos, data_size))
 
 
1155
                copy_queue.append((version_id, options, parents))
 
 
1156
                copy_set.add(version_id)
 
 
1158
            # data suck the join:
 
 
1160
            total = len(version_list)
 
 
1161
            # we want the raw gzip for bulk copying, but the record validated
 
 
1162
            # just enough to be sure its the right one.
 
 
1163
            # TODO: consider writev or write combining to reduce 
 
 
1164
            # death of a thousand cuts feeling.
 
 
1165
            for (version_id, raw_data), \
 
 
1166
                (version_id2, options, parents) in \
 
 
1167
                izip(self.source._data.read_records_iter_raw(copy_queue_records),
 
 
1169
                assert version_id == version_id2, 'logic error, inconsistent results'
 
 
1171
                pb.update("Joining knit", count, total)
 
 
1172
                pos, size = self.target._data.add_raw_record(raw_data)
 
 
1173
                self.target._index.add_version(version_id, options, pos, size, parents)
 
 
1175
            for version in mismatched_versions:
 
 
1176
                # FIXME RBC 20060309 is this needed?
 
 
1177
                n1 = set(self.target.get_parents_with_ghosts(version))
 
 
1178
                n2 = set(self.source.get_parents_with_ghosts(version))
 
 
1179
                # write a combined record to our history preserving the current 
 
 
1180
                # parents as first in the list
 
 
1181
                new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
 
 
1182
                self.target.fix_parents(version, new_parents)
 
 
1189
InterVersionedFile.register_optimiser(InterKnit)