~bzr-pqm/bzr/bzr.dev

1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
# Written by Martin Pool.
3
# Modified by Johan Rydberg <jrydberg@gnu.org>
4
# Modified by Robert Collins <robert.collins@canonical.com>
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20
"""Knit versionedfile implementation.
21
22
A knit is a versioned file implementation that supports efficient append only
23
updates.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
24
25
Knit file layout:
26
lifeless: the data file is made up of "delta records".  each delta record has a delta header 
27
that contains; (1) a version id, (2) the size of the delta (in lines), and (3)  the digest of 
28
the -expanded data- (ie, the delta applied to the parent).  the delta also ends with a 
29
end-marker; simply "end VERSION"
30
31
delta can be line or full contents.a
32
... the 8's there are the index number of the annotation.
33
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
34
59,59,3
35
8
36
8         if ie.executable:
37
8             e.set('executable', 'yes')
38
130,130,2
39
8         if elt.get('executable') == 'yes':
40
8             ie.executable = True
41
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 
42
43
44
whats in an index:
45
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
46
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
47
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
48
09:33 < lifeless> right
49
09:33 < jrydberg> lifeless: the position and size is the range in the data file
50
51
52
so the index sequence is the dictionary compressed sequence number used
53
in the deltas to provide line annotation
54
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
55
"""
56
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
57
# TODOS:
58
# 10:16 < lifeless> make partial index writes safe
59
# 10:16 < lifeless> implement 'knit.check()' like weave.check()
60
# 10:17 < lifeless> record known ghosts so we can detect when they are filled in rather than the current 'reweave 
61
#                    always' approach.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
62
# move sha1 out of the content so that join is faster at verifying parents
63
# record content length ?
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
64
                  
65
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
66
from cStringIO import StringIO
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
67
import difflib
68
from difflib import SequenceMatcher
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
69
from gzip import GzipFile
70
import os
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
71
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
72
import bzrlib.errors as errors
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
73
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
74
        InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
75
        RevisionNotPresent, RevisionAlreadyPresent
76
from bzrlib.trace import mutter
77
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
78
     sha_strings
1563.2.13 by Robert Collins
InterVersionedFile implemented.
79
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
80
from bzrlib.tsort import topo_sort
81
82
83
# TODO: Split out code specific to this format into an associated object.
84
85
# TODO: Can we put in some kind of value to check that the index and data
86
# files belong together?
87
88
# TODO: accomodate binaries, perhaps by storing a byte count
89
90
# TODO: function to check whole file
91
92
# TODO: atomically append data, then measure backwards from the cursor
93
# position after writing to work out where it was located.  we may need to
94
# bypass python file buffering.
95
96
DATA_SUFFIX = '.knit'
97
INDEX_SUFFIX = '.kndx'
98
99
100
class KnitContent(object):
101
    """Content of a knit version to which deltas can be applied."""
102
103
    def __init__(self, lines):
104
        self._lines = lines
105
106
    def annotate_iter(self):
107
        """Yield tuples of (origin, text) for each content line."""
108
        for origin, text in self._lines:
109
            yield origin, text
110
111
    def annotate(self):
112
        """Return a list of (origin, text) tuples."""
113
        return list(self.annotate_iter())
114
115
    def apply_delta(self, delta):
116
        """Apply delta to this content."""
117
        offset = 0
118
        for start, end, count, lines in delta:
119
            self._lines[offset+start:offset+end] = lines
120
            offset = offset + (start - end) + count
121
122
    def line_delta_iter(self, new_lines):
123
        """Generate line-based delta from new_lines to this content."""
124
        new_texts = [text for origin, text in new_lines._lines]
125
        old_texts = [text for origin, text in self._lines]
126
        s = difflib.SequenceMatcher(None, old_texts, new_texts)
127
        for op in s.get_opcodes():
128
            if op[0] == 'equal':
129
                continue
130
            yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
131
132
    def line_delta(self, new_lines):
133
        return list(self.line_delta_iter(new_lines))
134
135
    def text(self):
136
        return [text for origin, text in self._lines]
137
138
139
class _KnitFactory(object):
140
    """Base factory for creating content objects."""
141
142
    def make(self, lines, version):
143
        num_lines = len(lines)
144
        return KnitContent(zip([version] * num_lines, lines))
145
146
147
class KnitAnnotateFactory(_KnitFactory):
148
    """Factory for creating annotated Content objects."""
149
150
    annotated = True
151
152
    def parse_fulltext(self, content, version):
153
        lines = []
154
        for line in content:
155
            origin, text = line.split(' ', 1)
156
            lines.append((int(origin), text))
157
        return KnitContent(lines)
158
159
    def parse_line_delta_iter(self, lines):
160
        while lines:
161
            header = lines.pop(0)
162
            start, end, c = [int(n) for n in header.split(',')]
163
            contents = []
164
            for i in range(c):
165
                origin, text = lines.pop(0).split(' ', 1)
166
                contents.append((int(origin), text))
167
            yield start, end, c, contents
168
169
    def parse_line_delta(self, lines, version):
170
        return list(self.parse_line_delta_iter(lines))
171
172
    def lower_fulltext(self, content):
173
        return ['%d %s' % (o, t) for o, t in content._lines]
174
175
    def lower_line_delta(self, delta):
176
        out = []
177
        for start, end, c, lines in delta:
178
            out.append('%d,%d,%d\n' % (start, end, c))
179
            for origin, text in lines:
180
                out.append('%d %s' % (origin, text))
181
        return out
182
183
184
class KnitPlainFactory(_KnitFactory):
185
    """Factory for creating plain Content objects."""
186
187
    annotated = False
188
189
    def parse_fulltext(self, content, version):
190
        return self.make(content, version)
191
192
    def parse_line_delta_iter(self, lines, version):
193
        while lines:
194
            header = lines.pop(0)
195
            start, end, c = [int(n) for n in header.split(',')]
196
            yield start, end, c, zip([version] * c, lines[:c])
197
            del lines[:c]
198
199
    def parse_line_delta(self, lines, version):
200
        return list(self.parse_line_delta_iter(lines, version))
201
    
202
    def lower_fulltext(self, content):
203
        return content.text()
204
205
    def lower_line_delta(self, delta):
206
        out = []
207
        for start, end, c, lines in delta:
208
            out.append('%d,%d,%d\n' % (start, end, c))
209
            out.extend([text for origin, text in lines])
210
        return out
211
212
213
def make_empty_knit(transport, relpath):
214
    """Construct a empty knit at the specified location."""
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
215
    k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
216
    k._data._open_file()
217
218
219
class KnitVersionedFile(VersionedFile):
220
    """Weave-like structure with faster random access.
221
222
    A knit stores a number of texts and a summary of the relationships
223
    between them.  Texts are identified by a string version-id.  Texts
224
    are normally stored and retrieved as a series of lines, but can
225
    also be passed as single strings.
226
227
    Lines are stored with the trailing newline (if any) included, to
228
    avoid special cases for files with no final newline.  Lines are
229
    composed of 8-bit characters, not unicode.  The combination of
230
    these approaches should mean any 'binary' file can be safely
231
    stored and retrieved.
232
    """
233
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
234
    def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
235
                 basis_knit=None, delta=True):
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
236
        """Construct a knit at location specified by relpath."""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
237
        if access_mode is None:
238
            access_mode = 'w'
239
        assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
240
        assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
241
            type(basis_knit)
242
243
        self.transport = transport
244
        self.filename = relpath
245
        self.basis_knit = basis_knit
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
246
        self.factory = factory or KnitAnnotateFactory()
247
        self.writable = (access_mode == 'w')
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
248
        self.delta = delta
249
250
        self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
251
            access_mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
252
        self._data = _KnitData(transport, relpath + DATA_SUFFIX,
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
253
            access_mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
254
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
255
    def copy_to(self, name, transport):
256
        """See VersionedFile.copy_to()."""
257
        # copy the current index to a temp index to avoid racing with local
258
        # writes
259
        transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
260
        # copy the data file
261
        transport.put(name + DATA_SUFFIX, self._data._open_file())
262
        # rename the copied index into place
263
        transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
264
1563.2.13 by Robert Collins
InterVersionedFile implemented.
265
    def create_empty(self, name, transport, mode=None):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
266
        return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta)
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
267
    
268
    @staticmethod
269
    def get_suffixes():
270
        """See VersionedFile.get_suffixes()."""
271
        return [DATA_SUFFIX, INDEX_SUFFIX]
1563.2.13 by Robert Collins
InterVersionedFile implemented.
272
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
273
    def versions(self):
274
        """See VersionedFile.versions."""
275
        return self._index.get_versions()
276
277
    def has_version(self, version_id):
278
        """See VersionedFile.has_version."""
279
        return self._index.has_version(version_id)
280
281
    __contains__ = has_version
282
283
    def _merge_annotations(self, content, parents):
284
        """Merge annotations for content.  This is done by comparing
285
        the annotations based on changed to the text."""
286
        for parent_id in parents:
287
            merge_content = self._get_content(parent_id)
288
            seq = SequenceMatcher(None, merge_content.text(), content.text())
289
            for i, j, n in seq.get_matching_blocks():
290
                if n == 0:
291
                    continue
292
                content._lines[j:j+n] = merge_content._lines[i:i+n]
293
294
    def _get_components(self, version_id):
295
        """Return a list of (version_id, method, data) tuples that
296
        makes up version specified by version_id of the knit.
297
298
        The components should be applied in the order of the returned
299
        list.
300
301
        The basis knit will be used to the largest extent possible
302
        since it is assumed that accesses to it is faster.
303
        """
304
        # needed_revisions holds a list of (method, version_id) of
305
        # versions that is needed to be fetched to construct the final
306
        # version of the file.
307
        #
308
        # basis_revisions is a list of versions that needs to be
309
        # fetched but exists in the basis knit.
310
311
        basis = self.basis_knit
312
        needed_versions = []
313
        basis_versions = []
314
        cursor = version_id
315
316
        while 1:
317
            picked_knit = self
318
            if basis and basis._index.has_version(cursor):
319
                picked_knit = basis
320
                basis_versions.append(cursor)
321
            method = picked_knit._index.get_method(cursor)
322
            needed_versions.append((method, cursor))
323
            if method == 'fulltext':
324
                break
325
            cursor = picked_knit.get_parents(cursor)[0]
326
327
        components = {}
328
        if basis_versions:
329
            records = []
330
            for comp_id in basis_versions:
331
                data_pos, data_size = basis._index.get_data_position(comp_id)
332
                records.append((piece_id, data_pos, data_size))
333
            components.update(basis._data.read_records(records))
334
335
        records = []
336
        for comp_id in [vid for method, vid in needed_versions
337
                        if vid not in basis_versions]:
338
            data_pos, data_size = self._index.get_position(comp_id)
339
            records.append((comp_id, data_pos, data_size))
340
        components.update(self._data.read_records(records))
341
342
        # get_data_records returns a mapping with the version id as
343
        # index and the value as data.  The order the components need
344
        # to be applied is held by needed_versions (reversed).
345
        out = []
346
        for method, comp_id in reversed(needed_versions):
347
            out.append((comp_id, method, components[comp_id]))
348
349
        return out
350
351
    def _get_content(self, version_id):
352
        """Returns a content object that makes up the specified
353
        version."""
354
        if not self.has_version(version_id):
355
            raise RevisionNotPresent(version_id, self.filename)
356
357
        if self.basis_knit and version_id in self.basis_knit:
358
            return self.basis_knit._get_content(version_id)
359
360
        content = None
361
        components = self._get_components(version_id)
362
        for component_id, method, (data, digest) in components:
363
            version_idx = self._index.lookup(component_id)
364
            if method == 'fulltext':
365
                assert content is None
366
                content = self.factory.parse_fulltext(data, version_idx)
367
            elif method == 'line-delta':
368
                delta = self.factory.parse_line_delta(data, version_idx)
369
                content.apply_delta(delta)
370
371
        if 'no-eol' in self._index.get_options(version_id):
372
            line = content._lines[-1][1].rstrip('\n')
373
            content._lines[-1] = (content._lines[-1][0], line)
374
375
        if sha_strings(content.text()) != digest:
376
            raise KnitCorrupt(self.filename, 'sha-1 does not match')
377
378
        return content
379
380
    def _check_versions_present(self, version_ids):
381
        """Check that all specified versions are present."""
382
        version_ids = set(version_ids)
383
        for r in list(version_ids):
384
            if self._index.has_version(r):
385
                version_ids.remove(r)
386
        if version_ids:
387
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
388
389
    def add_lines(self, version_id, parents, lines):
390
        """See VersionedFile.add_lines."""
391
        assert self.writable, "knit is not opened for write"
392
        ### FIXME escape. RBC 20060228
393
        if contains_whitespace(version_id):
394
            raise InvalidRevisionId(version_id)
395
        if self.has_version(version_id):
396
            raise RevisionAlreadyPresent(version_id, self.filename)
397
398
        if True or __debug__:
399
            for l in lines:
400
                assert '\n' not in l[:-1]
401
402
        self._check_versions_present(parents)
403
        return self._add(version_id, lines[:], parents, self.delta)
404
405
    def _add(self, version_id, lines, parents, delta):
406
        """Add a set of lines on top of version specified by parents.
407
408
        If delta is true, compress the text as a line-delta against
409
        the first parent.
410
        """
411
        if delta and not parents:
412
            delta = False
413
414
        digest = sha_strings(lines)
415
        options = []
416
        if lines:
417
            if lines[-1][-1] != '\n':
418
                options.append('no-eol')
419
                lines[-1] = lines[-1] + '\n'
420
421
        lines = self.factory.make(lines, len(self._index))
422
        if self.factory.annotated and len(parents) > 0:
423
            # Merge annotations from parent texts if so is needed.
424
            self._merge_annotations(lines, parents)
425
426
        if parents and delta:
427
            # To speed the extract of texts the delta chain is limited
428
            # to a fixed number of deltas.  This should minimize both
429
            # I/O and the time spend applying deltas.
430
            count = 0
431
            delta_parents = parents
432
            while count < 25:
433
                parent = delta_parents[0]
434
                method = self._index.get_method(parent)
435
                if method == 'fulltext':
436
                    break
437
                delta_parents = self._index.get_parents(parent)
438
                count = count + 1
439
            if method == 'line-delta':
440
                delta = False
441
442
        if delta:
443
            options.append('line-delta')
444
            content = self._get_content(parents[0])
445
            delta_hunks = content.line_delta(lines)
446
            store_lines = self.factory.lower_line_delta(delta_hunks)
447
        else:
448
            options.append('fulltext')
449
            store_lines = self.factory.lower_fulltext(lines)
450
451
        where, size = self._data.add_record(version_id, digest, store_lines)
452
        self._index.add_version(version_id, options, where, size, parents)
453
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
454
    def clone_text(self, new_version_id, old_version_id, parents):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
455
        """See VersionedFile.clone_text()."""
456
        # FIXME RBC 20060228 make fast by only inserting an index with null delta.
457
        self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
458
459
    def get_lines(self, version_id):
460
        """See VersionedFile.get_lines()."""
461
        return self._get_content(version_id).text()
462
463
    def annotate_iter(self, version_id):
464
        """See VersionedFile.annotate_iter."""
465
        content = self._get_content(version_id)
466
        for origin, text in content.annotate_iter():
467
            yield self._index.idx_to_name(origin), text
468
469
    def get_parents(self, version_id):
470
        """See VersionedFile.get_parents."""
471
        self._check_versions_present([version_id])
472
        return list(self._index.get_parents(version_id))
473
474
    def get_ancestry(self, versions):
475
        """See VersionedFile.get_ancestry."""
476
        if isinstance(versions, basestring):
477
            versions = [versions]
478
        if not versions:
479
            return []
480
        self._check_versions_present(versions)
481
        return self._index.get_ancestry(versions)
482
483
    def _reannotate_line_delta(self, other, lines, new_version_id,
484
                               new_version_idx):
485
        """Re-annotate line-delta and return new delta."""
486
        new_delta = []
487
        for start, end, count, contents \
488
                in self.factory.parse_line_delta_iter(lines):
489
            new_lines = []
490
            for origin, line in contents:
491
                old_version_id = other._index.idx_to_name(origin)
492
                if old_version_id == new_version_id:
493
                    idx = new_version_idx
494
                else:
495
                    idx = self._index.lookup(old_version_id)
496
                new_lines.append((idx, line))
497
            new_delta.append((start, end, count, new_lines))
498
499
        return self.factory.lower_line_delta(new_delta)
500
501
    def _reannotate_fulltext(self, other, lines, new_version_id,
502
                             new_version_idx):
503
        """Re-annotate fulltext and return new version."""
504
        content = self.factory.parse_fulltext(lines, new_version_idx)
505
        new_lines = []
506
        for origin, line in content.annotate_iter():
507
            old_version_id = other._index.idx_to_name(origin)
508
            if old_version_id == new_version_id:
509
                idx = new_version_idx
510
            else:
511
                idx = self._index.lookup(old_version_id)
512
            new_lines.append((idx, line))
513
514
        return self.factory.lower_fulltext(KnitContent(new_lines))
515
516
    def walk(self, version_ids):
517
        """See VersionedFile.walk."""
518
        # We take the short path here, and extract all relevant texts
519
        # and put them in a weave and let that do all the work.  Far
520
        # from optimal, but is much simpler.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
521
        # FIXME RB 20060228 this really is inefficient!
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
522
        from bzrlib.weave import Weave
523
524
        w = Weave(self.filename)
525
        ancestry = self.get_ancestry(version_ids)
526
        sorted_graph = topo_sort(self._index.get_graph())
527
        version_list = [vid for vid in sorted_graph if vid in ancestry]
528
        
529
        for version_id in version_list:
530
            lines = self.get_lines(version_id)
531
            w.add_lines(version_id, self.get_parents(version_id), lines)
532
533
        for lineno, insert_id, dset, line in w.walk(version_ids):
534
            yield lineno, insert_id, dset, line
535
536
537
class _KnitComponentFile(object):
538
    """One of the files used to implement a knit database"""
539
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
540
    def __init__(self, transport, filename, mode):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
541
        self._transport = transport
542
        self._filename = filename
543
        self._mode = mode
544
545
    def write_header(self):
1563.2.13 by Robert Collins
InterVersionedFile implemented.
546
        old_len = self._transport.append(self._filename, StringIO(self.HEADER))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
547
        if old_len != 0:
548
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
549
550
    def check_header(self, fp):
551
        line = fp.read(len(self.HEADER))
552
        if line != self.HEADER:
553
            raise KnitHeaderError(badline=line)
554
555
    def commit(self):
556
        """Commit is a nop."""
557
558
    def __repr__(self):
559
        return '%s(%s)' % (self.__class__.__name__, self._filename)
560
561
562
class _KnitIndex(_KnitComponentFile):
563
    """Manages knit index file.
564
565
    The index is already kept in memory and read on startup, to enable
566
    fast lookups of revision information.  The cursor of the index
567
    file is always pointing to the end, making it easy to append
568
    entries.
569
570
    _cache is a cache for fast mapping from version id to a Index
571
    object.
572
573
    _history is a cache for fast mapping from indexes to version ids.
574
575
    The index data format is dictionary compressed when it comes to
576
    parent references; a index entry may only have parents that with a
577
    lover index number.  As a result, the index is topological sorted.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
578
579
    Duplicate entries may be written to the index for a single version id
580
    if this is done then the latter one completely replaces the former:
581
    this allows updates to correct version and parent information. 
582
    Note that the two entries may share the delta, and that successive
583
    annotations and references MUST point to the first entry.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
584
    """
585
586
    HEADER = "# bzr knit index 7\n"
587
588
    def _cache_version(self, version_id, options, pos, size, parents):
589
        val = (version_id, options, pos, size, parents)
590
        self._cache[version_id] = val
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
591
        if not version_id in self._history:
592
            self._history.append(version_id)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
593
594
    def _iter_index(self, fp):
595
        lines = fp.read()
596
        for l in lines.splitlines(False):
597
            yield l.split()
598
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
599
    def __init__(self, transport, filename, mode):
600
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
601
        self._cache = {}
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
602
        # position in _history is the 'official' index for a revision
603
        # but the values may have come from a newer entry.
604
        # so - wc -l of a knit index is != the number of uniqe names
605
        # in the weave.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
606
        self._history = []
607
        try:
608
            fp = self._transport.get(self._filename)
609
            self.check_header(fp)
610
            for rec in self._iter_index(fp):
611
                self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
612
                    [self._history[int(i)] for i in rec[4:]])
613
        except NoSuchFile, e:
614
            if mode != 'w':
615
                raise e
616
            self.write_header()
617
618
    def get_graph(self):
619
        graph = []
620
        for version_id, index in self._cache.iteritems():
621
            graph.append((version_id, index[4]))
622
        return graph
623
624
    def get_ancestry(self, versions):
625
        """See VersionedFile.get_ancestry."""
626
        version_idxs = []
627
        for version_id in versions:
628
            version_idxs.append(self._history.index(version_id))
629
        i = set(versions)
630
        for v in xrange(max(version_idxs), 0, -1):
631
            if self._history[v] in i:
632
                # include all its parents
633
                i.update(self._cache[self._history[v]][4])
634
        return list(i)
635
636
    def num_versions(self):
637
        return len(self._history)
638
639
    __len__ = num_versions
640
641
    def get_versions(self):
642
        return self._history
643
644
    def idx_to_name(self, idx):
645
        return self._history[idx]
646
647
    def lookup(self, version_id):
648
        assert version_id in self._cache
649
        return self._history.index(version_id)
650
651
    def add_version(self, version_id, options, pos, size, parents):
652
        """Add a version record to the index."""
653
        self._cache_version(version_id, options, pos, size, parents)
654
655
        content = "%s %s %s %s %s\n" % (version_id,
656
                                        ','.join(options),
657
                                        pos,
658
                                        size,
659
                                        ' '.join([str(self.lookup(vid)) for 
660
                                                  vid in parents]))
1563.2.13 by Robert Collins
InterVersionedFile implemented.
661
        self._transport.append(self._filename, StringIO(content))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
662
663
    def has_version(self, version_id):
664
        """True if the version is in the index."""
665
        return self._cache.has_key(version_id)
666
667
    def get_position(self, version_id):
668
        """Return data position and size of specified version."""
669
        return (self._cache[version_id][2], \
670
                self._cache[version_id][3])
671
672
    def get_method(self, version_id):
673
        """Return compression method of specified version."""
674
        options = self._cache[version_id][1]
675
        if 'fulltext' in options:
676
            return 'fulltext'
677
        else:
678
            assert 'line-delta' in options
679
            return 'line-delta'
680
681
    def get_options(self, version_id):
682
        return self._cache[version_id][1]
683
684
    def get_parents(self, version_id):
685
        """Return parents of specified version."""
686
        return self._cache[version_id][4]
687
688
    def check_versions_present(self, version_ids):
689
        """Check that all specified versions are present."""
690
        version_ids = set(version_ids)
691
        for version_id in list(version_ids):
692
            if version_id in self._cache:
693
                version_ids.remove(version_id)
694
        if version_ids:
695
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
696
697
698
class _KnitData(_KnitComponentFile):
699
    """Contents of the knit data file"""
700
701
    HEADER = "# bzr knit data 7\n"
702
1563.2.5 by Robert Collins
Remove unused transaction references from knit.py and the versionedfile interface.
703
    def __init__(self, transport, filename, mode):
704
        _KnitComponentFile.__init__(self, transport, filename, mode)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
705
        self._file = None
706
        self._checked = False
707
708
    def _open_file(self):
709
        if self._file is None:
710
            try:
711
                self._file = self._transport.get(self._filename)
712
            except NoSuchFile:
713
                pass
714
        return self._file
715
716
    def add_record(self, version_id, digest, lines):
717
        """Write new text record to disk.  Returns the position in the
718
        file where it was written."""
719
        sio = StringIO()
720
        data_file = GzipFile(None, mode='wb', fileobj=sio)
721
        print >>data_file, "version %s %d %s" % (version_id, len(lines), digest)
722
        data_file.writelines(lines)
723
        print >>data_file, "end %s\n" % version_id
724
        data_file.close()
725
726
        content = sio.getvalue()
1563.2.13 by Robert Collins
InterVersionedFile implemented.
727
        start_pos = self._transport.append(self._filename, StringIO(content))
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
728
        return start_pos, len(content)
729
730
    def _parse_record(self, version_id, data):
731
        df = GzipFile(mode='rb', fileobj=StringIO(data))
732
        rec = df.readline().split()
733
        if len(rec) != 4:
734
            raise KnitCorrupt(self._filename, 'unexpected number of records')
735
        if rec[1] != version_id:
736
            raise KnitCorrupt(self.file.name, 
737
                              'unexpected version, wanted %r' % version_id)
738
        lines = int(rec[2])
739
        record_contents = self._read_record_contents(df, lines)
740
        l = df.readline()
741
        if l != 'end %s\n' % version_id:
742
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
743
                        % (l, version_id))
744
        return record_contents, rec[3]
745
746
    def _read_record_contents(self, df, record_lines):
747
        """Read and return n lines from datafile."""
748
        r = []
749
        for i in range(record_lines):
750
            r.append(df.readline())
751
        return r
752
753
    def read_records_iter(self, records):
754
        """Read text records from data file and yield result.
755
756
        Each passed record is a tuple of (version_id, pos, len) and
757
        will be read in the given order.  Yields (version_id,
758
        contents, digest).
759
        """
760
761
        class ContinuousRange:
762
            def __init__(self, rec_id, pos, size):
763
                self.start_pos = pos
764
                self.end_pos = pos + size
765
                self.versions = [(rec_id, pos, size)]
766
767
            def add(self, rec_id, pos, size):
768
                if self.end_pos != pos:
769
                    return False
770
                self.end_pos = pos + size
771
                self.versions.append((rec_id, pos, size))
772
                return True
773
774
            def split(self, fp):
775
                for rec_id, pos, size in self.versions:
776
                    yield rec_id, fp.read(size)
777
778
        fp = self._open_file()
779
780
        # Loop through all records and try to collect as large
781
        # continuous region as possible to read.
782
        while records:
783
            record_id, pos, size = records.pop(0)
784
            continuous_range = ContinuousRange(record_id, pos, size)
785
            while records:
786
                record_id, pos, size = records[0]
787
                if continuous_range.add(record_id, pos, size):
788
                    del records[0]
789
                else:
790
                    break
791
            fp.seek(continuous_range.start_pos, 0)
792
            for record_id, data in continuous_range.split(fp):
793
                content, digest = self._parse_record(record_id, data)
794
                yield record_id, content, digest
795
796
        self._file = None
797
798
    def read_records(self, records):
799
        """Read records into a dictionary."""
800
        components = {}
801
        for record_id, content, digest in self.read_records_iter(records):
802
            components[record_id] = (content, digest)
803
        return components
804
1563.2.13 by Robert Collins
InterVersionedFile implemented.
805
806
class InterKnit(InterVersionedFile):
807
    """Optimised code paths for knit to knit operations."""
808
    
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
809
    _matching_file_factory = KnitVersionedFile
1563.2.13 by Robert Collins
InterVersionedFile implemented.
810
    
811
    @staticmethod
812
    def is_compatible(source, target):
813
        """Be compatible with knits.  """
814
        try:
815
            return (isinstance(source, KnitVersionedFile) and
816
                    isinstance(target, KnitVersionedFile))
817
        except AttributeError:
818
            return False
819
820
    def join(self, pb=None, msg=None, version_ids=None):
821
        """See InterVersionedFile.join."""
822
        assert isinstance(self.source, KnitVersionedFile)
823
        assert isinstance(self.target, KnitVersionedFile)
824
825
        if version_ids is None:
826
            version_ids = self.source.versions()
827
        if not version_ids:
828
            return 0
829
830
        if pb is None:
831
            from bzrlib.progress import DummyProgress
832
            pb = DummyProgress()
833
834
        version_ids = list(version_ids)
835
        if None in version_ids:
836
            version_ids.remove(None)
837
838
        self.source_ancestry = set(self.source.get_ancestry(version_ids))
839
        this_versions = set(self.target._index.get_versions())
840
        needed_versions = self.source_ancestry - this_versions
841
        cross_check_versions = self.source_ancestry.intersection(this_versions)
842
        mismatched_versions = set()
843
        for version in cross_check_versions:
844
            # scan to include needed parents.
845
            n1 = set(self.target.get_parents(version))
846
            n2 = set(self.source.get_parents(version))
847
            if n1 != n2:
848
                # FIXME TEST this check for cycles being introduced works
849
                # the logic is we have a cycle if in our graph we are an
850
                # ancestor of any of the n2 revisions.
851
                for parent in n2:
852
                    if parent in n1:
853
                        # safe
854
                        continue
855
                    else:
856
                        parent_ancestors = self.source.get_ancestry(parent)
857
                        if version in parent_ancestors:
858
                            raise errors.GraphCycleError([parent, version])
859
                # ensure this parent will be available later.
860
                new_parents = n2.difference(n1)
861
                needed_versions.update(new_parents.difference(this_versions))
862
                mismatched_versions.add(version)
863
864
        if not needed_versions and not cross_check_versions:
865
            return 0
866
        full_list = topo_sort(self.source._index.get_graph())
867
868
        version_list = [i for i in full_list if (not self.target.has_version(i)
869
                        and i in needed_versions)]
870
871
        records = []
872
        for version_id in version_list:
873
            data_pos, data_size = self.source._index.get_position(version_id)
874
            records.append((version_id, data_pos, data_size))
875
876
        count = 0
877
        for version_id, lines, digest \
878
                in self.source._data.read_records_iter(records):
879
            options = self.source._index.get_options(version_id)
880
            parents = self.source._index.get_parents(version_id)
881
            
882
            for parent in parents:
883
                assert self.target.has_version(parent)
884
885
            if self.target.factory.annotated:
886
                # FIXME jrydberg: it should be possible to skip
887
                # re-annotating components if we know that we are
888
                # going to pull all revisions in the same order.
889
                new_version_id = version_id
890
                new_version_idx = self.target._index.num_versions()
891
                if 'fulltext' in options:
892
                    lines = self.target._reannotate_fulltext(self.source, lines,
893
                        new_version_id, new_version_idx)
894
                elif 'line-delta' in options:
895
                    lines = self.target._reannotate_line_delta(self.source, lines,
896
                        new_version_id, new_version_idx)
897
898
            count = count + 1
899
            pb.update(self.target.filename, count, len(version_list))
900
901
            pos, size = self.target._data.add_record(version_id, digest, lines)
902
            self.target._index.add_version(version_id, options, pos, size, parents)
903
904
        for version in mismatched_versions:
905
            n1 = set(self.target.get_parents(version))
906
            n2 = set(self.source.get_parents(version))
907
            # write a combined record to our history.
908
            new_parents = self.target.get_parents(version) + list(n2.difference(n1))
909
            current_values = self.target._index._cache[version]
910
            self.target._index.add_version(version,
911
                                    current_values[1], 
912
                                    current_values[2],
913
                                    current_values[3],
914
                                    new_parents)
915
        pb.clear()
916
        return count
917
918
919
InterVersionedFile.register_optimiser(InterKnit)