/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/knit.py

Better readv coalescing, now with test, and progress during knit index reading.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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.
 
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
 
 
55
"""
 
56
 
 
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.
 
62
# move sha1 out of the content so that join is faster at verifying parents
 
63
# record content length ?
 
64
                  
 
65
 
 
66
from cStringIO import StringIO
 
67
import difflib
 
68
from difflib import SequenceMatcher
 
69
from gzip import GzipFile
 
70
import os
 
71
 
 
72
import bzrlib
 
73
import bzrlib.errors as errors
 
74
from bzrlib.errors import FileExists, NoSuchFile, KnitError, \
 
75
        InvalidRevisionId, KnitCorrupt, KnitHeaderError, \
 
76
        RevisionNotPresent, RevisionAlreadyPresent
 
77
from bzrlib.trace import mutter
 
78
from bzrlib.osutils import contains_whitespace, contains_linebreaks, \
 
79
     sha_strings
 
80
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
 
81
from bzrlib.tsort import topo_sort
 
82
 
 
83
 
 
84
# TODO: Split out code specific to this format into an associated object.
 
85
 
 
86
# TODO: Can we put in some kind of value to check that the index and data
 
87
# files belong together?
 
88
 
 
89
# TODO: accomodate binaries, perhaps by storing a byte count
 
90
 
 
91
# TODO: function to check whole file
 
92
 
 
93
# TODO: atomically append data, then measure backwards from the cursor
 
94
# position after writing to work out where it was located.  we may need to
 
95
# bypass python file buffering.
 
96
 
 
97
DATA_SUFFIX = '.knit'
 
98
INDEX_SUFFIX = '.kndx'
 
99
 
 
100
 
 
101
class KnitContent(object):
 
102
    """Content of a knit version to which deltas can be applied."""
 
103
 
 
104
    def __init__(self, lines):
 
105
        self._lines = lines
 
106
 
 
107
    def annotate_iter(self):
 
108
        """Yield tuples of (origin, text) for each content line."""
 
109
        for origin, text in self._lines:
 
110
            yield origin, text
 
111
 
 
112
    def annotate(self):
 
113
        """Return a list of (origin, text) tuples."""
 
114
        return list(self.annotate_iter())
 
115
 
 
116
    def apply_delta(self, delta):
 
117
        """Apply delta to this content."""
 
118
        offset = 0
 
119
        for start, end, count, lines in delta:
 
120
            self._lines[offset+start:offset+end] = lines
 
121
            offset = offset + (start - end) + count
 
122
 
 
123
    def line_delta_iter(self, new_lines):
 
124
        """Generate line-based delta from new_lines to this content."""
 
125
        new_texts = [text for origin, text in new_lines._lines]
 
126
        old_texts = [text for origin, text in self._lines]
 
127
        s = difflib.SequenceMatcher(None, old_texts, new_texts)
 
128
        for op in s.get_opcodes():
 
129
            if op[0] == 'equal':
 
130
                continue
 
131
            yield (op[1], op[2], op[4]-op[3], new_lines._lines[op[3]:op[4]])
 
132
 
 
133
    def line_delta(self, new_lines):
 
134
        return list(self.line_delta_iter(new_lines))
 
135
 
 
136
    def text(self):
 
137
        return [text for origin, text in self._lines]
 
138
 
 
139
 
 
140
class _KnitFactory(object):
 
141
    """Base factory for creating content objects."""
 
142
 
 
143
    def make(self, lines, version):
 
144
        num_lines = len(lines)
 
145
        return KnitContent(zip([version] * num_lines, lines))
 
146
 
 
147
 
 
148
class KnitAnnotateFactory(_KnitFactory):
 
149
    """Factory for creating annotated Content objects."""
 
150
 
 
151
    annotated = True
 
152
 
 
153
    def parse_fulltext(self, content, version):
 
154
        lines = []
 
155
        for line in content:
 
156
            origin, text = line.split(' ', 1)
 
157
            lines.append((int(origin), text))
 
158
        return KnitContent(lines)
 
159
 
 
160
    def parse_line_delta_iter(self, lines):
 
161
        while lines:
 
162
            header = lines.pop(0)
 
163
            start, end, c = [int(n) for n in header.split(',')]
 
164
            contents = []
 
165
            for i in range(c):
 
166
                origin, text = lines.pop(0).split(' ', 1)
 
167
                contents.append((int(origin), text))
 
168
            yield start, end, c, contents
 
169
 
 
170
    def parse_line_delta(self, lines, version):
 
171
        return list(self.parse_line_delta_iter(lines))
 
172
 
 
173
    def lower_fulltext(self, content):
 
174
        return ['%d %s' % (o, t) for o, t in content._lines]
 
175
 
 
176
    def lower_line_delta(self, delta):
 
177
        out = []
 
178
        for start, end, c, lines in delta:
 
179
            out.append('%d,%d,%d\n' % (start, end, c))
 
180
            for origin, text in lines:
 
181
                out.append('%d %s' % (origin, text))
 
182
        return out
 
183
 
 
184
 
 
185
class KnitPlainFactory(_KnitFactory):
 
186
    """Factory for creating plain Content objects."""
 
187
 
 
188
    annotated = False
 
189
 
 
190
    def parse_fulltext(self, content, version):
 
191
        return self.make(content, version)
 
192
 
 
193
    def parse_line_delta_iter(self, lines, version):
 
194
        while lines:
 
195
            header = lines.pop(0)
 
196
            start, end, c = [int(n) for n in header.split(',')]
 
197
            yield start, end, c, zip([version] * c, lines[:c])
 
198
            del lines[:c]
 
199
 
 
200
    def parse_line_delta(self, lines, version):
 
201
        return list(self.parse_line_delta_iter(lines, version))
 
202
    
 
203
    def lower_fulltext(self, content):
 
204
        return content.text()
 
205
 
 
206
    def lower_line_delta(self, delta):
 
207
        out = []
 
208
        for start, end, c, lines in delta:
 
209
            out.append('%d,%d,%d\n' % (start, end, c))
 
210
            out.extend([text for origin, text in lines])
 
211
        return out
 
212
 
 
213
 
 
214
def make_empty_knit(transport, relpath):
 
215
    """Construct a empty knit at the specified location."""
 
216
    k = KnitVersionedFile(transport, relpath, 'w', KnitPlainFactory)
 
217
    k._data._open_file()
 
218
 
 
219
 
 
220
class KnitVersionedFile(VersionedFile):
 
221
    """Weave-like structure with faster random access.
 
222
 
 
223
    A knit stores a number of texts and a summary of the relationships
 
224
    between them.  Texts are identified by a string version-id.  Texts
 
225
    are normally stored and retrieved as a series of lines, but can
 
226
    also be passed as single strings.
 
227
 
 
228
    Lines are stored with the trailing newline (if any) included, to
 
229
    avoid special cases for files with no final newline.  Lines are
 
230
    composed of 8-bit characters, not unicode.  The combination of
 
231
    these approaches should mean any 'binary' file can be safely
 
232
    stored and retrieved.
 
233
    """
 
234
 
 
235
    def __init__(self, relpath, transport, file_mode=None, access_mode=None, factory=None,
 
236
                 basis_knit=None, delta=True, create=False):
 
237
        """Construct a knit at location specified by relpath.
 
238
        
 
239
        :param create: If not True, only open an existing knit.
 
240
        """
 
241
        if access_mode is None:
 
242
            access_mode = 'w'
 
243
        assert access_mode in ('r', 'w'), "invalid mode specified %r" % access_mode
 
244
        assert not basis_knit or isinstance(basis_knit, KnitVersionedFile), \
 
245
            type(basis_knit)
 
246
 
 
247
        self.transport = transport
 
248
        self.filename = relpath
 
249
        self.basis_knit = basis_knit
 
250
        self.factory = factory or KnitAnnotateFactory()
 
251
        self.writable = (access_mode == 'w')
 
252
        self.delta = delta
 
253
 
 
254
        self._index = _KnitIndex(transport, relpath + INDEX_SUFFIX,
 
255
            access_mode, create=create)
 
256
        self._data = _KnitData(transport, relpath + DATA_SUFFIX,
 
257
            access_mode, create=not len(self.versions()))
 
258
 
 
259
    def copy_to(self, name, transport):
 
260
        """See VersionedFile.copy_to()."""
 
261
        # copy the current index to a temp index to avoid racing with local
 
262
        # writes
 
263
        transport.put(name + INDEX_SUFFIX + '.tmp', self.transport.get(self._index._filename))
 
264
        # copy the data file
 
265
        transport.put(name + DATA_SUFFIX, self._data._open_file())
 
266
        # rename the copied index into place
 
267
        transport.rename(name + INDEX_SUFFIX + '.tmp', name + INDEX_SUFFIX)
 
268
 
 
269
    def create_empty(self, name, transport, mode=None):
 
270
        return KnitVersionedFile(name, transport, factory=self.factory, delta=self.delta, create=True)
 
271
    
 
272
    def fix_parents(self, version, new_parents):
 
273
        """Fix the parents list for version.
 
274
        
 
275
        This is done by appending a new version to the index
 
276
        with identical data except for the parents list.
 
277
        the parents list must be a superset of the current
 
278
        list.
 
279
        """
 
280
        current_values = self._index._cache[version]
 
281
        assert set(current_values[4]).difference(set(new_parents)) == set()
 
282
        self._index.add_version(version,
 
283
                                current_values[1], 
 
284
                                current_values[2],
 
285
                                current_values[3],
 
286
                                new_parents)
 
287
 
 
288
    def get_graph_with_ghosts(self):
 
289
        """See VersionedFile.get_graph_with_ghosts()."""
 
290
        graph_items = self._index.get_graph()
 
291
        return dict(graph_items)
 
292
 
 
293
    @staticmethod
 
294
    def get_suffixes():
 
295
        """See VersionedFile.get_suffixes()."""
 
296
        return [DATA_SUFFIX, INDEX_SUFFIX]
 
297
 
 
298
    def has_ghost(self, version_id):
 
299
        """True if there is a ghost reference in the file to version_id."""
 
300
        # maybe we have it
 
301
        if self.has_version(version_id):
 
302
            return False
 
303
        # optimisable if needed by memoising the _ghosts set.
 
304
        items = self._index.get_graph()
 
305
        for node, parents in items:
 
306
            for parent in parents:
 
307
                if parent not in self._index._cache:
 
308
                    if parent == version_id:
 
309
                        return True
 
310
        return False
 
311
 
 
312
    def versions(self):
 
313
        """See VersionedFile.versions."""
 
314
        return self._index.get_versions()
 
315
 
 
316
    def has_version(self, version_id):
 
317
        """See VersionedFile.has_version."""
 
318
        return self._index.has_version(version_id)
 
319
 
 
320
    __contains__ = has_version
 
321
 
 
322
    def _merge_annotations(self, content, parents):
 
323
        """Merge annotations for content.  This is done by comparing
 
324
        the annotations based on changed to the text."""
 
325
        for parent_id in parents:
 
326
            merge_content = self._get_content(parent_id)
 
327
            seq = SequenceMatcher(None, merge_content.text(), content.text())
 
328
            for i, j, n in seq.get_matching_blocks():
 
329
                if n == 0:
 
330
                    continue
 
331
                content._lines[j:j+n] = merge_content._lines[i:i+n]
 
332
 
 
333
    def _get_components(self, version_id):
 
334
        """Return a list of (version_id, method, data) tuples that
 
335
        makes up version specified by version_id of the knit.
 
336
 
 
337
        The components should be applied in the order of the returned
 
338
        list.
 
339
 
 
340
        The basis knit will be used to the largest extent possible
 
341
        since it is assumed that accesses to it is faster.
 
342
        """
 
343
        # needed_revisions holds a list of (method, version_id) of
 
344
        # versions that is needed to be fetched to construct the final
 
345
        # version of the file.
 
346
        #
 
347
        # basis_revisions is a list of versions that needs to be
 
348
        # fetched but exists in the basis knit.
 
349
 
 
350
        basis = self.basis_knit
 
351
        needed_versions = []
 
352
        basis_versions = []
 
353
        cursor = version_id
 
354
 
 
355
        while 1:
 
356
            picked_knit = self
 
357
            if basis and basis._index.has_version(cursor):
 
358
                picked_knit = basis
 
359
                basis_versions.append(cursor)
 
360
            method = picked_knit._index.get_method(cursor)
 
361
            needed_versions.append((method, cursor))
 
362
            if method == 'fulltext':
 
363
                break
 
364
            cursor = picked_knit.get_parents(cursor)[0]
 
365
 
 
366
        components = {}
 
367
        if basis_versions:
 
368
            records = []
 
369
            for comp_id in basis_versions:
 
370
                data_pos, data_size = basis._index.get_data_position(comp_id)
 
371
                records.append((piece_id, data_pos, data_size))
 
372
            components.update(basis._data.read_records(records))
 
373
 
 
374
        records = []
 
375
        for comp_id in [vid for method, vid in needed_versions
 
376
                        if vid not in basis_versions]:
 
377
            data_pos, data_size = self._index.get_position(comp_id)
 
378
            records.append((comp_id, data_pos, data_size))
 
379
        components.update(self._data.read_records(records))
 
380
 
 
381
        # get_data_records returns a mapping with the version id as
 
382
        # index and the value as data.  The order the components need
 
383
        # to be applied is held by needed_versions (reversed).
 
384
        out = []
 
385
        for method, comp_id in reversed(needed_versions):
 
386
            out.append((comp_id, method, components[comp_id]))
 
387
 
 
388
        return out
 
389
 
 
390
    def _get_content(self, version_id):
 
391
        """Returns a content object that makes up the specified
 
392
        version."""
 
393
        if not self.has_version(version_id):
 
394
            raise RevisionNotPresent(version_id, self.filename)
 
395
 
 
396
        if self.basis_knit and version_id in self.basis_knit:
 
397
            return self.basis_knit._get_content(version_id)
 
398
 
 
399
        content = None
 
400
        components = self._get_components(version_id)
 
401
        for component_id, method, (data, digest) in components:
 
402
            version_idx = self._index.lookup(component_id)
 
403
            if method == 'fulltext':
 
404
                assert content is None
 
405
                content = self.factory.parse_fulltext(data, version_idx)
 
406
            elif method == 'line-delta':
 
407
                delta = self.factory.parse_line_delta(data, version_idx)
 
408
                content.apply_delta(delta)
 
409
 
 
410
        if 'no-eol' in self._index.get_options(version_id):
 
411
            line = content._lines[-1][1].rstrip('\n')
 
412
            content._lines[-1] = (content._lines[-1][0], line)
 
413
 
 
414
        if sha_strings(content.text()) != digest:
 
415
            raise KnitCorrupt(self.filename, 'sha-1 does not match')
 
416
 
 
417
        return content
 
418
 
 
419
    def _check_versions_present(self, version_ids):
 
420
        """Check that all specified versions are present."""
 
421
        version_ids = set(version_ids)
 
422
        for r in list(version_ids):
 
423
            if self._index.has_version(r):
 
424
                version_ids.remove(r)
 
425
        if version_ids:
 
426
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
427
 
 
428
    def add_lines_with_ghosts(self, version_id, parents, lines):
 
429
        """See VersionedFile.add_lines_with_ghosts()."""
 
430
        self._check_add(version_id, lines)
 
431
        return self._add(version_id, lines[:], parents, self.delta)
 
432
 
 
433
    def add_lines(self, version_id, parents, lines):
 
434
        """See VersionedFile.add_lines."""
 
435
        self._check_add(version_id, lines)
 
436
        self._check_versions_present(parents)
 
437
        return self._add(version_id, lines[:], parents, self.delta)
 
438
 
 
439
    def _check_add(self, version_id, lines):
 
440
        """check that version_id and lines are safe to add."""
 
441
        assert self.writable, "knit is not opened for write"
 
442
        ### FIXME escape. RBC 20060228
 
443
        if contains_whitespace(version_id):
 
444
            raise InvalidRevisionId(version_id)
 
445
        if self.has_version(version_id):
 
446
            raise RevisionAlreadyPresent(version_id, self.filename)
 
447
 
 
448
        if False or __debug__:
 
449
            for l in lines:
 
450
                assert '\n' not in l[:-1]
 
451
 
 
452
    def _add(self, version_id, lines, parents, delta):
 
453
        """Add a set of lines on top of version specified by parents.
 
454
 
 
455
        If delta is true, compress the text as a line-delta against
 
456
        the first parent.
 
457
 
 
458
        Any versions not present will be converted into ghosts.
 
459
        """
 
460
        ghostless_parents = []
 
461
        ghosts = []
 
462
        for parent in parents:
 
463
            if not self.has_version(parent):
 
464
                ghosts.append(parent)
 
465
            else:
 
466
                ghostless_parents.append(parent)
 
467
 
 
468
        if delta and not len(ghostless_parents):
 
469
            delta = False
 
470
 
 
471
        digest = sha_strings(lines)
 
472
        options = []
 
473
        if lines:
 
474
            if lines[-1][-1] != '\n':
 
475
                options.append('no-eol')
 
476
                lines[-1] = lines[-1] + '\n'
 
477
 
 
478
        lines = self.factory.make(lines, len(self._index))
 
479
        if self.factory.annotated and len(ghostless_parents) > 0:
 
480
            # Merge annotations from parent texts if so is needed.
 
481
            self._merge_annotations(lines, ghostless_parents)
 
482
 
 
483
        if len(ghostless_parents) and delta:
 
484
            # To speed the extract of texts the delta chain is limited
 
485
            # to a fixed number of deltas.  This should minimize both
 
486
            # I/O and the time spend applying deltas.
 
487
            count = 0
 
488
            delta_parents = ghostless_parents
 
489
            while count < 25:
 
490
                parent = delta_parents[0]
 
491
                method = self._index.get_method(parent)
 
492
                if method == 'fulltext':
 
493
                    break
 
494
                delta_parents = self._index.get_parents(parent)
 
495
                count = count + 1
 
496
            if method == 'line-delta':
 
497
                delta = False
 
498
 
 
499
        if delta:
 
500
            options.append('line-delta')
 
501
            content = self._get_content(ghostless_parents[0])
 
502
            delta_hunks = content.line_delta(lines)
 
503
            store_lines = self.factory.lower_line_delta(delta_hunks)
 
504
        else:
 
505
            options.append('fulltext')
 
506
            store_lines = self.factory.lower_fulltext(lines)
 
507
 
 
508
        where, size = self._data.add_record(version_id, digest, store_lines)
 
509
        self._index.add_version(version_id, options, where, size, parents)
 
510
 
 
511
    def check(self, progress_bar=None):
 
512
        """See VersionedFile.check()."""
 
513
 
 
514
    def clone_text(self, new_version_id, old_version_id, parents):
 
515
        """See VersionedFile.clone_text()."""
 
516
        # FIXME RBC 20060228 make fast by only inserting an index with null delta.
 
517
        self.add_lines(new_version_id, parents, self.get_lines(old_version_id))
 
518
 
 
519
    def get_lines(self, version_id):
 
520
        """See VersionedFile.get_lines()."""
 
521
        return self._get_content(version_id).text()
 
522
 
 
523
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
 
524
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
 
525
        if version_ids is None:
 
526
            version_ids = self.versions()
 
527
        # we dont care about inclusions, the caller cares.
 
528
        # but we need to setup a list of records to visit.
 
529
        # we need version_id, position, length
 
530
        version_id_records = []
 
531
        for version_id in version_ids:
 
532
            if not self.has_version(version_id):
 
533
                raise RevisionNotPresent(version_id, self.filename)
 
534
            data_pos, length = self._index.get_position(version_id)
 
535
            version_id_records.append((version_id, data_pos, length))
 
536
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
537
        count = 0
 
538
        total = len(version_id_records)
 
539
        try:
 
540
            for version_id, data, sha_value in \
 
541
                self._data.read_records_iter(version_id_records):
 
542
                pb.update('Walking content.', count, total)
 
543
                method = self._index.get_method(version_id)
 
544
                version_idx = self._index.lookup(version_id)
 
545
                assert method in ('fulltext', 'line-delta')
 
546
                if method == 'fulltext':
 
547
                    content = self.factory.parse_fulltext(data, version_idx)
 
548
                    for line in content.text():
 
549
                        yield line
 
550
                else:
 
551
                    delta = self.factory.parse_line_delta(data, version_idx)
 
552
                    for start, end, count, lines in delta:
 
553
                        for origin, line in lines:
 
554
                            yield line
 
555
                count +=1
 
556
        except:
 
557
            pb.update('Walking content.', total, total)
 
558
            pb.finished()
 
559
            raise
 
560
        
 
561
    def num_versions(self):
 
562
        """See VersionedFile.num_versions()."""
 
563
        return self._index.num_versions()
 
564
 
 
565
    __len__ = num_versions
 
566
 
 
567
    def annotate_iter(self, version_id):
 
568
        """See VersionedFile.annotate_iter."""
 
569
        content = self._get_content(version_id)
 
570
        for origin, text in content.annotate_iter():
 
571
            yield self._index.idx_to_name(origin), text
 
572
 
 
573
    def get_parents(self, version_id):
 
574
        """See VersionedFile.get_parents."""
 
575
        self._check_versions_present([version_id])
 
576
        return list(self._index.get_parents(version_id))
 
577
 
 
578
    def get_parents_with_ghosts(self, version_id):
 
579
        """See VersionedFile.get_parents."""
 
580
        self._check_versions_present([version_id])
 
581
        return list(self._index.get_parents_with_ghosts(version_id))
 
582
 
 
583
    def get_ancestry(self, versions):
 
584
        """See VersionedFile.get_ancestry."""
 
585
        if isinstance(versions, basestring):
 
586
            versions = [versions]
 
587
        if not versions:
 
588
            return []
 
589
        self._check_versions_present(versions)
 
590
        return self._index.get_ancestry(versions)
 
591
 
 
592
    def get_ancestry_with_ghosts(self, versions):
 
593
        """See VersionedFile.get_ancestry_with_ghosts."""
 
594
        if isinstance(versions, basestring):
 
595
            versions = [versions]
 
596
        if not versions:
 
597
            return []
 
598
        self._check_versions_present(versions)
 
599
        return self._index.get_ancestry_with_ghosts(versions)
 
600
 
 
601
    def _reannotate_line_delta(self, other, lines, new_version_id,
 
602
                               new_version_idx):
 
603
        """Re-annotate line-delta and return new delta."""
 
604
        new_delta = []
 
605
        for start, end, count, contents \
 
606
                in self.factory.parse_line_delta_iter(lines):
 
607
            new_lines = []
 
608
            for origin, line in contents:
 
609
                old_version_id = other._index.idx_to_name(origin)
 
610
                if old_version_id == new_version_id:
 
611
                    idx = new_version_idx
 
612
                else:
 
613
                    idx = self._index.lookup(old_version_id)
 
614
                new_lines.append((idx, line))
 
615
            new_delta.append((start, end, count, new_lines))
 
616
 
 
617
        return self.factory.lower_line_delta(new_delta)
 
618
 
 
619
    def _reannotate_fulltext(self, other, lines, new_version_id,
 
620
                             new_version_idx):
 
621
        """Re-annotate fulltext and return new version."""
 
622
        content = self.factory.parse_fulltext(lines, new_version_idx)
 
623
        new_lines = []
 
624
        for origin, line in content.annotate_iter():
 
625
            old_version_id = other._index.idx_to_name(origin)
 
626
            if old_version_id == new_version_id:
 
627
                idx = new_version_idx
 
628
            else:
 
629
                idx = self._index.lookup(old_version_id)
 
630
            new_lines.append((idx, line))
 
631
 
 
632
        return self.factory.lower_fulltext(KnitContent(new_lines))
 
633
 
 
634
    #@deprecated_method(zero_eight)
 
635
    def walk(self, version_ids):
 
636
        """See VersionedFile.walk."""
 
637
        # We take the short path here, and extract all relevant texts
 
638
        # and put them in a weave and let that do all the work.  Far
 
639
        # from optimal, but is much simpler.
 
640
        # FIXME RB 20060228 this really is inefficient!
 
641
        from bzrlib.weave import Weave
 
642
 
 
643
        w = Weave(self.filename)
 
644
        ancestry = self.get_ancestry(version_ids)
 
645
        sorted_graph = topo_sort(self._index.get_graph())
 
646
        version_list = [vid for vid in sorted_graph if vid in ancestry]
 
647
        
 
648
        for version_id in version_list:
 
649
            lines = self.get_lines(version_id)
 
650
            w.add_lines(version_id, self.get_parents(version_id), lines)
 
651
 
 
652
        for lineno, insert_id, dset, line in w.walk(version_ids):
 
653
            yield lineno, insert_id, dset, line
 
654
 
 
655
 
 
656
class _KnitComponentFile(object):
 
657
    """One of the files used to implement a knit database"""
 
658
 
 
659
    def __init__(self, transport, filename, mode):
 
660
        self._transport = transport
 
661
        self._filename = filename
 
662
        self._mode = mode
 
663
 
 
664
    def write_header(self):
 
665
        old_len = self._transport.append(self._filename, StringIO(self.HEADER))
 
666
        if old_len != 0:
 
667
            raise KnitCorrupt(self._filename, 'misaligned after writing header')
 
668
 
 
669
    def check_header(self, fp):
 
670
        line = fp.read(len(self.HEADER))
 
671
        if line != self.HEADER:
 
672
            raise KnitHeaderError(badline=line)
 
673
 
 
674
    def commit(self):
 
675
        """Commit is a nop."""
 
676
 
 
677
    def __repr__(self):
 
678
        return '%s(%s)' % (self.__class__.__name__, self._filename)
 
679
 
 
680
 
 
681
class _KnitIndex(_KnitComponentFile):
 
682
    """Manages knit index file.
 
683
 
 
684
    The index is already kept in memory and read on startup, to enable
 
685
    fast lookups of revision information.  The cursor of the index
 
686
    file is always pointing to the end, making it easy to append
 
687
    entries.
 
688
 
 
689
    _cache is a cache for fast mapping from version id to a Index
 
690
    object.
 
691
 
 
692
    _history is a cache for fast mapping from indexes to version ids.
 
693
 
 
694
    The index data format is dictionary compressed when it comes to
 
695
    parent references; a index entry may only have parents that with a
 
696
    lover index number.  As a result, the index is topological sorted.
 
697
 
 
698
    Duplicate entries may be written to the index for a single version id
 
699
    if this is done then the latter one completely replaces the former:
 
700
    this allows updates to correct version and parent information. 
 
701
    Note that the two entries may share the delta, and that successive
 
702
    annotations and references MUST point to the first entry.
 
703
    """
 
704
 
 
705
    HEADER = "# bzr knit index 7\n"
 
706
 
 
707
    def _cache_version(self, version_id, options, pos, size, parents):
 
708
        val = (version_id, options, pos, size, parents)
 
709
        self._cache[version_id] = val
 
710
        if not version_id in self._history:
 
711
            self._history.append(version_id)
 
712
 
 
713
    def _iter_index(self, fp):
 
714
        for l in fp.readlines():
 
715
            yield l.split()
 
716
        #lines = fp.read()
 
717
        #for l in lines.splitlines(False):
 
718
        #    yield l.split()
 
719
 
 
720
    def __init__(self, transport, filename, mode, create=False):
 
721
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
722
        self._cache = {}
 
723
        # position in _history is the 'official' index for a revision
 
724
        # but the values may have come from a newer entry.
 
725
        # so - wc -l of a knit index is != the number of uniqe names
 
726
        # in the weave.
 
727
        self._history = []
 
728
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
729
        try:
 
730
            count = 0
 
731
            total = 1
 
732
            try:
 
733
                pb.update('read knit index', count, total)
 
734
                fp = self._transport.get(self._filename)
 
735
                self.check_header(fp)
 
736
                for rec in self._iter_index(fp):
 
737
                    count += 1
 
738
                    total += 1
 
739
                    pb.update('read knit index', count, total)
 
740
                    parents = self._parse_parents(rec[4:])
 
741
                    self._cache_version(rec[0], rec[1].split(','), int(rec[2]), int(rec[3]),
 
742
                        parents)
 
743
            except NoSuchFile, e:
 
744
                if mode != 'w' or not create:
 
745
                    raise
 
746
                self.write_header()
 
747
        finally:
 
748
            pb.update('read knit index', total, total)
 
749
            pb.finished()
 
750
 
 
751
    def _parse_parents(self, compressed_parents):
 
752
        """convert a list of string parent values into version ids.
 
753
 
 
754
        ints are looked up in the index.
 
755
        .FOO values are ghosts and converted in to FOO.
 
756
        """
 
757
        result = []
 
758
        for value in compressed_parents:
 
759
            if value.startswith('.'):
 
760
                result.append(value[1:])
 
761
            else:
 
762
                assert isinstance(value, str)
 
763
                result.append(self._history[int(value)])
 
764
        return result
 
765
 
 
766
    def get_graph(self):
 
767
        graph = []
 
768
        for version_id, index in self._cache.iteritems():
 
769
            graph.append((version_id, index[4]))
 
770
        return graph
 
771
 
 
772
    def get_ancestry(self, versions):
 
773
        """See VersionedFile.get_ancestry."""
 
774
        # get a graph of all the mentioned versions:
 
775
        graph = {}
 
776
        pending = set(versions)
 
777
        while len(pending):
 
778
            version = pending.pop()
 
779
            parents = self._cache[version][4]
 
780
            # got the parents ok
 
781
            # trim ghosts
 
782
            parents = [parent for parent in parents if parent in self._cache]
 
783
            for parent in parents:
 
784
                # if not completed and not a ghost
 
785
                if parent not in graph:
 
786
                    pending.add(parent)
 
787
            graph[version] = parents
 
788
        return topo_sort(graph.items())
 
789
 
 
790
    def get_ancestry_with_ghosts(self, versions):
 
791
        """See VersionedFile.get_ancestry_with_ghosts."""
 
792
        # get a graph of all the mentioned versions:
 
793
        graph = {}
 
794
        pending = set(versions)
 
795
        while len(pending):
 
796
            version = pending.pop()
 
797
            try:
 
798
                parents = self._cache[version][4]
 
799
            except KeyError:
 
800
                # ghost, fake it
 
801
                graph[version] = []
 
802
                pass
 
803
            else:
 
804
                # got the parents ok
 
805
                for parent in parents:
 
806
                    if parent not in graph:
 
807
                        pending.add(parent)
 
808
                graph[version] = parents
 
809
        return topo_sort(graph.items())
 
810
 
 
811
    def num_versions(self):
 
812
        return len(self._history)
 
813
 
 
814
    __len__ = num_versions
 
815
 
 
816
    def get_versions(self):
 
817
        return self._history
 
818
 
 
819
    def idx_to_name(self, idx):
 
820
        return self._history[idx]
 
821
 
 
822
    def lookup(self, version_id):
 
823
        assert version_id in self._cache
 
824
        return self._history.index(version_id)
 
825
 
 
826
    def _version_list_to_index(self, versions):
 
827
        result_list = []
 
828
        for version in versions:
 
829
            if version in self._cache:
 
830
                result_list.append(str(self._history.index(version)))
 
831
            else:
 
832
                result_list.append('.' + version.encode('utf-8'))
 
833
        return ' '.join(result_list)
 
834
 
 
835
    def add_version(self, version_id, options, pos, size, parents):
 
836
        """Add a version record to the index."""
 
837
        self._cache_version(version_id, options, pos, size, parents)
 
838
 
 
839
        content = "%s %s %s %s %s\n" % (version_id,
 
840
                                        ','.join(options),
 
841
                                        pos,
 
842
                                        size,
 
843
                                        self._version_list_to_index(parents))
 
844
        self._transport.append(self._filename, StringIO(content))
 
845
 
 
846
    def has_version(self, version_id):
 
847
        """True if the version is in the index."""
 
848
        return self._cache.has_key(version_id)
 
849
 
 
850
    def get_position(self, version_id):
 
851
        """Return data position and size of specified version."""
 
852
        return (self._cache[version_id][2], \
 
853
                self._cache[version_id][3])
 
854
 
 
855
    def get_method(self, version_id):
 
856
        """Return compression method of specified version."""
 
857
        options = self._cache[version_id][1]
 
858
        if 'fulltext' in options:
 
859
            return 'fulltext'
 
860
        else:
 
861
            assert 'line-delta' in options
 
862
            return 'line-delta'
 
863
 
 
864
    def get_options(self, version_id):
 
865
        return self._cache[version_id][1]
 
866
 
 
867
    def get_parents(self, version_id):
 
868
        """Return parents of specified version ignoring ghosts."""
 
869
        return [parent for parent in self._cache[version_id][4] 
 
870
                if parent in self._cache]
 
871
 
 
872
    def get_parents_with_ghosts(self, version_id):
 
873
        """Return parents of specified version wth ghosts."""
 
874
        return self._cache[version_id][4] 
 
875
 
 
876
    def check_versions_present(self, version_ids):
 
877
        """Check that all specified versions are present."""
 
878
        version_ids = set(version_ids)
 
879
        for version_id in list(version_ids):
 
880
            if version_id in self._cache:
 
881
                version_ids.remove(version_id)
 
882
        if version_ids:
 
883
            raise RevisionNotPresent(list(version_ids)[0], self.filename)
 
884
 
 
885
 
 
886
class _KnitData(_KnitComponentFile):
 
887
    """Contents of the knit data file"""
 
888
 
 
889
    HEADER = "# bzr knit data 7\n"
 
890
 
 
891
    def __init__(self, transport, filename, mode, create=False):
 
892
        _KnitComponentFile.__init__(self, transport, filename, mode)
 
893
        self._file = None
 
894
        self._checked = False
 
895
        if create:
 
896
            self._transport.put(self._filename, StringIO(''))
 
897
 
 
898
    def _open_file(self):
 
899
        if self._file is None:
 
900
            try:
 
901
                self._file = self._transport.get(self._filename)
 
902
            except NoSuchFile:
 
903
                pass
 
904
        return self._file
 
905
 
 
906
    def add_record(self, version_id, digest, lines):
 
907
        """Write new text record to disk.  Returns the position in the
 
908
        file where it was written."""
 
909
        sio = StringIO()
 
910
        data_file = GzipFile(None, mode='wb', fileobj=sio)
 
911
        print >>data_file, "version %s %d %s" % (version_id, len(lines), digest)
 
912
        data_file.writelines(lines)
 
913
        print >>data_file, "end %s\n" % version_id
 
914
        data_file.close()
 
915
 
 
916
        content = sio.getvalue()
 
917
        start_pos = self._transport.append(self._filename, StringIO(content))
 
918
        return start_pos, len(content)
 
919
 
 
920
    def _parse_record(self, version_id, data):
 
921
        df = GzipFile(mode='rb', fileobj=StringIO(data))
 
922
        rec = df.readline().split()
 
923
        if len(rec) != 4:
 
924
            raise KnitCorrupt(self._filename, 'unexpected number of records')
 
925
        if rec[1] != version_id:
 
926
            raise KnitCorrupt(self.file.name, 
 
927
                              'unexpected version, wanted %r' % version_id)
 
928
        lines = int(rec[2])
 
929
        record_contents = self._read_record_contents(df, lines)
 
930
        l = df.readline()
 
931
        if l != 'end %s\n' % version_id:
 
932
            raise KnitCorrupt(self._filename, 'unexpected version end line %r, wanted %r' 
 
933
                        % (l, version_id))
 
934
        return record_contents, rec[3]
 
935
 
 
936
    def _read_record_contents(self, df, record_lines):
 
937
        """Read and return n lines from datafile."""
 
938
        r = []
 
939
        for i in range(record_lines):
 
940
            r.append(df.readline())
 
941
        return r
 
942
 
 
943
    def read_records_iter(self, records):
 
944
        """Read text records from data file and yield result.
 
945
 
 
946
        Each passed record is a tuple of (version_id, pos, len) and
 
947
        will be read in the given order.  Yields (version_id,
 
948
        contents, digest).
 
949
        """
 
950
 
 
951
        class ContinuousRange:
 
952
            def __init__(self, rec_id, pos, size):
 
953
                self.start_pos = pos
 
954
                self.end_pos = pos + size
 
955
                self.versions = [(rec_id, pos, size)]
 
956
 
 
957
            def add(self, rec_id, pos, size):
 
958
                if self.end_pos != pos:
 
959
                    return False
 
960
                self.end_pos = pos + size
 
961
                self.versions.append((rec_id, pos, size))
 
962
                return True
 
963
 
 
964
            def split(self, fp):
 
965
                for rec_id, pos, size in self.versions:
 
966
                    yield rec_id, fp.read(size)
 
967
 
 
968
        # We take it that the transport optimizes the fetching as good
 
969
        # as possible (ie, reads continous ranges.)
 
970
        response = self._transport.readv(self._filename,
 
971
            [(pos, size) for version_id, pos, size in records])
 
972
 
 
973
        for (record_id, pos, size), (pos, data) in zip(records, response):
 
974
            content, digest = self._parse_record(record_id, data)
 
975
            yield record_id, content, digest
 
976
 
 
977
    def read_records(self, records):
 
978
        """Read records into a dictionary."""
 
979
        components = {}
 
980
        for record_id, content, digest in self.read_records_iter(records):
 
981
            components[record_id] = (content, digest)
 
982
        return components
 
983
 
 
984
 
 
985
class InterKnit(InterVersionedFile):
 
986
    """Optimised code paths for knit to knit operations."""
 
987
    
 
988
    _matching_file_factory = KnitVersionedFile
 
989
    
 
990
    @staticmethod
 
991
    def is_compatible(source, target):
 
992
        """Be compatible with knits.  """
 
993
        try:
 
994
            return (isinstance(source, KnitVersionedFile) and
 
995
                    isinstance(target, KnitVersionedFile))
 
996
        except AttributeError:
 
997
            return False
 
998
 
 
999
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
1000
        """See InterVersionedFile.join."""
 
1001
        assert isinstance(self.source, KnitVersionedFile)
 
1002
        assert isinstance(self.target, KnitVersionedFile)
 
1003
 
 
1004
        if version_ids is None:
 
1005
            version_ids = self.source.versions()
 
1006
        else:
 
1007
            if not ignore_missing:
 
1008
                self.source._check_versions_present(version_ids)
 
1009
            else:
 
1010
                version_ids = set(self.source.versions()).intersection(
 
1011
                    set(version_ids))
 
1012
 
 
1013
        if not version_ids:
 
1014
            return 0
 
1015
 
 
1016
        if pb is None:
 
1017
            from bzrlib.progress import DummyProgress
 
1018
            pb = DummyProgress()
 
1019
 
 
1020
        version_ids = list(version_ids)
 
1021
        if None in version_ids:
 
1022
            version_ids.remove(None)
 
1023
 
 
1024
        self.source_ancestry = set(self.source.get_ancestry(version_ids))
 
1025
        this_versions = set(self.target._index.get_versions())
 
1026
        needed_versions = self.source_ancestry - this_versions
 
1027
        cross_check_versions = self.source_ancestry.intersection(this_versions)
 
1028
        mismatched_versions = set()
 
1029
        for version in cross_check_versions:
 
1030
            # scan to include needed parents.
 
1031
            n1 = set(self.target.get_parents_with_ghosts(version))
 
1032
            n2 = set(self.source.get_parents_with_ghosts(version))
 
1033
            if n1 != n2:
 
1034
                # FIXME TEST this check for cycles being introduced works
 
1035
                # the logic is we have a cycle if in our graph we are an
 
1036
                # ancestor of any of the n2 revisions.
 
1037
                for parent in n2:
 
1038
                    if parent in n1:
 
1039
                        # safe
 
1040
                        continue
 
1041
                    else:
 
1042
                        parent_ancestors = self.source.get_ancestry(parent)
 
1043
                        if version in parent_ancestors:
 
1044
                            raise errors.GraphCycleError([parent, version])
 
1045
                # ensure this parent will be available later.
 
1046
                new_parents = n2.difference(n1)
 
1047
                needed_versions.update(new_parents.difference(this_versions))
 
1048
                mismatched_versions.add(version)
 
1049
 
 
1050
        if not needed_versions and not cross_check_versions:
 
1051
            return 0
 
1052
        full_list = topo_sort(self.source.get_graph())
 
1053
 
 
1054
        version_list = [i for i in full_list if (not self.target.has_version(i)
 
1055
                        and i in needed_versions)]
 
1056
 
 
1057
        records = []
 
1058
        for version_id in version_list:
 
1059
            data_pos, data_size = self.source._index.get_position(version_id)
 
1060
            records.append((version_id, data_pos, data_size))
 
1061
 
 
1062
        count = 0
 
1063
        for version_id, lines, digest \
 
1064
                in self.source._data.read_records_iter(records):
 
1065
            options = self.source._index.get_options(version_id)
 
1066
            parents = self.source._index.get_parents_with_ghosts(version_id)
 
1067
            
 
1068
            for parent in parents:
 
1069
                # if source has the parent, we must hav grabbed it first.
 
1070
                assert (self.target.has_version(parent) or not
 
1071
                        self.source.has_version(parent))
 
1072
 
 
1073
            if self.target.factory.annotated:
 
1074
                # FIXME jrydberg: it should be possible to skip
 
1075
                # re-annotating components if we know that we are
 
1076
                # going to pull all revisions in the same order.
 
1077
                new_version_id = version_id
 
1078
                new_version_idx = self.target._index.num_versions()
 
1079
                if 'fulltext' in options:
 
1080
                    lines = self.target._reannotate_fulltext(self.source, lines,
 
1081
                        new_version_id, new_version_idx)
 
1082
                elif 'line-delta' in options:
 
1083
                    lines = self.target._reannotate_line_delta(self.source, lines,
 
1084
                        new_version_id, new_version_idx)
 
1085
 
 
1086
            count = count + 1
 
1087
            pb.update("Joining knit", count, len(version_list))
 
1088
 
 
1089
            pos, size = self.target._data.add_record(version_id, digest, lines)
 
1090
            self.target._index.add_version(version_id, options, pos, size, parents)
 
1091
 
 
1092
        for version in mismatched_versions:
 
1093
            n1 = set(self.target.get_parents_with_ghosts(version))
 
1094
            n2 = set(self.source.get_parents_with_ghosts(version))
 
1095
            # write a combined record to our history preserving the current 
 
1096
            # parents as first in the list
 
1097
            new_parents = self.target.get_parents_with_ghosts(version) + list(n2.difference(n1))
 
1098
            self.target.fix_parents(version, new_parents)
 
1099
        pb.clear()
 
1100
        return count
 
1101
 
 
1102
 
 
1103
InterVersionedFile.register_optimiser(InterKnit)