/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

  • Committer: John Arbash Meinel
  • Date: 2006-05-02 20:46:11 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060502204611-02caa5c20fb84ef8
Moved url functions into bzrlib.urlutils

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