/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: Robert Collins
  • Date: 2009-02-20 08:26:50 UTC
  • mto: This revision was merged to the branch mainline in revision 4028.
  • Revision ID: robertc@robertcollins.net-20090220082650-wmzch4en338bymkm
Cherrypick and polish the RemoteSink for streaming push.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Knit versionedfile implementation.
 
18
 
 
19
A knit is a versioned file implementation that supports efficient append only
 
20
updates.
 
21
 
 
22
Knit file layout:
 
23
lifeless: the data file is made up of "delta records".  each delta record has a delta header 
 
24
that contains; (1) a version id, (2) the size of the delta (in lines), and (3)  the digest of 
 
25
the -expanded data- (ie, the delta applied to the parent).  the delta also ends with a 
 
26
end-marker; simply "end VERSION"
 
27
 
 
28
delta can be line or full contents.a
 
29
... the 8's there are the index number of the annotation.
 
30
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
 
31
59,59,3
 
32
8
 
33
8         if ie.executable:
 
34
8             e.set('executable', 'yes')
 
35
130,130,2
 
36
8         if elt.get('executable') == 'yes':
 
37
8             ie.executable = True
 
38
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 
 
39
 
 
40
 
 
41
whats in an index:
 
42
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
 
43
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
 
44
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
 
45
09:33 < lifeless> right
 
46
09:33 < jrydberg> lifeless: the position and size is the range in the data file
 
47
 
 
48
 
 
49
so the index sequence is the dictionary compressed sequence number used
 
50
in the deltas to provide line annotation
 
51
 
 
52
"""
 
53
 
 
54
# TODOS:
 
55
# 10:16 < lifeless> make partial index writes safe
 
56
# 10:16 < lifeless> implement 'knit.check()' like weave.check()
 
57
# 10:17 < lifeless> record known ghosts so we can detect when they are filled in rather than the current 'reweave 
 
58
#                    always' approach.
 
59
# move sha1 out of the content so that join is faster at verifying parents
 
60
# record content length ?
 
61
                  
 
62
 
 
63
from cStringIO import StringIO
 
64
from itertools import izip, chain
 
65
import operator
 
66
import os
 
67
import sys
 
68
 
 
69
from bzrlib.lazy_import import lazy_import
 
70
lazy_import(globals(), """
 
71
from bzrlib import (
 
72
    annotate,
 
73
    debug,
 
74
    diff,
 
75
    graph as _mod_graph,
 
76
    index as _mod_index,
 
77
    lru_cache,
 
78
    pack,
 
79
    progress,
 
80
    trace,
 
81
    tsort,
 
82
    tuned_gzip,
 
83
    )
 
84
""")
 
85
from bzrlib import (
 
86
    errors,
 
87
    osutils,
 
88
    patiencediff,
 
89
    )
 
90
from bzrlib.errors import (
 
91
    FileExists,
 
92
    NoSuchFile,
 
93
    KnitError,
 
94
    InvalidRevisionId,
 
95
    KnitCorrupt,
 
96
    KnitHeaderError,
 
97
    RevisionNotPresent,
 
98
    RevisionAlreadyPresent,
 
99
    SHA1KnitCorrupt,
 
100
    )
 
101
from bzrlib.osutils import (
 
102
    contains_whitespace,
 
103
    contains_linebreaks,
 
104
    sha_string,
 
105
    sha_strings,
 
106
    split_lines,
 
107
    )
 
108
from bzrlib.versionedfile import (
 
109
    AbsentContentFactory,
 
110
    adapter_registry,
 
111
    ConstantMapper,
 
112
    ContentFactory,
 
113
    ChunkedContentFactory,
 
114
    VersionedFile,
 
115
    VersionedFiles,
 
116
    )
 
117
 
 
118
 
 
119
# TODO: Split out code specific to this format into an associated object.
 
120
 
 
121
# TODO: Can we put in some kind of value to check that the index and data
 
122
# files belong together?
 
123
 
 
124
# TODO: accommodate binaries, perhaps by storing a byte count
 
125
 
 
126
# TODO: function to check whole file
 
127
 
 
128
# TODO: atomically append data, then measure backwards from the cursor
 
129
# position after writing to work out where it was located.  we may need to
 
130
# bypass python file buffering.
 
131
 
 
132
DATA_SUFFIX = '.knit'
 
133
INDEX_SUFFIX = '.kndx'
 
134
 
 
135
 
 
136
class KnitAdapter(object):
 
137
    """Base class for knit record adaption."""
 
138
 
 
139
    def __init__(self, basis_vf):
 
140
        """Create an adapter which accesses full texts from basis_vf.
 
141
        
 
142
        :param basis_vf: A versioned file to access basis texts of deltas from.
 
143
            May be None for adapters that do not need to access basis texts.
 
144
        """
 
145
        self._data = KnitVersionedFiles(None, None)
 
146
        self._annotate_factory = KnitAnnotateFactory()
 
147
        self._plain_factory = KnitPlainFactory()
 
148
        self._basis_vf = basis_vf
 
149
 
 
150
 
 
151
class FTAnnotatedToUnannotated(KnitAdapter):
 
152
    """An adapter from FT annotated knits to unannotated ones."""
 
153
 
 
154
    def get_bytes(self, factory):
 
155
        annotated_compressed_bytes = factory._raw_record
 
156
        rec, contents = \
 
157
            self._data._parse_record_unchecked(annotated_compressed_bytes)
 
158
        content = self._annotate_factory.parse_fulltext(contents, rec[1])
 
159
        size, bytes = self._data._record_to_data((rec[1],), rec[3], content.text())
 
160
        return bytes
 
161
 
 
162
 
 
163
class DeltaAnnotatedToUnannotated(KnitAdapter):
 
164
    """An adapter for deltas from annotated to unannotated."""
 
165
 
 
166
    def get_bytes(self, factory):
 
167
        annotated_compressed_bytes = factory._raw_record
 
168
        rec, contents = \
 
169
            self._data._parse_record_unchecked(annotated_compressed_bytes)
 
170
        delta = self._annotate_factory.parse_line_delta(contents, rec[1],
 
171
            plain=True)
 
172
        contents = self._plain_factory.lower_line_delta(delta)
 
173
        size, bytes = self._data._record_to_data((rec[1],), rec[3], contents)
 
174
        return bytes
 
175
 
 
176
 
 
177
class FTAnnotatedToFullText(KnitAdapter):
 
178
    """An adapter from FT annotated knits to unannotated ones."""
 
179
 
 
180
    def get_bytes(self, factory):
 
181
        annotated_compressed_bytes = factory._raw_record
 
182
        rec, contents = \
 
183
            self._data._parse_record_unchecked(annotated_compressed_bytes)
 
184
        content, delta = self._annotate_factory.parse_record(factory.key[-1],
 
185
            contents, factory._build_details, None)
 
186
        return ''.join(content.text())
 
187
 
 
188
 
 
189
class DeltaAnnotatedToFullText(KnitAdapter):
 
190
    """An adapter for deltas from annotated to unannotated."""
 
191
 
 
192
    def get_bytes(self, factory):
 
193
        annotated_compressed_bytes = factory._raw_record
 
194
        rec, contents = \
 
195
            self._data._parse_record_unchecked(annotated_compressed_bytes)
 
196
        delta = self._annotate_factory.parse_line_delta(contents, rec[1],
 
197
            plain=True)
 
198
        compression_parent = factory.parents[0]
 
199
        basis_entry = self._basis_vf.get_record_stream(
 
200
            [compression_parent], 'unordered', True).next()
 
201
        if basis_entry.storage_kind == 'absent':
 
202
            raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
 
203
        basis_chunks = basis_entry.get_bytes_as('chunked')
 
204
        basis_lines = osutils.chunks_to_lines(basis_chunks)
 
205
        # Manually apply the delta because we have one annotated content and
 
206
        # one plain.
 
207
        basis_content = PlainKnitContent(basis_lines, compression_parent)
 
208
        basis_content.apply_delta(delta, rec[1])
 
209
        basis_content._should_strip_eol = factory._build_details[1]
 
210
        return ''.join(basis_content.text())
 
211
 
 
212
 
 
213
class FTPlainToFullText(KnitAdapter):
 
214
    """An adapter from FT plain knits to unannotated ones."""
 
215
 
 
216
    def get_bytes(self, factory):
 
217
        compressed_bytes = factory._raw_record
 
218
        rec, contents = \
 
219
            self._data._parse_record_unchecked(compressed_bytes)
 
220
        content, delta = self._plain_factory.parse_record(factory.key[-1],
 
221
            contents, factory._build_details, None)
 
222
        return ''.join(content.text())
 
223
 
 
224
 
 
225
class DeltaPlainToFullText(KnitAdapter):
 
226
    """An adapter for deltas from annotated to unannotated."""
 
227
 
 
228
    def get_bytes(self, factory):
 
229
        compressed_bytes = factory._raw_record
 
230
        rec, contents = \
 
231
            self._data._parse_record_unchecked(compressed_bytes)
 
232
        delta = self._plain_factory.parse_line_delta(contents, rec[1])
 
233
        compression_parent = factory.parents[0]
 
234
        # XXX: string splitting overhead.
 
235
        basis_entry = self._basis_vf.get_record_stream(
 
236
            [compression_parent], 'unordered', True).next()
 
237
        if basis_entry.storage_kind == 'absent':
 
238
            raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
 
239
        basis_chunks = basis_entry.get_bytes_as('chunked')
 
240
        basis_lines = osutils.chunks_to_lines(basis_chunks)
 
241
        basis_content = PlainKnitContent(basis_lines, compression_parent)
 
242
        # Manually apply the delta because we have one annotated content and
 
243
        # one plain.
 
244
        content, _ = self._plain_factory.parse_record(rec[1], contents,
 
245
            factory._build_details, basis_content)
 
246
        return ''.join(content.text())
 
247
 
 
248
 
 
249
class KnitContentFactory(ContentFactory):
 
250
    """Content factory for streaming from knits.
 
251
    
 
252
    :seealso ContentFactory:
 
253
    """
 
254
 
 
255
    def __init__(self, key, parents, build_details, sha1, raw_record,
 
256
        annotated, knit=None, network_bytes=None):
 
257
        """Create a KnitContentFactory for key.
 
258
        
 
259
        :param key: The key.
 
260
        :param parents: The parents.
 
261
        :param build_details: The build details as returned from
 
262
            get_build_details.
 
263
        :param sha1: The sha1 expected from the full text of this object.
 
264
        :param raw_record: The bytes of the knit data from disk.
 
265
        :param annotated: True if the raw data is annotated.
 
266
        :param network_bytes: None to calculate the network bytes on demand,
 
267
            not-none if they are already known.
 
268
        """
 
269
        ContentFactory.__init__(self)
 
270
        self.sha1 = sha1
 
271
        self.key = key
 
272
        self.parents = parents
 
273
        if build_details[0] == 'line-delta':
 
274
            kind = 'delta'
 
275
        else:
 
276
            kind = 'ft'
 
277
        if annotated:
 
278
            annotated_kind = 'annotated-'
 
279
        else:
 
280
            annotated_kind = ''
 
281
        self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
 
282
        self._raw_record = raw_record
 
283
        self._network_bytes = network_bytes
 
284
        self._build_details = build_details
 
285
        self._knit = knit
 
286
 
 
287
    def _create_network_bytes(self):
 
288
        """Create a fully serialised network version for transmission."""
 
289
        # storage_kind, key, parents, Noeol, raw_record
 
290
        key_bytes = '\x00'.join(self.key)
 
291
        if self.parents is None:
 
292
            parent_bytes = 'None:'
 
293
        else:
 
294
            parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
 
295
        if self._build_details[1]:
 
296
            noeol = 'N'
 
297
        else:
 
298
            noeol = ' '
 
299
        network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
 
300
            parent_bytes, noeol, self._raw_record)
 
301
        self._network_bytes = network_bytes
 
302
 
 
303
    def get_bytes_as(self, storage_kind):
 
304
        if storage_kind == self.storage_kind:
 
305
            if self._network_bytes is None:
 
306
                self._create_network_bytes()
 
307
            return self._network_bytes
 
308
        if self._knit is not None:
 
309
            if storage_kind == 'chunked':
 
310
                return self._knit.get_lines(self.key[0])
 
311
            elif storage_kind == 'fulltext':
 
312
                return self._knit.get_text(self.key[0])
 
313
        raise errors.UnavailableRepresentation(self.key, storage_kind,
 
314
            self.storage_kind)
 
315
 
 
316
 
 
317
class LazyKnitContentFactory(ContentFactory):
 
318
    """A ContentFactory which can either generate full text or a wire form.
 
319
 
 
320
    :seealso ContentFactory:
 
321
    """
 
322
 
 
323
    def __init__(self, key, parents, generator, first):
 
324
        """Create a LazyKnitContentFactory.
 
325
        
 
326
        :param key: The key of the record.
 
327
        :param parents: The parents of the record.
 
328
        :param generator: A _ContentMapGenerator containing the record for this
 
329
            key.
 
330
        :param first: Is this the first content object returned from generator?
 
331
            if it is, its storage kind is knit-delta-closure, otherwise it is
 
332
            knit-delta-closure-ref
 
333
        """
 
334
        self.key = key
 
335
        self.parents = parents
 
336
        self.sha1 = None
 
337
        self._generator = generator
 
338
        self.storage_kind = "knit-delta-closure"
 
339
        if not first:
 
340
            self.storage_kind = self.storage_kind + "-ref"
 
341
        self._first = first
 
342
 
 
343
    def get_bytes_as(self, storage_kind):
 
344
        if storage_kind == self.storage_kind:
 
345
            if self._first:
 
346
                return self._generator._wire_bytes()
 
347
            else:
 
348
                # all the keys etc are contained in the bytes returned in the
 
349
                # first record.
 
350
                return ''
 
351
        if storage_kind in ('chunked', 'fulltext'):
 
352
            chunks = self._generator._get_one_work(self.key).text()
 
353
            if storage_kind == 'chunked':
 
354
                return chunks
 
355
            else:
 
356
                return ''.join(chunks)
 
357
        raise errors.UnavailableRepresentation(self.key, storage_kind,
 
358
            self.storage_kind)
 
359
 
 
360
 
 
361
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
 
362
    """Convert a network record to a iterator over stream records.
 
363
 
 
364
    :param storage_kind: The storage kind of the record.
 
365
        Must be 'knit-delta-closure'.
 
366
    :param bytes: The bytes of the record on the network.
 
367
    """
 
368
    generator = _NetworkContentMapGenerator(bytes, line_end)
 
369
    return generator.get_record_stream()
 
370
 
 
371
 
 
372
def knit_network_to_record(storage_kind, bytes, line_end):
 
373
    """Convert a network record to a record object.
 
374
 
 
375
    :param storage_kind: The storage kind of the record.
 
376
    :param bytes: The bytes of the record on the network.
 
377
    """
 
378
    start = line_end
 
379
    line_end = bytes.find('\n', start)
 
380
    key = tuple(bytes[start:line_end].split('\x00'))
 
381
    start = line_end + 1
 
382
    line_end = bytes.find('\n', start)
 
383
    parent_line = bytes[start:line_end]
 
384
    if parent_line == 'None:':
 
385
        parents = None
 
386
    else:
 
387
        parents = tuple(
 
388
            [tuple(segment.split('\x00')) for segment in parent_line.split('\t')
 
389
             if segment])
 
390
    start = line_end + 1
 
391
    noeol = bytes[start] == 'N'
 
392
    if 'ft' in storage_kind:
 
393
        method = 'fulltext'
 
394
    else:
 
395
        method = 'line-delta'
 
396
    build_details = (method, noeol)
 
397
    start = start + 1
 
398
    raw_record = bytes[start:]
 
399
    annotated = 'annotated' in storage_kind
 
400
    return [KnitContentFactory(key, parents, build_details, None, raw_record,
 
401
        annotated, network_bytes=bytes)]
 
402
 
 
403
 
 
404
class KnitContent(object):
 
405
    """Content of a knit version to which deltas can be applied.
 
406
    
 
407
    This is always stored in memory as a list of lines with \n at the end,
 
408
    plus a flag saying if the final ending is really there or not, because that 
 
409
    corresponds to the on-disk knit representation.
 
410
    """
 
411
 
 
412
    def __init__(self):
 
413
        self._should_strip_eol = False
 
414
 
 
415
    def apply_delta(self, delta, new_version_id):
 
416
        """Apply delta to this object to become new_version_id."""
 
417
        raise NotImplementedError(self.apply_delta)
 
418
 
 
419
    def line_delta_iter(self, new_lines):
 
420
        """Generate line-based delta from this content to new_lines."""
 
421
        new_texts = new_lines.text()
 
422
        old_texts = self.text()
 
423
        s = patiencediff.PatienceSequenceMatcher(None, old_texts, new_texts)
 
424
        for tag, i1, i2, j1, j2 in s.get_opcodes():
 
425
            if tag == 'equal':
 
426
                continue
 
427
            # ofrom, oto, length, data
 
428
            yield i1, i2, j2 - j1, new_lines._lines[j1:j2]
 
429
 
 
430
    def line_delta(self, new_lines):
 
431
        return list(self.line_delta_iter(new_lines))
 
432
 
 
433
    @staticmethod
 
434
    def get_line_delta_blocks(knit_delta, source, target):
 
435
        """Extract SequenceMatcher.get_matching_blocks() from a knit delta"""
 
436
        target_len = len(target)
 
437
        s_pos = 0
 
438
        t_pos = 0
 
439
        for s_begin, s_end, t_len, new_text in knit_delta:
 
440
            true_n = s_begin - s_pos
 
441
            n = true_n
 
442
            if n > 0:
 
443
                # knit deltas do not provide reliable info about whether the
 
444
                # last line of a file matches, due to eol handling.
 
445
                if source[s_pos + n -1] != target[t_pos + n -1]:
 
446
                    n-=1
 
447
                if n > 0:
 
448
                    yield s_pos, t_pos, n
 
449
            t_pos += t_len + true_n
 
450
            s_pos = s_end
 
451
        n = target_len - t_pos
 
452
        if n > 0:
 
453
            if source[s_pos + n -1] != target[t_pos + n -1]:
 
454
                n-=1
 
455
            if n > 0:
 
456
                yield s_pos, t_pos, n
 
457
        yield s_pos + (target_len - t_pos), target_len, 0
 
458
 
 
459
 
 
460
class AnnotatedKnitContent(KnitContent):
 
461
    """Annotated content."""
 
462
 
 
463
    def __init__(self, lines):
 
464
        KnitContent.__init__(self)
 
465
        self._lines = lines
 
466
 
 
467
    def annotate(self):
 
468
        """Return a list of (origin, text) for each content line."""
 
469
        lines = self._lines[:]
 
470
        if self._should_strip_eol:
 
471
            origin, last_line = lines[-1]
 
472
            lines[-1] = (origin, last_line.rstrip('\n'))
 
473
        return lines
 
474
 
 
475
    def apply_delta(self, delta, new_version_id):
 
476
        """Apply delta to this object to become new_version_id."""
 
477
        offset = 0
 
478
        lines = self._lines
 
479
        for start, end, count, delta_lines in delta:
 
480
            lines[offset+start:offset+end] = delta_lines
 
481
            offset = offset + (start - end) + count
 
482
 
 
483
    def text(self):
 
484
        try:
 
485
            lines = [text for origin, text in self._lines]
 
486
        except ValueError, e:
 
487
            # most commonly (only?) caused by the internal form of the knit
 
488
            # missing annotation information because of a bug - see thread
 
489
            # around 20071015
 
490
            raise KnitCorrupt(self,
 
491
                "line in annotated knit missing annotation information: %s"
 
492
                % (e,))
 
493
        if self._should_strip_eol:
 
494
            lines[-1] = lines[-1].rstrip('\n')
 
495
        return lines
 
496
 
 
497
    def copy(self):
 
498
        return AnnotatedKnitContent(self._lines[:])
 
499
 
 
500
 
 
501
class PlainKnitContent(KnitContent):
 
502
    """Unannotated content.
 
503
    
 
504
    When annotate[_iter] is called on this content, the same version is reported
 
505
    for all lines. Generally, annotate[_iter] is not useful on PlainKnitContent
 
506
    objects.
 
507
    """
 
508
 
 
509
    def __init__(self, lines, version_id):
 
510
        KnitContent.__init__(self)
 
511
        self._lines = lines
 
512
        self._version_id = version_id
 
513
 
 
514
    def annotate(self):
 
515
        """Return a list of (origin, text) for each content line."""
 
516
        return [(self._version_id, line) for line in self._lines]
 
517
 
 
518
    def apply_delta(self, delta, new_version_id):
 
519
        """Apply delta to this object to become new_version_id."""
 
520
        offset = 0
 
521
        lines = self._lines
 
522
        for start, end, count, delta_lines in delta:
 
523
            lines[offset+start:offset+end] = delta_lines
 
524
            offset = offset + (start - end) + count
 
525
        self._version_id = new_version_id
 
526
 
 
527
    def copy(self):
 
528
        return PlainKnitContent(self._lines[:], self._version_id)
 
529
 
 
530
    def text(self):
 
531
        lines = self._lines
 
532
        if self._should_strip_eol:
 
533
            lines = lines[:]
 
534
            lines[-1] = lines[-1].rstrip('\n')
 
535
        return lines
 
536
 
 
537
 
 
538
class _KnitFactory(object):
 
539
    """Base class for common Factory functions."""
 
540
 
 
541
    def parse_record(self, version_id, record, record_details,
 
542
                     base_content, copy_base_content=True):
 
543
        """Parse a record into a full content object.
 
544
 
 
545
        :param version_id: The official version id for this content
 
546
        :param record: The data returned by read_records_iter()
 
547
        :param record_details: Details about the record returned by
 
548
            get_build_details
 
549
        :param base_content: If get_build_details returns a compression_parent,
 
550
            you must return a base_content here, else use None
 
551
        :param copy_base_content: When building from the base_content, decide
 
552
            you can either copy it and return a new object, or modify it in
 
553
            place.
 
554
        :return: (content, delta) A Content object and possibly a line-delta,
 
555
            delta may be None
 
556
        """
 
557
        method, noeol = record_details
 
558
        if method == 'line-delta':
 
559
            if copy_base_content:
 
560
                content = base_content.copy()
 
561
            else:
 
562
                content = base_content
 
563
            delta = self.parse_line_delta(record, version_id)
 
564
            content.apply_delta(delta, version_id)
 
565
        else:
 
566
            content = self.parse_fulltext(record, version_id)
 
567
            delta = None
 
568
        content._should_strip_eol = noeol
 
569
        return (content, delta)
 
570
 
 
571
 
 
572
class KnitAnnotateFactory(_KnitFactory):
 
573
    """Factory for creating annotated Content objects."""
 
574
 
 
575
    annotated = True
 
576
 
 
577
    def make(self, lines, version_id):
 
578
        num_lines = len(lines)
 
579
        return AnnotatedKnitContent(zip([version_id] * num_lines, lines))
 
580
 
 
581
    def parse_fulltext(self, content, version_id):
 
582
        """Convert fulltext to internal representation
 
583
 
 
584
        fulltext content is of the format
 
585
        revid(utf8) plaintext\n
 
586
        internal representation is of the format:
 
587
        (revid, plaintext)
 
588
        """
 
589
        # TODO: jam 20070209 The tests expect this to be returned as tuples,
 
590
        #       but the code itself doesn't really depend on that.
 
591
        #       Figure out a way to not require the overhead of turning the
 
592
        #       list back into tuples.
 
593
        lines = [tuple(line.split(' ', 1)) for line in content]
 
594
        return AnnotatedKnitContent(lines)
 
595
 
 
596
    def parse_line_delta_iter(self, lines):
 
597
        return iter(self.parse_line_delta(lines))
 
598
 
 
599
    def parse_line_delta(self, lines, version_id, plain=False):
 
600
        """Convert a line based delta into internal representation.
 
601
 
 
602
        line delta is in the form of:
 
603
        intstart intend intcount
 
604
        1..count lines:
 
605
        revid(utf8) newline\n
 
606
        internal representation is
 
607
        (start, end, count, [1..count tuples (revid, newline)])
 
608
 
 
609
        :param plain: If True, the lines are returned as a plain
 
610
            list without annotations, not as a list of (origin, content) tuples, i.e.
 
611
            (start, end, count, [1..count newline])
 
612
        """
 
613
        result = []
 
614
        lines = iter(lines)
 
615
        next = lines.next
 
616
 
 
617
        cache = {}
 
618
        def cache_and_return(line):
 
619
            origin, text = line.split(' ', 1)
 
620
            return cache.setdefault(origin, origin), text
 
621
 
 
622
        # walk through the lines parsing.
 
623
        # Note that the plain test is explicitly pulled out of the
 
624
        # loop to minimise any performance impact
 
625
        if plain:
 
626
            for header in lines:
 
627
                start, end, count = [int(n) for n in header.split(',')]
 
628
                contents = [next().split(' ', 1)[1] for i in xrange(count)]
 
629
                result.append((start, end, count, contents))
 
630
        else:
 
631
            for header in lines:
 
632
                start, end, count = [int(n) for n in header.split(',')]
 
633
                contents = [tuple(next().split(' ', 1)) for i in xrange(count)]
 
634
                result.append((start, end, count, contents))
 
635
        return result
 
636
 
 
637
    def get_fulltext_content(self, lines):
 
638
        """Extract just the content lines from a fulltext."""
 
639
        return (line.split(' ', 1)[1] for line in lines)
 
640
 
 
641
    def get_linedelta_content(self, lines):
 
642
        """Extract just the content from a line delta.
 
643
 
 
644
        This doesn't return all of the extra information stored in a delta.
 
645
        Only the actual content lines.
 
646
        """
 
647
        lines = iter(lines)
 
648
        next = lines.next
 
649
        for header in lines:
 
650
            header = header.split(',')
 
651
            count = int(header[2])
 
652
            for i in xrange(count):
 
653
                origin, text = next().split(' ', 1)
 
654
                yield text
 
655
 
 
656
    def lower_fulltext(self, content):
 
657
        """convert a fulltext content record into a serializable form.
 
658
 
 
659
        see parse_fulltext which this inverts.
 
660
        """
 
661
        # TODO: jam 20070209 We only do the caching thing to make sure that
 
662
        #       the origin is a valid utf-8 line, eventually we could remove it
 
663
        return ['%s %s' % (o, t) for o, t in content._lines]
 
664
 
 
665
    def lower_line_delta(self, delta):
 
666
        """convert a delta into a serializable form.
 
667
 
 
668
        See parse_line_delta which this inverts.
 
669
        """
 
670
        # TODO: jam 20070209 We only do the caching thing to make sure that
 
671
        #       the origin is a valid utf-8 line, eventually we could remove it
 
672
        out = []
 
673
        for start, end, c, lines in delta:
 
674
            out.append('%d,%d,%d\n' % (start, end, c))
 
675
            out.extend(origin + ' ' + text
 
676
                       for origin, text in lines)
 
677
        return out
 
678
 
 
679
    def annotate(self, knit, key):
 
680
        content = knit._get_content(key)
 
681
        # adjust for the fact that serialised annotations are only key suffixes
 
682
        # for this factory.
 
683
        if type(key) == tuple:
 
684
            prefix = key[:-1]
 
685
            origins = content.annotate()
 
686
            result = []
 
687
            for origin, line in origins:
 
688
                result.append((prefix + (origin,), line))
 
689
            return result
 
690
        else:
 
691
            # XXX: This smells a bit.  Why would key ever be a non-tuple here?
 
692
            # Aren't keys defined to be tuples?  -- spiv 20080618
 
693
            return content.annotate()
 
694
 
 
695
 
 
696
class KnitPlainFactory(_KnitFactory):
 
697
    """Factory for creating plain Content objects."""
 
698
 
 
699
    annotated = False
 
700
 
 
701
    def make(self, lines, version_id):
 
702
        return PlainKnitContent(lines, version_id)
 
703
 
 
704
    def parse_fulltext(self, content, version_id):
 
705
        """This parses an unannotated fulltext.
 
706
 
 
707
        Note that this is not a noop - the internal representation
 
708
        has (versionid, line) - its just a constant versionid.
 
709
        """
 
710
        return self.make(content, version_id)
 
711
 
 
712
    def parse_line_delta_iter(self, lines, version_id):
 
713
        cur = 0
 
714
        num_lines = len(lines)
 
715
        while cur < num_lines:
 
716
            header = lines[cur]
 
717
            cur += 1
 
718
            start, end, c = [int(n) for n in header.split(',')]
 
719
            yield start, end, c, lines[cur:cur+c]
 
720
            cur += c
 
721
 
 
722
    def parse_line_delta(self, lines, version_id):
 
723
        return list(self.parse_line_delta_iter(lines, version_id))
 
724
 
 
725
    def get_fulltext_content(self, lines):
 
726
        """Extract just the content lines from a fulltext."""
 
727
        return iter(lines)
 
728
 
 
729
    def get_linedelta_content(self, lines):
 
730
        """Extract just the content from a line delta.
 
731
 
 
732
        This doesn't return all of the extra information stored in a delta.
 
733
        Only the actual content lines.
 
734
        """
 
735
        lines = iter(lines)
 
736
        next = lines.next
 
737
        for header in lines:
 
738
            header = header.split(',')
 
739
            count = int(header[2])
 
740
            for i in xrange(count):
 
741
                yield next()
 
742
 
 
743
    def lower_fulltext(self, content):
 
744
        return content.text()
 
745
 
 
746
    def lower_line_delta(self, delta):
 
747
        out = []
 
748
        for start, end, c, lines in delta:
 
749
            out.append('%d,%d,%d\n' % (start, end, c))
 
750
            out.extend(lines)
 
751
        return out
 
752
 
 
753
    def annotate(self, knit, key):
 
754
        annotator = _KnitAnnotator(knit)
 
755
        return annotator.annotate(key)
 
756
 
 
757
 
 
758
 
 
759
def make_file_factory(annotated, mapper):
 
760
    """Create a factory for creating a file based KnitVersionedFiles.
 
761
 
 
762
    This is only functional enough to run interface tests, it doesn't try to
 
763
    provide a full pack environment.
 
764
    
 
765
    :param annotated: knit annotations are wanted.
 
766
    :param mapper: The mapper from keys to paths.
 
767
    """
 
768
    def factory(transport):
 
769
        index = _KndxIndex(transport, mapper, lambda:None, lambda:True, lambda:True)
 
770
        access = _KnitKeyAccess(transport, mapper)
 
771
        return KnitVersionedFiles(index, access, annotated=annotated)
 
772
    return factory
 
773
 
 
774
 
 
775
def make_pack_factory(graph, delta, keylength):
 
776
    """Create a factory for creating a pack based VersionedFiles.
 
777
 
 
778
    This is only functional enough to run interface tests, it doesn't try to
 
779
    provide a full pack environment.
 
780
    
 
781
    :param graph: Store a graph.
 
782
    :param delta: Delta compress contents.
 
783
    :param keylength: How long should keys be.
 
784
    """
 
785
    def factory(transport):
 
786
        parents = graph or delta
 
787
        ref_length = 0
 
788
        if graph:
 
789
            ref_length += 1
 
790
        if delta:
 
791
            ref_length += 1
 
792
            max_delta_chain = 200
 
793
        else:
 
794
            max_delta_chain = 0
 
795
        graph_index = _mod_index.InMemoryGraphIndex(reference_lists=ref_length,
 
796
            key_elements=keylength)
 
797
        stream = transport.open_write_stream('newpack')
 
798
        writer = pack.ContainerWriter(stream.write)
 
799
        writer.begin()
 
800
        index = _KnitGraphIndex(graph_index, lambda:True, parents=parents,
 
801
            deltas=delta, add_callback=graph_index.add_nodes)
 
802
        access = _DirectPackAccess({})
 
803
        access.set_writer(writer, graph_index, (transport, 'newpack'))
 
804
        result = KnitVersionedFiles(index, access,
 
805
            max_delta_chain=max_delta_chain)
 
806
        result.stream = stream
 
807
        result.writer = writer
 
808
        return result
 
809
    return factory
 
810
 
 
811
 
 
812
def cleanup_pack_knit(versioned_files):
 
813
    versioned_files.stream.close()
 
814
    versioned_files.writer.end()
 
815
 
 
816
 
 
817
class KnitVersionedFiles(VersionedFiles):
 
818
    """Storage for many versioned files using knit compression.
 
819
 
 
820
    Backend storage is managed by indices and data objects.
 
821
 
 
822
    :ivar _index: A _KnitGraphIndex or similar that can describe the 
 
823
        parents, graph, compression and data location of entries in this 
 
824
        KnitVersionedFiles.  Note that this is only the index for 
 
825
        *this* vfs; if there are fallbacks they must be queried separately.
 
826
    """
 
827
 
 
828
    def __init__(self, index, data_access, max_delta_chain=200,
 
829
                 annotated=False, reload_func=None):
 
830
        """Create a KnitVersionedFiles with index and data_access.
 
831
 
 
832
        :param index: The index for the knit data.
 
833
        :param data_access: The access object to store and retrieve knit
 
834
            records.
 
835
        :param max_delta_chain: The maximum number of deltas to permit during
 
836
            insertion. Set to 0 to prohibit the use of deltas.
 
837
        :param annotated: Set to True to cause annotations to be calculated and
 
838
            stored during insertion.
 
839
        :param reload_func: An function that can be called if we think we need
 
840
            to reload the pack listing and try again. See
 
841
            'bzrlib.repofmt.pack_repo.AggregateIndex' for the signature.
 
842
        """
 
843
        self._index = index
 
844
        self._access = data_access
 
845
        self._max_delta_chain = max_delta_chain
 
846
        if annotated:
 
847
            self._factory = KnitAnnotateFactory()
 
848
        else:
 
849
            self._factory = KnitPlainFactory()
 
850
        self._fallback_vfs = []
 
851
        self._reload_func = reload_func
 
852
 
 
853
    def __repr__(self):
 
854
        return "%s(%r, %r)" % (
 
855
            self.__class__.__name__,
 
856
            self._index,
 
857
            self._access)
 
858
 
 
859
    def add_fallback_versioned_files(self, a_versioned_files):
 
860
        """Add a source of texts for texts not present in this knit.
 
861
 
 
862
        :param a_versioned_files: A VersionedFiles object.
 
863
        """
 
864
        self._fallback_vfs.append(a_versioned_files)
 
865
 
 
866
    def add_lines(self, key, parents, lines, parent_texts=None,
 
867
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
868
        check_content=True):
 
869
        """See VersionedFiles.add_lines()."""
 
870
        self._index._check_write_ok()
 
871
        self._check_add(key, lines, random_id, check_content)
 
872
        if parents is None:
 
873
            # The caller might pass None if there is no graph data, but kndx
 
874
            # indexes can't directly store that, so we give them
 
875
            # an empty tuple instead.
 
876
            parents = ()
 
877
        return self._add(key, lines, parents,
 
878
            parent_texts, left_matching_blocks, nostore_sha, random_id)
 
879
 
 
880
    def _add(self, key, lines, parents, parent_texts,
 
881
        left_matching_blocks, nostore_sha, random_id):
 
882
        """Add a set of lines on top of version specified by parents.
 
883
 
 
884
        Any versions not present will be converted into ghosts.
 
885
        """
 
886
        # first thing, if the content is something we don't need to store, find
 
887
        # that out.
 
888
        line_bytes = ''.join(lines)
 
889
        digest = sha_string(line_bytes)
 
890
        if nostore_sha == digest:
 
891
            raise errors.ExistingContent
 
892
 
 
893
        present_parents = []
 
894
        if parent_texts is None:
 
895
            parent_texts = {}
 
896
        # Do a single query to ascertain parent presence; we only compress
 
897
        # against parents in the same kvf.
 
898
        present_parent_map = self._index.get_parent_map(parents)
 
899
        for parent in parents:
 
900
            if parent in present_parent_map:
 
901
                present_parents.append(parent)
 
902
 
 
903
        # Currently we can only compress against the left most present parent.
 
904
        if (len(present_parents) == 0 or
 
905
            present_parents[0] != parents[0]):
 
906
            delta = False
 
907
        else:
 
908
            # To speed the extract of texts the delta chain is limited
 
909
            # to a fixed number of deltas.  This should minimize both
 
910
            # I/O and the time spend applying deltas.
 
911
            delta = self._check_should_delta(present_parents[0])
 
912
 
 
913
        text_length = len(line_bytes)
 
914
        options = []
 
915
        if lines:
 
916
            if lines[-1][-1] != '\n':
 
917
                # copy the contents of lines.
 
918
                lines = lines[:]
 
919
                options.append('no-eol')
 
920
                lines[-1] = lines[-1] + '\n'
 
921
                line_bytes += '\n'
 
922
 
 
923
        for element in key:
 
924
            if type(element) != str:
 
925
                raise TypeError("key contains non-strings: %r" % (key,))
 
926
        # Knit hunks are still last-element only
 
927
        version_id = key[-1]
 
928
        content = self._factory.make(lines, version_id)
 
929
        if 'no-eol' in options:
 
930
            # Hint to the content object that its text() call should strip the
 
931
            # EOL.
 
932
            content._should_strip_eol = True
 
933
        if delta or (self._factory.annotated and len(present_parents) > 0):
 
934
            # Merge annotations from parent texts if needed.
 
935
            delta_hunks = self._merge_annotations(content, present_parents,
 
936
                parent_texts, delta, self._factory.annotated,
 
937
                left_matching_blocks)
 
938
 
 
939
        if delta:
 
940
            options.append('line-delta')
 
941
            store_lines = self._factory.lower_line_delta(delta_hunks)
 
942
            size, bytes = self._record_to_data(key, digest,
 
943
                store_lines)
 
944
        else:
 
945
            options.append('fulltext')
 
946
            # isinstance is slower and we have no hierarchy.
 
947
            if self._factory.__class__ == KnitPlainFactory:
 
948
                # Use the already joined bytes saving iteration time in
 
949
                # _record_to_data.
 
950
                size, bytes = self._record_to_data(key, digest,
 
951
                    lines, [line_bytes])
 
952
            else:
 
953
                # get mixed annotation + content and feed it into the
 
954
                # serialiser.
 
955
                store_lines = self._factory.lower_fulltext(content)
 
956
                size, bytes = self._record_to_data(key, digest,
 
957
                    store_lines)
 
958
 
 
959
        access_memo = self._access.add_raw_records([(key, size)], bytes)[0]
 
960
        self._index.add_records(
 
961
            ((key, options, access_memo, parents),),
 
962
            random_id=random_id)
 
963
        return digest, text_length, content
 
964
 
 
965
    def annotate(self, key):
 
966
        """See VersionedFiles.annotate."""
 
967
        return self._factory.annotate(self, key)
 
968
 
 
969
    def check(self, progress_bar=None):
 
970
        """See VersionedFiles.check()."""
 
971
        # This doesn't actually test extraction of everything, but that will
 
972
        # impact 'bzr check' substantially, and needs to be integrated with
 
973
        # care. However, it does check for the obvious problem of a delta with
 
974
        # no basis.
 
975
        keys = self._index.keys()
 
976
        parent_map = self.get_parent_map(keys)
 
977
        for key in keys:
 
978
            if self._index.get_method(key) != 'fulltext':
 
979
                compression_parent = parent_map[key][0]
 
980
                if compression_parent not in parent_map:
 
981
                    raise errors.KnitCorrupt(self,
 
982
                        "Missing basis parent %s for %s" % (
 
983
                        compression_parent, key))
 
984
        for fallback_vfs in self._fallback_vfs:
 
985
            fallback_vfs.check()
 
986
 
 
987
    def _check_add(self, key, lines, random_id, check_content):
 
988
        """check that version_id and lines are safe to add."""
 
989
        version_id = key[-1]
 
990
        if contains_whitespace(version_id):
 
991
            raise InvalidRevisionId(version_id, self)
 
992
        self.check_not_reserved_id(version_id)
 
993
        # TODO: If random_id==False and the key is already present, we should
 
994
        # probably check that the existing content is identical to what is
 
995
        # being inserted, and otherwise raise an exception.  This would make
 
996
        # the bundle code simpler.
 
997
        if check_content:
 
998
            self._check_lines_not_unicode(lines)
 
999
            self._check_lines_are_lines(lines)
 
1000
 
 
1001
    def _check_header(self, key, line):
 
1002
        rec = self._split_header(line)
 
1003
        self._check_header_version(rec, key[-1])
 
1004
        return rec
 
1005
 
 
1006
    def _check_header_version(self, rec, version_id):
 
1007
        """Checks the header version on original format knit records.
 
1008
        
 
1009
        These have the last component of the key embedded in the record.
 
1010
        """
 
1011
        if rec[1] != version_id:
 
1012
            raise KnitCorrupt(self,
 
1013
                'unexpected version, wanted %r, got %r' % (version_id, rec[1]))
 
1014
 
 
1015
    def _check_should_delta(self, parent):
 
1016
        """Iterate back through the parent listing, looking for a fulltext.
 
1017
 
 
1018
        This is used when we want to decide whether to add a delta or a new
 
1019
        fulltext. It searches for _max_delta_chain parents. When it finds a
 
1020
        fulltext parent, it sees if the total size of the deltas leading up to
 
1021
        it is large enough to indicate that we want a new full text anyway.
 
1022
 
 
1023
        Return True if we should create a new delta, False if we should use a
 
1024
        full text.
 
1025
        """
 
1026
        delta_size = 0
 
1027
        fulltext_size = None
 
1028
        for count in xrange(self._max_delta_chain):
 
1029
            try:
 
1030
                # Note that this only looks in the index of this particular
 
1031
                # KnitVersionedFiles, not in the fallbacks.  This ensures that
 
1032
                # we won't store a delta spanning physical repository
 
1033
                # boundaries.
 
1034
                build_details = self._index.get_build_details([parent])
 
1035
                parent_details = build_details[parent]
 
1036
            except (RevisionNotPresent, KeyError), e:
 
1037
                # Some basis is not locally present: always fulltext
 
1038
                return False
 
1039
            index_memo, compression_parent, _, _ = parent_details
 
1040
            _, _, size = index_memo
 
1041
            if compression_parent is None:
 
1042
                fulltext_size = size
 
1043
                break
 
1044
            delta_size += size
 
1045
            # We don't explicitly check for presence because this is in an
 
1046
            # inner loop, and if it's missing it'll fail anyhow.
 
1047
            parent = compression_parent
 
1048
        else:
 
1049
            # We couldn't find a fulltext, so we must create a new one
 
1050
            return False
 
1051
        # Simple heuristic - if the total I/O wold be greater as a delta than
 
1052
        # the originally installed fulltext, we create a new fulltext.
 
1053
        return fulltext_size > delta_size
 
1054
 
 
1055
    def _build_details_to_components(self, build_details):
 
1056
        """Convert a build_details tuple to a position tuple."""
 
1057
        # record_details, access_memo, compression_parent
 
1058
        return build_details[3], build_details[0], build_details[1]
 
1059
 
 
1060
    def _get_components_positions(self, keys, allow_missing=False):
 
1061
        """Produce a map of position data for the components of keys.
 
1062
 
 
1063
        This data is intended to be used for retrieving the knit records.
 
1064
 
 
1065
        A dict of key to (record_details, index_memo, next, parents) is
 
1066
        returned.
 
1067
        method is the way referenced data should be applied.
 
1068
        index_memo is the handle to pass to the data access to actually get the
 
1069
            data
 
1070
        next is the build-parent of the version, or None for fulltexts.
 
1071
        parents is the version_ids of the parents of this version
 
1072
 
 
1073
        :param allow_missing: If True do not raise an error on a missing component,
 
1074
            just ignore it.
 
1075
        """
 
1076
        component_data = {}
 
1077
        pending_components = keys
 
1078
        while pending_components:
 
1079
            build_details = self._index.get_build_details(pending_components)
 
1080
            current_components = set(pending_components)
 
1081
            pending_components = set()
 
1082
            for key, details in build_details.iteritems():
 
1083
                (index_memo, compression_parent, parents,
 
1084
                 record_details) = details
 
1085
                method = record_details[0]
 
1086
                if compression_parent is not None:
 
1087
                    pending_components.add(compression_parent)
 
1088
                component_data[key] = self._build_details_to_components(details)
 
1089
            missing = current_components.difference(build_details)
 
1090
            if missing and not allow_missing:
 
1091
                raise errors.RevisionNotPresent(missing.pop(), self)
 
1092
        return component_data
 
1093
       
 
1094
    def _get_content(self, key, parent_texts={}):
 
1095
        """Returns a content object that makes up the specified
 
1096
        version."""
 
1097
        cached_version = parent_texts.get(key, None)
 
1098
        if cached_version is not None:
 
1099
            # Ensure the cache dict is valid.
 
1100
            if not self.get_parent_map([key]):
 
1101
                raise RevisionNotPresent(key, self)
 
1102
            return cached_version
 
1103
        generator = _VFContentMapGenerator(self, [key])
 
1104
        return generator._get_content(key)
 
1105
 
 
1106
    def get_parent_map(self, keys):
 
1107
        """Get a map of the graph parents of keys.
 
1108
 
 
1109
        :param keys: The keys to look up parents for.
 
1110
        :return: A mapping from keys to parents. Absent keys are absent from
 
1111
            the mapping.
 
1112
        """
 
1113
        return self._get_parent_map_with_sources(keys)[0]
 
1114
 
 
1115
    def _get_parent_map_with_sources(self, keys):
 
1116
        """Get a map of the parents of keys.
 
1117
 
 
1118
        :param keys: The keys to look up parents for.
 
1119
        :return: A tuple. The first element is a mapping from keys to parents.
 
1120
            Absent keys are absent from the mapping. The second element is a
 
1121
            list with the locations each key was found in. The first element
 
1122
            is the in-this-knit parents, the second the first fallback source,
 
1123
            and so on.
 
1124
        """
 
1125
        result = {}
 
1126
        sources = [self._index] + self._fallback_vfs
 
1127
        source_results = []
 
1128
        missing = set(keys)
 
1129
        for source in sources:
 
1130
            if not missing:
 
1131
                break
 
1132
            new_result = source.get_parent_map(missing)
 
1133
            source_results.append(new_result)
 
1134
            result.update(new_result)
 
1135
            missing.difference_update(set(new_result))
 
1136
        return result, source_results
 
1137
 
 
1138
    def _get_record_map(self, keys, allow_missing=False):
 
1139
        """Produce a dictionary of knit records.
 
1140
        
 
1141
        :return: {key:(record, record_details, digest, next)}
 
1142
            record
 
1143
                data returned from read_records (a KnitContentobject)
 
1144
            record_details
 
1145
                opaque information to pass to parse_record
 
1146
            digest
 
1147
                SHA1 digest of the full text after all steps are done
 
1148
            next
 
1149
                build-parent of the version, i.e. the leftmost ancestor.
 
1150
                Will be None if the record is not a delta.
 
1151
        :param keys: The keys to build a map for
 
1152
        :param allow_missing: If some records are missing, rather than 
 
1153
            error, just return the data that could be generated.
 
1154
        """
 
1155
        raw_map = self._get_record_map_unparsed(keys,
 
1156
            allow_missing=allow_missing)
 
1157
        return self._raw_map_to_record_map(raw_map)
 
1158
 
 
1159
    def _raw_map_to_record_map(self, raw_map):
 
1160
        """Parse the contents of _get_record_map_unparsed.
 
1161
        
 
1162
        :return: see _get_record_map.
 
1163
        """
 
1164
        result = {}
 
1165
        for key in raw_map:
 
1166
            data, record_details, next = raw_map[key]
 
1167
            content, digest = self._parse_record(key[-1], data)
 
1168
            result[key] = content, record_details, digest, next
 
1169
        return result
 
1170
 
 
1171
    def _get_record_map_unparsed(self, keys, allow_missing=False):
 
1172
        """Get the raw data for reconstructing keys without parsing it.
 
1173
        
 
1174
        :return: A dict suitable for parsing via _raw_map_to_record_map.
 
1175
            key-> raw_bytes, (method, noeol), compression_parent
 
1176
        """
 
1177
        # This retries the whole request if anything fails. Potentially we
 
1178
        # could be a bit more selective. We could track the keys whose records
 
1179
        # we have successfully found, and then only request the new records
 
1180
        # from there. However, _get_components_positions grabs the whole build
 
1181
        # chain, which means we'll likely try to grab the same records again
 
1182
        # anyway. Also, can the build chains change as part of a pack
 
1183
        # operation? We wouldn't want to end up with a broken chain.
 
1184
        while True:
 
1185
            try:
 
1186
                position_map = self._get_components_positions(keys,
 
1187
                    allow_missing=allow_missing)
 
1188
                # key = component_id, r = record_details, i_m = index_memo,
 
1189
                # n = next
 
1190
                records = [(key, i_m) for key, (r, i_m, n)
 
1191
                                       in position_map.iteritems()]
 
1192
                raw_record_map = {}
 
1193
                for key, data in self._read_records_iter_unchecked(records):
 
1194
                    (record_details, index_memo, next) = position_map[key]
 
1195
                    raw_record_map[key] = data, record_details, next
 
1196
                return raw_record_map
 
1197
            except errors.RetryWithNewPacks, e:
 
1198
                self._access.reload_or_raise(e)
 
1199
 
 
1200
    def _split_by_prefix(self, keys):
 
1201
        """For the given keys, split them up based on their prefix.
 
1202
 
 
1203
        To keep memory pressure somewhat under control, split the
 
1204
        requests back into per-file-id requests, otherwise "bzr co"
 
1205
        extracts the full tree into memory before writing it to disk.
 
1206
        This should be revisited if _get_content_maps() can ever cross
 
1207
        file-id boundaries.
 
1208
 
 
1209
        :param keys: An iterable of key tuples
 
1210
        :return: A dict of {prefix: [key_list]}
 
1211
        """
 
1212
        split_by_prefix = {}
 
1213
        for key in keys:
 
1214
            if len(key) == 1:
 
1215
                split_by_prefix.setdefault('', []).append(key)
 
1216
            else:
 
1217
                split_by_prefix.setdefault(key[0], []).append(key)
 
1218
        return split_by_prefix
 
1219
 
 
1220
    def get_record_stream(self, keys, ordering, include_delta_closure):
 
1221
        """Get a stream of records for keys.
 
1222
 
 
1223
        :param keys: The keys to include.
 
1224
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
1225
            sorted stream has compression parents strictly before their
 
1226
            children.
 
1227
        :param include_delta_closure: If True then the closure across any
 
1228
            compression parents will be included (in the opaque data).
 
1229
        :return: An iterator of ContentFactory objects, each of which is only
 
1230
            valid until the iterator is advanced.
 
1231
        """
 
1232
        # keys might be a generator
 
1233
        keys = set(keys)
 
1234
        if not keys:
 
1235
            return
 
1236
        if not self._index.has_graph:
 
1237
            # Cannot topological order when no graph has been stored.
 
1238
            ordering = 'unordered'
 
1239
 
 
1240
        remaining_keys = keys
 
1241
        while True:
 
1242
            try:
 
1243
                keys = set(remaining_keys)
 
1244
                for content_factory in self._get_remaining_record_stream(keys,
 
1245
                                            ordering, include_delta_closure):
 
1246
                    remaining_keys.discard(content_factory.key)
 
1247
                    yield content_factory
 
1248
                return
 
1249
            except errors.RetryWithNewPacks, e:
 
1250
                self._access.reload_or_raise(e)
 
1251
 
 
1252
    def _get_remaining_record_stream(self, keys, ordering,
 
1253
                                     include_delta_closure):
 
1254
        """This function is the 'retry' portion for get_record_stream."""
 
1255
        if include_delta_closure:
 
1256
            positions = self._get_components_positions(keys, allow_missing=True)
 
1257
        else:
 
1258
            build_details = self._index.get_build_details(keys)
 
1259
            # map from key to
 
1260
            # (record_details, access_memo, compression_parent_key)
 
1261
            positions = dict((key, self._build_details_to_components(details))
 
1262
                for key, details in build_details.iteritems())
 
1263
        absent_keys = keys.difference(set(positions))
 
1264
        # There may be more absent keys : if we're missing the basis component
 
1265
        # and are trying to include the delta closure.
 
1266
        # XXX: We should not ever need to examine remote sources because we do
 
1267
        # not permit deltas across versioned files boundaries.
 
1268
        if include_delta_closure:
 
1269
            needed_from_fallback = set()
 
1270
            # Build up reconstructable_keys dict.  key:True in this dict means
 
1271
            # the key can be reconstructed.
 
1272
            reconstructable_keys = {}
 
1273
            for key in keys:
 
1274
                # the delta chain
 
1275
                try:
 
1276
                    chain = [key, positions[key][2]]
 
1277
                except KeyError:
 
1278
                    needed_from_fallback.add(key)
 
1279
                    continue
 
1280
                result = True
 
1281
                while chain[-1] is not None:
 
1282
                    if chain[-1] in reconstructable_keys:
 
1283
                        result = reconstructable_keys[chain[-1]]
 
1284
                        break
 
1285
                    else:
 
1286
                        try:
 
1287
                            chain.append(positions[chain[-1]][2])
 
1288
                        except KeyError:
 
1289
                            # missing basis component
 
1290
                            needed_from_fallback.add(chain[-1])
 
1291
                            result = True
 
1292
                            break
 
1293
                for chain_key in chain[:-1]:
 
1294
                    reconstructable_keys[chain_key] = result
 
1295
                if not result:
 
1296
                    needed_from_fallback.add(key)
 
1297
        # Double index lookups here : need a unified api ?
 
1298
        global_map, parent_maps = self._get_parent_map_with_sources(keys)
 
1299
        if ordering == 'topological':
 
1300
            # Global topological sort
 
1301
            present_keys = tsort.topo_sort(global_map)
 
1302
            # Now group by source:
 
1303
            source_keys = []
 
1304
            current_source = None
 
1305
            for key in present_keys:
 
1306
                for parent_map in parent_maps:
 
1307
                    if key in parent_map:
 
1308
                        key_source = parent_map
 
1309
                        break
 
1310
                if current_source is not key_source:
 
1311
                    source_keys.append((key_source, []))
 
1312
                    current_source = key_source
 
1313
                source_keys[-1][1].append(key)
 
1314
        else:
 
1315
            if ordering != 'unordered':
 
1316
                raise AssertionError('valid values for ordering are:'
 
1317
                    ' "unordered" or "topological" not: %r'
 
1318
                    % (ordering,))
 
1319
            # Just group by source; remote sources first.
 
1320
            present_keys = []
 
1321
            source_keys = []
 
1322
            for parent_map in reversed(parent_maps):
 
1323
                source_keys.append((parent_map, []))
 
1324
                for key in parent_map:
 
1325
                    present_keys.append(key)
 
1326
                    source_keys[-1][1].append(key)
 
1327
            # We have been requested to return these records in an order that
 
1328
            # suits us. So we ask the index to give us an optimally sorted
 
1329
            # order.
 
1330
            for source, sub_keys in source_keys:
 
1331
                if source is parent_maps[0]:
 
1332
                    # Only sort the keys for this VF
 
1333
                    self._index._sort_keys_by_io(sub_keys, positions)
 
1334
        absent_keys = keys - set(global_map)
 
1335
        for key in absent_keys:
 
1336
            yield AbsentContentFactory(key)
 
1337
        # restrict our view to the keys we can answer.
 
1338
        # XXX: Memory: TODO: batch data here to cap buffered data at (say) 1MB.
 
1339
        # XXX: At that point we need to consider the impact of double reads by
 
1340
        # utilising components multiple times.
 
1341
        if include_delta_closure:
 
1342
            # XXX: get_content_maps performs its own index queries; allow state
 
1343
            # to be passed in.
 
1344
            non_local_keys = needed_from_fallback - absent_keys
 
1345
            prefix_split_keys = self._split_by_prefix(present_keys)
 
1346
            prefix_split_non_local_keys = self._split_by_prefix(non_local_keys)
 
1347
            for prefix, keys in prefix_split_keys.iteritems():
 
1348
                non_local = prefix_split_non_local_keys.get(prefix, [])
 
1349
                non_local = set(non_local)
 
1350
                generator = _VFContentMapGenerator(self, keys, non_local,
 
1351
                    global_map)
 
1352
                for record in generator.get_record_stream():
 
1353
                    yield record
 
1354
        else:
 
1355
            for source, keys in source_keys:
 
1356
                if source is parent_maps[0]:
 
1357
                    # this KnitVersionedFiles
 
1358
                    records = [(key, positions[key][1]) for key in keys]
 
1359
                    for key, raw_data, sha1 in self._read_records_iter_raw(records):
 
1360
                        (record_details, index_memo, _) = positions[key]
 
1361
                        yield KnitContentFactory(key, global_map[key],
 
1362
                            record_details, sha1, raw_data, self._factory.annotated, None)
 
1363
                else:
 
1364
                    vf = self._fallback_vfs[parent_maps.index(source) - 1]
 
1365
                    for record in vf.get_record_stream(keys, ordering,
 
1366
                        include_delta_closure):
 
1367
                        yield record
 
1368
 
 
1369
    def get_sha1s(self, keys):
 
1370
        """See VersionedFiles.get_sha1s()."""
 
1371
        missing = set(keys)
 
1372
        record_map = self._get_record_map(missing, allow_missing=True)
 
1373
        result = {}
 
1374
        for key, details in record_map.iteritems():
 
1375
            if key not in missing:
 
1376
                continue
 
1377
            # record entry 2 is the 'digest'.
 
1378
            result[key] = details[2]
 
1379
        missing.difference_update(set(result))
 
1380
        for source in self._fallback_vfs:
 
1381
            if not missing:
 
1382
                break
 
1383
            new_result = source.get_sha1s(missing)
 
1384
            result.update(new_result)
 
1385
            missing.difference_update(set(new_result))
 
1386
        return result
 
1387
 
 
1388
    def insert_record_stream(self, stream):
 
1389
        """Insert a record stream into this container.
 
1390
 
 
1391
        :param stream: A stream of records to insert. 
 
1392
        :return: None
 
1393
        :seealso VersionedFiles.get_record_stream:
 
1394
        """
 
1395
        def get_adapter(adapter_key):
 
1396
            try:
 
1397
                return adapters[adapter_key]
 
1398
            except KeyError:
 
1399
                adapter_factory = adapter_registry.get(adapter_key)
 
1400
                adapter = adapter_factory(self)
 
1401
                adapters[adapter_key] = adapter
 
1402
                return adapter
 
1403
        delta_types = set()
 
1404
        if self._factory.annotated:
 
1405
            # self is annotated, we need annotated knits to use directly.
 
1406
            annotated = "annotated-"
 
1407
            convertibles = []
 
1408
        else:
 
1409
            # self is not annotated, but we can strip annotations cheaply.
 
1410
            annotated = ""
 
1411
            convertibles = set(["knit-annotated-ft-gz"])
 
1412
            if self._max_delta_chain:
 
1413
                delta_types.add("knit-annotated-delta-gz")
 
1414
                convertibles.add("knit-annotated-delta-gz")
 
1415
        # The set of types we can cheaply adapt without needing basis texts.
 
1416
        native_types = set()
 
1417
        if self._max_delta_chain:
 
1418
            native_types.add("knit-%sdelta-gz" % annotated)
 
1419
            delta_types.add("knit-%sdelta-gz" % annotated)
 
1420
        native_types.add("knit-%sft-gz" % annotated)
 
1421
        knit_types = native_types.union(convertibles)
 
1422
        adapters = {}
 
1423
        # Buffer all index entries that we can't add immediately because their
 
1424
        # basis parent is missing. We don't buffer all because generating
 
1425
        # annotations may require access to some of the new records. However we
 
1426
        # can't generate annotations from new deltas until their basis parent
 
1427
        # is present anyway, so we get away with not needing an index that
 
1428
        # includes the new keys.
 
1429
        #
 
1430
        # See <http://launchpad.net/bugs/300177> about ordering of compression
 
1431
        # parents in the records - to be conservative, we insist that all
 
1432
        # parents must be present to avoid expanding to a fulltext.
 
1433
        #
 
1434
        # key = basis_parent, value = index entry to add
 
1435
        buffered_index_entries = {}
 
1436
        for record in stream:
 
1437
            parents = record.parents
 
1438
            if record.storage_kind in delta_types:
 
1439
                # TODO: eventually the record itself should track
 
1440
                #       compression_parent
 
1441
                compression_parent = parents[0]
 
1442
            else:
 
1443
                compression_parent = None
 
1444
            # Raise an error when a record is missing.
 
1445
            if record.storage_kind == 'absent':
 
1446
                raise RevisionNotPresent([record.key], self)
 
1447
            elif ((record.storage_kind in knit_types)
 
1448
                  and (compression_parent is None
 
1449
                       or not self._fallback_vfs
 
1450
                       or self._index.has_key(compression_parent)
 
1451
                       or not self.has_key(compression_parent))):
 
1452
                # we can insert the knit record literally if either it has no
 
1453
                # compression parent OR we already have its basis in this kvf
 
1454
                # OR the basis is not present even in the fallbacks.  In the
 
1455
                # last case it will either turn up later in the stream and all
 
1456
                # will be well, or it won't turn up at all and we'll raise an
 
1457
                # error at the end.
 
1458
                #
 
1459
                # TODO: self.has_key is somewhat redundant with
 
1460
                # self._index.has_key; we really want something that directly
 
1461
                # asks if it's only present in the fallbacks. -- mbp 20081119
 
1462
                if record.storage_kind not in native_types:
 
1463
                    try:
 
1464
                        adapter_key = (record.storage_kind, "knit-delta-gz")
 
1465
                        adapter = get_adapter(adapter_key)
 
1466
                    except KeyError:
 
1467
                        adapter_key = (record.storage_kind, "knit-ft-gz")
 
1468
                        adapter = get_adapter(adapter_key)
 
1469
                    bytes = adapter.get_bytes(record)
 
1470
                else:
 
1471
                    # It's a knit record, it has a _raw_record field (even if
 
1472
                    # it was reconstituted from a network stream).
 
1473
                    bytes = record._raw_record
 
1474
                options = [record._build_details[0]]
 
1475
                if record._build_details[1]:
 
1476
                    options.append('no-eol')
 
1477
                # Just blat it across.
 
1478
                # Note: This does end up adding data on duplicate keys. As
 
1479
                # modern repositories use atomic insertions this should not
 
1480
                # lead to excessive growth in the event of interrupted fetches.
 
1481
                # 'knit' repositories may suffer excessive growth, but as a
 
1482
                # deprecated format this is tolerable. It can be fixed if
 
1483
                # needed by in the kndx index support raising on a duplicate
 
1484
                # add with identical parents and options.
 
1485
                access_memo = self._access.add_raw_records(
 
1486
                    [(record.key, len(bytes))], bytes)[0]
 
1487
                index_entry = (record.key, options, access_memo, parents)
 
1488
                buffered = False
 
1489
                if 'fulltext' not in options:
 
1490
                    # Not a fulltext, so we need to make sure the compression
 
1491
                    # parent will also be present.
 
1492
                    # Note that pack backed knits don't need to buffer here
 
1493
                    # because they buffer all writes to the transaction level,
 
1494
                    # but we don't expose that difference at the index level. If
 
1495
                    # the query here has sufficient cost to show up in
 
1496
                    # profiling we should do that.
 
1497
                    #
 
1498
                    # They're required to be physically in this
 
1499
                    # KnitVersionedFiles, not in a fallback.
 
1500
                    if not self._index.has_key(compression_parent):
 
1501
                        pending = buffered_index_entries.setdefault(
 
1502
                            compression_parent, [])
 
1503
                        pending.append(index_entry)
 
1504
                        buffered = True
 
1505
                if not buffered:
 
1506
                    self._index.add_records([index_entry])
 
1507
            elif record.storage_kind == 'chunked':
 
1508
                self.add_lines(record.key, parents,
 
1509
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
 
1510
            else:
 
1511
                # Not suitable for direct insertion as a
 
1512
                # delta, either because it's not the right format, or this
 
1513
                # KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
 
1514
                # 0) or because it depends on a base only present in the
 
1515
                # fallback kvfs.
 
1516
                try:
 
1517
                    # Try getting a fulltext directly from the record.
 
1518
                    bytes = record.get_bytes_as('fulltext')
 
1519
                except errors.UnavailableRepresentation:
 
1520
                    adapter_key = record.storage_kind, 'fulltext'
 
1521
                    adapter = get_adapter(adapter_key)
 
1522
                    bytes = adapter.get_bytes(record)
 
1523
                lines = split_lines(bytes)
 
1524
                try:
 
1525
                    self.add_lines(record.key, parents, lines)
 
1526
                except errors.RevisionAlreadyPresent:
 
1527
                    pass
 
1528
            # Add any records whose basis parent is now available.
 
1529
            added_keys = [record.key]
 
1530
            while added_keys:
 
1531
                key = added_keys.pop(0)
 
1532
                if key in buffered_index_entries:
 
1533
                    index_entries = buffered_index_entries[key]
 
1534
                    self._index.add_records(index_entries)
 
1535
                    added_keys.extend(
 
1536
                        [index_entry[0] for index_entry in index_entries])
 
1537
                    del buffered_index_entries[key]
 
1538
        # If there were any deltas which had a missing basis parent, error.
 
1539
        if buffered_index_entries:
 
1540
            from pprint import pformat
 
1541
            raise errors.BzrCheckError(
 
1542
                "record_stream refers to compression parents not in %r:\n%s"
 
1543
                % (self, pformat(sorted(buffered_index_entries.keys()))))
 
1544
 
 
1545
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
 
1546
        """Iterate over the lines in the versioned files from keys.
 
1547
 
 
1548
        This may return lines from other keys. Each item the returned
 
1549
        iterator yields is a tuple of a line and a text version that that line
 
1550
        is present in (not introduced in).
 
1551
 
 
1552
        Ordering of results is in whatever order is most suitable for the
 
1553
        underlying storage format.
 
1554
 
 
1555
        If a progress bar is supplied, it may be used to indicate progress.
 
1556
        The caller is responsible for cleaning up progress bars (because this
 
1557
        is an iterator).
 
1558
 
 
1559
        NOTES:
 
1560
         * Lines are normalised by the underlying store: they will all have \\n
 
1561
           terminators.
 
1562
         * Lines are returned in arbitrary order.
 
1563
         * If a requested key did not change any lines (or didn't have any
 
1564
           lines), it may not be mentioned at all in the result.
 
1565
 
 
1566
        :return: An iterator over (line, key).
 
1567
        """
 
1568
        if pb is None:
 
1569
            pb = progress.DummyProgress()
 
1570
        keys = set(keys)
 
1571
        total = len(keys)
 
1572
        done = False
 
1573
        while not done:
 
1574
            try:
 
1575
                # we don't care about inclusions, the caller cares.
 
1576
                # but we need to setup a list of records to visit.
 
1577
                # we need key, position, length
 
1578
                key_records = []
 
1579
                build_details = self._index.get_build_details(keys)
 
1580
                for key, details in build_details.iteritems():
 
1581
                    if key in keys:
 
1582
                        key_records.append((key, details[0]))
 
1583
                records_iter = enumerate(self._read_records_iter(key_records))
 
1584
                for (key_idx, (key, data, sha_value)) in records_iter:
 
1585
                    pb.update('Walking content.', key_idx, total)
 
1586
                    compression_parent = build_details[key][1]
 
1587
                    if compression_parent is None:
 
1588
                        # fulltext
 
1589
                        line_iterator = self._factory.get_fulltext_content(data)
 
1590
                    else:
 
1591
                        # Delta 
 
1592
                        line_iterator = self._factory.get_linedelta_content(data)
 
1593
                    # Now that we are yielding the data for this key, remove it
 
1594
                    # from the list
 
1595
                    keys.remove(key)
 
1596
                    # XXX: It might be more efficient to yield (key,
 
1597
                    # line_iterator) in the future. However for now, this is a
 
1598
                    # simpler change to integrate into the rest of the
 
1599
                    # codebase. RBC 20071110
 
1600
                    for line in line_iterator:
 
1601
                        yield line, key
 
1602
                done = True
 
1603
            except errors.RetryWithNewPacks, e:
 
1604
                self._access.reload_or_raise(e)
 
1605
        # If there are still keys we've not yet found, we look in the fallback
 
1606
        # vfs, and hope to find them there.  Note that if the keys are found
 
1607
        # but had no changes or no content, the fallback may not return
 
1608
        # anything.  
 
1609
        if keys and not self._fallback_vfs:
 
1610
            # XXX: strictly the second parameter is meant to be the file id
 
1611
            # but it's not easily accessible here.
 
1612
            raise RevisionNotPresent(keys, repr(self))
 
1613
        for source in self._fallback_vfs:
 
1614
            if not keys:
 
1615
                break
 
1616
            source_keys = set()
 
1617
            for line, key in source.iter_lines_added_or_present_in_keys(keys):
 
1618
                source_keys.add(key)
 
1619
                yield line, key
 
1620
            keys.difference_update(source_keys)
 
1621
        pb.update('Walking content.', total, total)
 
1622
 
 
1623
    def _make_line_delta(self, delta_seq, new_content):
 
1624
        """Generate a line delta from delta_seq and new_content."""
 
1625
        diff_hunks = []
 
1626
        for op in delta_seq.get_opcodes():
 
1627
            if op[0] == 'equal':
 
1628
                continue
 
1629
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
 
1630
        return diff_hunks
 
1631
 
 
1632
    def _merge_annotations(self, content, parents, parent_texts={},
 
1633
                           delta=None, annotated=None,
 
1634
                           left_matching_blocks=None):
 
1635
        """Merge annotations for content and generate deltas.
 
1636
        
 
1637
        This is done by comparing the annotations based on changes to the text
 
1638
        and generating a delta on the resulting full texts. If annotations are
 
1639
        not being created then a simple delta is created.
 
1640
        """
 
1641
        if left_matching_blocks is not None:
 
1642
            delta_seq = diff._PrematchedMatcher(left_matching_blocks)
 
1643
        else:
 
1644
            delta_seq = None
 
1645
        if annotated:
 
1646
            for parent_key in parents:
 
1647
                merge_content = self._get_content(parent_key, parent_texts)
 
1648
                if (parent_key == parents[0] and delta_seq is not None):
 
1649
                    seq = delta_seq
 
1650
                else:
 
1651
                    seq = patiencediff.PatienceSequenceMatcher(
 
1652
                        None, merge_content.text(), content.text())
 
1653
                for i, j, n in seq.get_matching_blocks():
 
1654
                    if n == 0:
 
1655
                        continue
 
1656
                    # this copies (origin, text) pairs across to the new
 
1657
                    # content for any line that matches the last-checked
 
1658
                    # parent.
 
1659
                    content._lines[j:j+n] = merge_content._lines[i:i+n]
 
1660
            # XXX: Robert says the following block is a workaround for a
 
1661
            # now-fixed bug and it can probably be deleted. -- mbp 20080618
 
1662
            if content._lines and content._lines[-1][1][-1] != '\n':
 
1663
                # The copied annotation was from a line without a trailing EOL,
 
1664
                # reinstate one for the content object, to ensure correct
 
1665
                # serialization.
 
1666
                line = content._lines[-1][1] + '\n'
 
1667
                content._lines[-1] = (content._lines[-1][0], line)
 
1668
        if delta:
 
1669
            if delta_seq is None:
 
1670
                reference_content = self._get_content(parents[0], parent_texts)
 
1671
                new_texts = content.text()
 
1672
                old_texts = reference_content.text()
 
1673
                delta_seq = patiencediff.PatienceSequenceMatcher(
 
1674
                                                 None, old_texts, new_texts)
 
1675
            return self._make_line_delta(delta_seq, content)
 
1676
 
 
1677
    def _parse_record(self, version_id, data):
 
1678
        """Parse an original format knit record.
 
1679
 
 
1680
        These have the last element of the key only present in the stored data.
 
1681
        """
 
1682
        rec, record_contents = self._parse_record_unchecked(data)
 
1683
        self._check_header_version(rec, version_id)
 
1684
        return record_contents, rec[3]
 
1685
 
 
1686
    def _parse_record_header(self, key, raw_data):
 
1687
        """Parse a record header for consistency.
 
1688
 
 
1689
        :return: the header and the decompressor stream.
 
1690
                 as (stream, header_record)
 
1691
        """
 
1692
        df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
 
1693
        try:
 
1694
            # Current serialise
 
1695
            rec = self._check_header(key, df.readline())
 
1696
        except Exception, e:
 
1697
            raise KnitCorrupt(self,
 
1698
                              "While reading {%s} got %s(%s)"
 
1699
                              % (key, e.__class__.__name__, str(e)))
 
1700
        return df, rec
 
1701
 
 
1702
    def _parse_record_unchecked(self, data):
 
1703
        # profiling notes:
 
1704
        # 4168 calls in 2880 217 internal
 
1705
        # 4168 calls to _parse_record_header in 2121
 
1706
        # 4168 calls to readlines in 330
 
1707
        df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(data))
 
1708
        try:
 
1709
            record_contents = df.readlines()
 
1710
        except Exception, e:
 
1711
            raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
 
1712
                (data, e.__class__.__name__, str(e)))
 
1713
        header = record_contents.pop(0)
 
1714
        rec = self._split_header(header)
 
1715
        last_line = record_contents.pop()
 
1716
        if len(record_contents) != int(rec[2]):
 
1717
            raise KnitCorrupt(self,
 
1718
                              'incorrect number of lines %s != %s'
 
1719
                              ' for version {%s} %s'
 
1720
                              % (len(record_contents), int(rec[2]),
 
1721
                                 rec[1], record_contents))
 
1722
        if last_line != 'end %s\n' % rec[1]:
 
1723
            raise KnitCorrupt(self,
 
1724
                              'unexpected version end line %r, wanted %r' 
 
1725
                              % (last_line, rec[1]))
 
1726
        df.close()
 
1727
        return rec, record_contents
 
1728
 
 
1729
    def _read_records_iter(self, records):
 
1730
        """Read text records from data file and yield result.
 
1731
 
 
1732
        The result will be returned in whatever is the fastest to read.
 
1733
        Not by the order requested. Also, multiple requests for the same
 
1734
        record will only yield 1 response.
 
1735
        :param records: A list of (key, access_memo) entries
 
1736
        :return: Yields (key, contents, digest) in the order
 
1737
                 read, not the order requested
 
1738
        """
 
1739
        if not records:
 
1740
            return
 
1741
 
 
1742
        # XXX: This smells wrong, IO may not be getting ordered right.
 
1743
        needed_records = sorted(set(records), key=operator.itemgetter(1))
 
1744
        if not needed_records:
 
1745
            return
 
1746
 
 
1747
        # The transport optimizes the fetching as well 
 
1748
        # (ie, reads continuous ranges.)
 
1749
        raw_data = self._access.get_raw_records(
 
1750
            [index_memo for key, index_memo in needed_records])
 
1751
 
 
1752
        for (key, index_memo), data in \
 
1753
                izip(iter(needed_records), raw_data):
 
1754
            content, digest = self._parse_record(key[-1], data)
 
1755
            yield key, content, digest
 
1756
 
 
1757
    def _read_records_iter_raw(self, records):
 
1758
        """Read text records from data file and yield raw data.
 
1759
 
 
1760
        This unpacks enough of the text record to validate the id is
 
1761
        as expected but thats all.
 
1762
 
 
1763
        Each item the iterator yields is (key, bytes,
 
1764
            expected_sha1_of_full_text).
 
1765
        """
 
1766
        for key, data in self._read_records_iter_unchecked(records):
 
1767
            # validate the header (note that we can only use the suffix in
 
1768
            # current knit records).
 
1769
            df, rec = self._parse_record_header(key, data)
 
1770
            df.close()
 
1771
            yield key, data, rec[3]
 
1772
 
 
1773
    def _read_records_iter_unchecked(self, records):
 
1774
        """Read text records from data file and yield raw data.
 
1775
 
 
1776
        No validation is done.
 
1777
 
 
1778
        Yields tuples of (key, data).
 
1779
        """
 
1780
        # setup an iterator of the external records:
 
1781
        # uses readv so nice and fast we hope.
 
1782
        if len(records):
 
1783
            # grab the disk data needed.
 
1784
            needed_offsets = [index_memo for key, index_memo
 
1785
                                           in records]
 
1786
            raw_records = self._access.get_raw_records(needed_offsets)
 
1787
 
 
1788
        for key, index_memo in records:
 
1789
            data = raw_records.next()
 
1790
            yield key, data
 
1791
 
 
1792
    def _record_to_data(self, key, digest, lines, dense_lines=None):
 
1793
        """Convert key, digest, lines into a raw data block.
 
1794
        
 
1795
        :param key: The key of the record. Currently keys are always serialised
 
1796
            using just the trailing component.
 
1797
        :param dense_lines: The bytes of lines but in a denser form. For
 
1798
            instance, if lines is a list of 1000 bytestrings each ending in \n,
 
1799
            dense_lines may be a list with one line in it, containing all the
 
1800
            1000's lines and their \n's. Using dense_lines if it is already
 
1801
            known is a win because the string join to create bytes in this
 
1802
            function spends less time resizing the final string.
 
1803
        :return: (len, a StringIO instance with the raw data ready to read.)
 
1804
        """
 
1805
        # Note: using a string copy here increases memory pressure with e.g.
 
1806
        # ISO's, but it is about 3 seconds faster on a 1.2Ghz intel machine
 
1807
        # when doing the initial commit of a mozilla tree. RBC 20070921
 
1808
        bytes = ''.join(chain(
 
1809
            ["version %s %d %s\n" % (key[-1],
 
1810
                                     len(lines),
 
1811
                                     digest)],
 
1812
            dense_lines or lines,
 
1813
            ["end %s\n" % key[-1]]))
 
1814
        if type(bytes) != str:
 
1815
            raise AssertionError(
 
1816
                'data must be plain bytes was %s' % type(bytes))
 
1817
        if lines and lines[-1][-1] != '\n':
 
1818
            raise ValueError('corrupt lines value %r' % lines)
 
1819
        compressed_bytes = tuned_gzip.bytes_to_gzip(bytes)
 
1820
        return len(compressed_bytes), compressed_bytes
 
1821
 
 
1822
    def _split_header(self, line):
 
1823
        rec = line.split()
 
1824
        if len(rec) != 4:
 
1825
            raise KnitCorrupt(self,
 
1826
                              'unexpected number of elements in record header')
 
1827
        return rec
 
1828
 
 
1829
    def keys(self):
 
1830
        """See VersionedFiles.keys."""
 
1831
        if 'evil' in debug.debug_flags:
 
1832
            trace.mutter_callsite(2, "keys scales with size of history")
 
1833
        sources = [self._index] + self._fallback_vfs
 
1834
        result = set()
 
1835
        for source in sources:
 
1836
            result.update(source.keys())
 
1837
        return result
 
1838
 
 
1839
 
 
1840
class _ContentMapGenerator(object):
 
1841
    """Generate texts or expose raw deltas for a set of texts."""
 
1842
 
 
1843
    def _get_content(self, key):
 
1844
        """Get the content object for key."""
 
1845
        # Note that _get_content is only called when the _ContentMapGenerator
 
1846
        # has been constructed with just one key requested for reconstruction.
 
1847
        if key in self.nonlocal_keys:
 
1848
            record = self.get_record_stream().next()
 
1849
            # Create a content object on the fly
 
1850
            lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
 
1851
            return PlainKnitContent(lines, record.key)
 
1852
        else:
 
1853
            # local keys we can ask for directly
 
1854
            return self._get_one_work(key)
 
1855
 
 
1856
    def get_record_stream(self):
 
1857
        """Get a record stream for the keys requested during __init__."""
 
1858
        for record in self._work():
 
1859
            yield record
 
1860
 
 
1861
    def _work(self):
 
1862
        """Produce maps of text and KnitContents as dicts.
 
1863
        
 
1864
        :return: (text_map, content_map) where text_map contains the texts for
 
1865
            the requested versions and content_map contains the KnitContents.
 
1866
        """
 
1867
        # NB: By definition we never need to read remote sources unless texts
 
1868
        # are requested from them: we don't delta across stores - and we
 
1869
        # explicitly do not want to to prevent data loss situations.
 
1870
        if self.global_map is None:
 
1871
            self.global_map = self.vf.get_parent_map(self.keys)
 
1872
        nonlocal_keys = self.nonlocal_keys
 
1873
 
 
1874
        missing_keys = set(nonlocal_keys)
 
1875
        # Read from remote versioned file instances and provide to our caller.
 
1876
        for source in self.vf._fallback_vfs:
 
1877
            if not missing_keys:
 
1878
                break
 
1879
            # Loop over fallback repositories asking them for texts - ignore
 
1880
            # any missing from a particular fallback.
 
1881
            for record in source.get_record_stream(missing_keys,
 
1882
                'unordered', True):
 
1883
                if record.storage_kind == 'absent':
 
1884
                    # Not in thie particular stream, may be in one of the
 
1885
                    # other fallback vfs objects.
 
1886
                    continue
 
1887
                missing_keys.remove(record.key)
 
1888
                yield record
 
1889
 
 
1890
        self._raw_record_map = self.vf._get_record_map_unparsed(self.keys,
 
1891
            allow_missing=True)
 
1892
        first = True
 
1893
        for key in self.keys:
 
1894
            if key in self.nonlocal_keys:
 
1895
                continue
 
1896
            yield LazyKnitContentFactory(key, self.global_map[key], self, first)
 
1897
            first = False
 
1898
 
 
1899
    def _get_one_work(self, requested_key):
 
1900
        # Now, if we have calculated everything already, just return the
 
1901
        # desired text.
 
1902
        if requested_key in self._contents_map:
 
1903
            return self._contents_map[requested_key]
 
1904
        # To simplify things, parse everything at once - code that wants one text
 
1905
        # probably wants them all.
 
1906
        # FUTURE: This function could be improved for the 'extract many' case
 
1907
        # by tracking each component and only doing the copy when the number of
 
1908
        # children than need to apply delta's to it is > 1 or it is part of the
 
1909
        # final output.
 
1910
        multiple_versions = len(self.keys) != 1
 
1911
        if self._record_map is None:
 
1912
            self._record_map = self.vf._raw_map_to_record_map(
 
1913
                self._raw_record_map)
 
1914
        record_map = self._record_map
 
1915
        # raw_record_map is key:
 
1916
        # Have read and parsed records at this point. 
 
1917
        for key in self.keys:
 
1918
            if key in self.nonlocal_keys:
 
1919
                # already handled
 
1920
                continue
 
1921
            components = []
 
1922
            cursor = key
 
1923
            while cursor is not None:
 
1924
                try:
 
1925
                    record, record_details, digest, next = record_map[cursor]
 
1926
                except KeyError:
 
1927
                    raise RevisionNotPresent(cursor, self)
 
1928
                components.append((cursor, record, record_details, digest))
 
1929
                cursor = next
 
1930
                if cursor in self._contents_map:
 
1931
                    # no need to plan further back
 
1932
                    components.append((cursor, None, None, None))
 
1933
                    break
 
1934
 
 
1935
            content = None
 
1936
            for (component_id, record, record_details,
 
1937
                 digest) in reversed(components):
 
1938
                if component_id in self._contents_map:
 
1939
                    content = self._contents_map[component_id]
 
1940
                else:
 
1941
                    content, delta = self._factory.parse_record(key[-1],
 
1942
                        record, record_details, content,
 
1943
                        copy_base_content=multiple_versions)
 
1944
                    if multiple_versions:
 
1945
                        self._contents_map[component_id] = content
 
1946
 
 
1947
            # digest here is the digest from the last applied component.
 
1948
            text = content.text()
 
1949
            actual_sha = sha_strings(text)
 
1950
            if actual_sha != digest:
 
1951
                raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
 
1952
        if multiple_versions:
 
1953
            return self._contents_map[requested_key]
 
1954
        else:
 
1955
            return content
 
1956
 
 
1957
    def _wire_bytes(self):
 
1958
        """Get the bytes to put on the wire for 'key'.
 
1959
 
 
1960
        The first collection of bytes asked for returns the serialised
 
1961
        raw_record_map and the additional details (key, parent) for key.
 
1962
        Subsequent calls return just the additional details (key, parent).
 
1963
        The wire storage_kind given for the first key is 'knit-delta-closure',
 
1964
        For subsequent keys it is 'knit-delta-closure-ref'.
 
1965
 
 
1966
        :param key: A key from the content generator.
 
1967
        :return: Bytes to put on the wire.
 
1968
        """
 
1969
        lines = []
 
1970
        # kind marker for dispatch on the far side,
 
1971
        lines.append('knit-delta-closure')
 
1972
        # Annotated or not
 
1973
        if self.vf._factory.annotated:
 
1974
            lines.append('annotated')
 
1975
        else:
 
1976
            lines.append('')
 
1977
        # then the list of keys
 
1978
        lines.append('\t'.join(['\x00'.join(key) for key in self.keys
 
1979
            if key not in self.nonlocal_keys]))
 
1980
        # then the _raw_record_map in serialised form:
 
1981
        map_byte_list = []
 
1982
        # for each item in the map:
 
1983
        # 1 line with key
 
1984
        # 1 line with parents if the key is to be yielded (None: for None, '' for ())
 
1985
        # one line with method
 
1986
        # one line with noeol
 
1987
        # one line with next ('' for None)
 
1988
        # one line with byte count of the record bytes
 
1989
        # the record bytes
 
1990
        for key, (record_bytes, (method, noeol), next) in \
 
1991
            self._raw_record_map.iteritems():
 
1992
            key_bytes = '\x00'.join(key)
 
1993
            parents = self.global_map.get(key, None)
 
1994
            if parents is None:
 
1995
                parent_bytes = 'None:'
 
1996
            else:
 
1997
                parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
 
1998
            method_bytes = method
 
1999
            if noeol:
 
2000
                noeol_bytes = "T"
 
2001
            else:
 
2002
                noeol_bytes = "F"
 
2003
            if next:
 
2004
                next_bytes = '\x00'.join(next)
 
2005
            else:
 
2006
                next_bytes = ''
 
2007
            map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
 
2008
                key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
 
2009
                len(record_bytes), record_bytes))
 
2010
        map_bytes = ''.join(map_byte_list)
 
2011
        lines.append(map_bytes)
 
2012
        bytes = '\n'.join(lines)
 
2013
        return bytes
 
2014
 
 
2015
 
 
2016
class _VFContentMapGenerator(_ContentMapGenerator):
 
2017
    """Content map generator reading from a VersionedFiles object."""
 
2018
 
 
2019
    def __init__(self, versioned_files, keys, nonlocal_keys=None,
 
2020
        global_map=None, raw_record_map=None):
 
2021
        """Create a _ContentMapGenerator.
 
2022
        
 
2023
        :param versioned_files: The versioned files that the texts are being
 
2024
            extracted from.
 
2025
        :param keys: The keys to produce content maps for.
 
2026
        :param nonlocal_keys: An iterable of keys(possibly intersecting keys)
 
2027
            which are known to not be in this knit, but rather in one of the
 
2028
            fallback knits.
 
2029
        :param global_map: The result of get_parent_map(keys) (or a supermap).
 
2030
            This is required if get_record_stream() is to be used.
 
2031
        :param raw_record_map: A unparsed raw record map to use for answering
 
2032
            contents.
 
2033
        """
 
2034
        # The vf to source data from
 
2035
        self.vf = versioned_files
 
2036
        # The keys desired
 
2037
        self.keys = list(keys)
 
2038
        # Keys known to be in fallback vfs objects
 
2039
        if nonlocal_keys is None:
 
2040
            self.nonlocal_keys = set()
 
2041
        else:
 
2042
            self.nonlocal_keys = frozenset(nonlocal_keys)
 
2043
        # Parents data for keys to be returned in get_record_stream
 
2044
        self.global_map = global_map
 
2045
        # The chunked lists for self.keys in text form
 
2046
        self._text_map = {}
 
2047
        # A cache of KnitContent objects used in extracting texts.
 
2048
        self._contents_map = {}
 
2049
        # All the knit records needed to assemble the requested keys as full
 
2050
        # texts.
 
2051
        self._record_map = None
 
2052
        if raw_record_map is None:
 
2053
            self._raw_record_map = self.vf._get_record_map_unparsed(keys,
 
2054
                allow_missing=True)
 
2055
        else:
 
2056
            self._raw_record_map = raw_record_map
 
2057
        # the factory for parsing records
 
2058
        self._factory = self.vf._factory
 
2059
 
 
2060
 
 
2061
class _NetworkContentMapGenerator(_ContentMapGenerator):
 
2062
    """Content map generator sourced from a network stream."""
 
2063
 
 
2064
    def __init__(self, bytes, line_end):
 
2065
        """Construct a _NetworkContentMapGenerator from a bytes block."""
 
2066
        self._bytes = bytes
 
2067
        self.global_map = {}
 
2068
        self._raw_record_map = {}
 
2069
        self._contents_map = {}
 
2070
        self._record_map = None
 
2071
        self.nonlocal_keys = []
 
2072
        # Get access to record parsing facilities
 
2073
        self.vf = KnitVersionedFiles(None, None)
 
2074
        start = line_end
 
2075
        # Annotated or not
 
2076
        line_end = bytes.find('\n', start)
 
2077
        line = bytes[start:line_end]
 
2078
        start = line_end + 1
 
2079
        if line == 'annotated':
 
2080
            self._factory = KnitAnnotateFactory()
 
2081
        else:
 
2082
            self._factory = KnitPlainFactory()
 
2083
        # list of keys to emit in get_record_stream
 
2084
        line_end = bytes.find('\n', start)
 
2085
        line = bytes[start:line_end]
 
2086
        start = line_end + 1
 
2087
        self.keys = [
 
2088
            tuple(segment.split('\x00')) for segment in line.split('\t')
 
2089
            if segment]
 
2090
        # now a loop until the end. XXX: It would be nice if this was just a
 
2091
        # bunch of the same records as get_record_stream(..., False) gives, but
 
2092
        # there is a decent sized gap stopping that at the moment.
 
2093
        end = len(bytes)
 
2094
        while start < end:
 
2095
            # 1 line with key
 
2096
            line_end = bytes.find('\n', start)
 
2097
            key = tuple(bytes[start:line_end].split('\x00'))
 
2098
            start = line_end + 1
 
2099
            # 1 line with parents (None: for None, '' for ())
 
2100
            line_end = bytes.find('\n', start)
 
2101
            line = bytes[start:line_end]
 
2102
            if line == 'None:':
 
2103
                parents = None
 
2104
            else:
 
2105
                parents = tuple(
 
2106
                    [tuple(segment.split('\x00')) for segment in line.split('\t')
 
2107
                     if segment])
 
2108
            self.global_map[key] = parents
 
2109
            start = line_end + 1
 
2110
            # one line with method
 
2111
            line_end = bytes.find('\n', start)
 
2112
            line = bytes[start:line_end]
 
2113
            method = line
 
2114
            start = line_end + 1
 
2115
            # one line with noeol
 
2116
            line_end = bytes.find('\n', start)
 
2117
            line = bytes[start:line_end]
 
2118
            noeol = line == "T"
 
2119
            start = line_end + 1
 
2120
            # one line with next ('' for None)
 
2121
            line_end = bytes.find('\n', start)
 
2122
            line = bytes[start:line_end]
 
2123
            if not line:
 
2124
                next = None
 
2125
            else:
 
2126
                next = tuple(bytes[start:line_end].split('\x00'))
 
2127
            start = line_end + 1
 
2128
            # one line with byte count of the record bytes
 
2129
            line_end = bytes.find('\n', start)
 
2130
            line = bytes[start:line_end]
 
2131
            count = int(line)
 
2132
            start = line_end + 1
 
2133
            # the record bytes
 
2134
            record_bytes = bytes[start:start+count]
 
2135
            start = start + count
 
2136
            # put it in the map
 
2137
            self._raw_record_map[key] = (record_bytes, (method, noeol), next)
 
2138
 
 
2139
    def get_record_stream(self):
 
2140
        """Get a record stream for for keys requested by the bytestream."""
 
2141
        first = True
 
2142
        for key in self.keys:
 
2143
            yield LazyKnitContentFactory(key, self.global_map[key], self, first)
 
2144
            first = False
 
2145
 
 
2146
    def _wire_bytes(self):
 
2147
        return self._bytes
 
2148
 
 
2149
 
 
2150
class _KndxIndex(object):
 
2151
    """Manages knit index files
 
2152
 
 
2153
    The index is kept in memory and read on startup, to enable
 
2154
    fast lookups of revision information.  The cursor of the index
 
2155
    file is always pointing to the end, making it easy to append
 
2156
    entries.
 
2157
 
 
2158
    _cache is a cache for fast mapping from version id to a Index
 
2159
    object.
 
2160
 
 
2161
    _history is a cache for fast mapping from indexes to version ids.
 
2162
 
 
2163
    The index data format is dictionary compressed when it comes to
 
2164
    parent references; a index entry may only have parents that with a
 
2165
    lover index number.  As a result, the index is topological sorted.
 
2166
 
 
2167
    Duplicate entries may be written to the index for a single version id
 
2168
    if this is done then the latter one completely replaces the former:
 
2169
    this allows updates to correct version and parent information. 
 
2170
    Note that the two entries may share the delta, and that successive
 
2171
    annotations and references MUST point to the first entry.
 
2172
 
 
2173
    The index file on disc contains a header, followed by one line per knit
 
2174
    record. The same revision can be present in an index file more than once.
 
2175
    The first occurrence gets assigned a sequence number starting from 0. 
 
2176
    
 
2177
    The format of a single line is
 
2178
    REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
 
2179
    REVISION_ID is a utf8-encoded revision id
 
2180
    FLAGS is a comma separated list of flags about the record. Values include 
 
2181
        no-eol, line-delta, fulltext.
 
2182
    BYTE_OFFSET is the ascii representation of the byte offset in the data file
 
2183
        that the the compressed data starts at.
 
2184
    LENGTH is the ascii representation of the length of the data file.
 
2185
    PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
 
2186
        REVISION_ID.
 
2187
    PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
 
2188
        revision id already in the knit that is a parent of REVISION_ID.
 
2189
    The ' :' marker is the end of record marker.
 
2190
    
 
2191
    partial writes:
 
2192
    when a write is interrupted to the index file, it will result in a line
 
2193
    that does not end in ' :'. If the ' :' is not present at the end of a line,
 
2194
    or at the end of the file, then the record that is missing it will be
 
2195
    ignored by the parser.
 
2196
 
 
2197
    When writing new records to the index file, the data is preceded by '\n'
 
2198
    to ensure that records always start on new lines even if the last write was
 
2199
    interrupted. As a result its normal for the last line in the index to be
 
2200
    missing a trailing newline. One can be added with no harmful effects.
 
2201
 
 
2202
    :ivar _kndx_cache: dict from prefix to the old state of KnitIndex objects,
 
2203
        where prefix is e.g. the (fileid,) for .texts instances or () for
 
2204
        constant-mapped things like .revisions, and the old state is
 
2205
        tuple(history_vector, cache_dict).  This is used to prevent having an
 
2206
        ABI change with the C extension that reads .kndx files.
 
2207
    """
 
2208
 
 
2209
    HEADER = "# bzr knit index 8\n"
 
2210
 
 
2211
    def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
 
2212
        """Create a _KndxIndex on transport using mapper."""
 
2213
        self._transport = transport
 
2214
        self._mapper = mapper
 
2215
        self._get_scope = get_scope
 
2216
        self._allow_writes = allow_writes
 
2217
        self._is_locked = is_locked
 
2218
        self._reset_cache()
 
2219
        self.has_graph = True
 
2220
 
 
2221
    def add_records(self, records, random_id=False):
 
2222
        """Add multiple records to the index.
 
2223
        
 
2224
        :param records: a list of tuples:
 
2225
                         (key, options, access_memo, parents).
 
2226
        :param random_id: If True the ids being added were randomly generated
 
2227
            and no check for existence will be performed.
 
2228
        """
 
2229
        paths = {}
 
2230
        for record in records:
 
2231
            key = record[0]
 
2232
            prefix = key[:-1]
 
2233
            path = self._mapper.map(key) + '.kndx'
 
2234
            path_keys = paths.setdefault(path, (prefix, []))
 
2235
            path_keys[1].append(record)
 
2236
        for path in sorted(paths):
 
2237
            prefix, path_keys = paths[path]
 
2238
            self._load_prefixes([prefix])
 
2239
            lines = []
 
2240
            orig_history = self._kndx_cache[prefix][1][:]
 
2241
            orig_cache = self._kndx_cache[prefix][0].copy()
 
2242
 
 
2243
            try:
 
2244
                for key, options, (_, pos, size), parents in path_keys:
 
2245
                    if parents is None:
 
2246
                        # kndx indices cannot be parentless.
 
2247
                        parents = ()
 
2248
                    line = "\n%s %s %s %s %s :" % (
 
2249
                        key[-1], ','.join(options), pos, size,
 
2250
                        self._dictionary_compress(parents))
 
2251
                    if type(line) != str:
 
2252
                        raise AssertionError(
 
2253
                            'data must be utf8 was %s' % type(line))
 
2254
                    lines.append(line)
 
2255
                    self._cache_key(key, options, pos, size, parents)
 
2256
                if len(orig_history):
 
2257
                    self._transport.append_bytes(path, ''.join(lines))
 
2258
                else:
 
2259
                    self._init_index(path, lines)
 
2260
            except:
 
2261
                # If any problems happen, restore the original values and re-raise
 
2262
                self._kndx_cache[prefix] = (orig_cache, orig_history)
 
2263
                raise
 
2264
 
 
2265
    def scan_unvalidated_index(self, graph_index):
 
2266
        """See _KnitGraphIndex.scan_unvalidated_index."""
 
2267
        # Because kndx files do not support atomic insertion via separate index
 
2268
        # files, they do not support this method.
 
2269
        raise NotImplementedError(self.scan_unvalidated_index)
 
2270
 
 
2271
    def get_missing_compression_parents(self):
 
2272
        """See _KnitGraphIndex.get_missing_compression_parents."""
 
2273
        # Because kndx files do not support atomic insertion via separate index
 
2274
        # files, they do not support this method.
 
2275
        raise NotImplementedError(self.get_missing_compression_parents)
 
2276
    
 
2277
    def _cache_key(self, key, options, pos, size, parent_keys):
 
2278
        """Cache a version record in the history array and index cache.
 
2279
 
 
2280
        This is inlined into _load_data for performance. KEEP IN SYNC.
 
2281
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
 
2282
         indexes).
 
2283
        """
 
2284
        prefix = key[:-1]
 
2285
        version_id = key[-1]
 
2286
        # last-element only for compatibilty with the C load_data.
 
2287
        parents = tuple(parent[-1] for parent in parent_keys)
 
2288
        for parent in parent_keys:
 
2289
            if parent[:-1] != prefix:
 
2290
                raise ValueError("mismatched prefixes for %r, %r" % (
 
2291
                    key, parent_keys))
 
2292
        cache, history = self._kndx_cache[prefix]
 
2293
        # only want the _history index to reference the 1st index entry
 
2294
        # for version_id
 
2295
        if version_id not in cache:
 
2296
            index = len(history)
 
2297
            history.append(version_id)
 
2298
        else:
 
2299
            index = cache[version_id][5]
 
2300
        cache[version_id] = (version_id,
 
2301
                                   options,
 
2302
                                   pos,
 
2303
                                   size,
 
2304
                                   parents,
 
2305
                                   index)
 
2306
 
 
2307
    def check_header(self, fp):
 
2308
        line = fp.readline()
 
2309
        if line == '':
 
2310
            # An empty file can actually be treated as though the file doesn't
 
2311
            # exist yet.
 
2312
            raise errors.NoSuchFile(self)
 
2313
        if line != self.HEADER:
 
2314
            raise KnitHeaderError(badline=line, filename=self)
 
2315
 
 
2316
    def _check_read(self):
 
2317
        if not self._is_locked():
 
2318
            raise errors.ObjectNotLocked(self)
 
2319
        if self._get_scope() != self._scope:
 
2320
            self._reset_cache()
 
2321
 
 
2322
    def _check_write_ok(self):
 
2323
        """Assert if not writes are permitted."""
 
2324
        if not self._is_locked():
 
2325
            raise errors.ObjectNotLocked(self)
 
2326
        if self._get_scope() != self._scope:
 
2327
            self._reset_cache()
 
2328
        if self._mode != 'w':
 
2329
            raise errors.ReadOnlyObjectDirtiedError(self)
 
2330
 
 
2331
    def get_build_details(self, keys):
 
2332
        """Get the method, index_memo and compression parent for keys.
 
2333
 
 
2334
        Ghosts are omitted from the result.
 
2335
 
 
2336
        :param keys: An iterable of keys.
 
2337
        :return: A dict of key:(index_memo, compression_parent, parents,
 
2338
            record_details).
 
2339
            index_memo
 
2340
                opaque structure to pass to read_records to extract the raw
 
2341
                data
 
2342
            compression_parent
 
2343
                Content that this record is built upon, may be None
 
2344
            parents
 
2345
                Logical parents of this node
 
2346
            record_details
 
2347
                extra information about the content which needs to be passed to
 
2348
                Factory.parse_record
 
2349
        """
 
2350
        parent_map = self.get_parent_map(keys)
 
2351
        result = {}
 
2352
        for key in keys:
 
2353
            if key not in parent_map:
 
2354
                continue # Ghost
 
2355
            method = self.get_method(key)
 
2356
            parents = parent_map[key]
 
2357
            if method == 'fulltext':
 
2358
                compression_parent = None
 
2359
            else:
 
2360
                compression_parent = parents[0]
 
2361
            noeol = 'no-eol' in self.get_options(key)
 
2362
            index_memo = self.get_position(key)
 
2363
            result[key] = (index_memo, compression_parent,
 
2364
                                  parents, (method, noeol))
 
2365
        return result
 
2366
 
 
2367
    def get_method(self, key):
 
2368
        """Return compression method of specified key."""
 
2369
        options = self.get_options(key)
 
2370
        if 'fulltext' in options:
 
2371
            return 'fulltext'
 
2372
        elif 'line-delta' in options:
 
2373
            return 'line-delta'
 
2374
        else:
 
2375
            raise errors.KnitIndexUnknownMethod(self, options)
 
2376
 
 
2377
    def get_options(self, key):
 
2378
        """Return a list representing options.
 
2379
 
 
2380
        e.g. ['foo', 'bar']
 
2381
        """
 
2382
        prefix, suffix = self._split_key(key)
 
2383
        self._load_prefixes([prefix])
 
2384
        try:
 
2385
            return self._kndx_cache[prefix][0][suffix][1]
 
2386
        except KeyError:
 
2387
            raise RevisionNotPresent(key, self)
 
2388
 
 
2389
    def get_parent_map(self, keys):
 
2390
        """Get a map of the parents of keys.
 
2391
 
 
2392
        :param keys: The keys to look up parents for.
 
2393
        :return: A mapping from keys to parents. Absent keys are absent from
 
2394
            the mapping.
 
2395
        """
 
2396
        # Parse what we need to up front, this potentially trades off I/O
 
2397
        # locality (.kndx and .knit in the same block group for the same file
 
2398
        # id) for less checking in inner loops.
 
2399
        prefixes = set(key[:-1] for key in keys)
 
2400
        self._load_prefixes(prefixes)
 
2401
        result = {}
 
2402
        for key in keys:
 
2403
            prefix = key[:-1]
 
2404
            try:
 
2405
                suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
 
2406
            except KeyError:
 
2407
                pass
 
2408
            else:
 
2409
                result[key] = tuple(prefix + (suffix,) for
 
2410
                    suffix in suffix_parents)
 
2411
        return result
 
2412
 
 
2413
    def get_position(self, key):
 
2414
        """Return details needed to access the version.
 
2415
        
 
2416
        :return: a tuple (key, data position, size) to hand to the access
 
2417
            logic to get the record.
 
2418
        """
 
2419
        prefix, suffix = self._split_key(key)
 
2420
        self._load_prefixes([prefix])
 
2421
        entry = self._kndx_cache[prefix][0][suffix]
 
2422
        return key, entry[2], entry[3]
 
2423
 
 
2424
    has_key = _mod_index._has_key_from_parent_map
 
2425
    
 
2426
    def _init_index(self, path, extra_lines=[]):
 
2427
        """Initialize an index."""
 
2428
        sio = StringIO()
 
2429
        sio.write(self.HEADER)
 
2430
        sio.writelines(extra_lines)
 
2431
        sio.seek(0)
 
2432
        self._transport.put_file_non_atomic(path, sio,
 
2433
                            create_parent_dir=True)
 
2434
                           # self._create_parent_dir)
 
2435
                           # mode=self._file_mode,
 
2436
                           # dir_mode=self._dir_mode)
 
2437
 
 
2438
    def keys(self):
 
2439
        """Get all the keys in the collection.
 
2440
        
 
2441
        The keys are not ordered.
 
2442
        """
 
2443
        result = set()
 
2444
        # Identify all key prefixes.
 
2445
        # XXX: A bit hacky, needs polish.
 
2446
        if type(self._mapper) == ConstantMapper:
 
2447
            prefixes = [()]
 
2448
        else:
 
2449
            relpaths = set()
 
2450
            for quoted_relpath in self._transport.iter_files_recursive():
 
2451
                path, ext = os.path.splitext(quoted_relpath)
 
2452
                relpaths.add(path)
 
2453
            prefixes = [self._mapper.unmap(path) for path in relpaths]
 
2454
        self._load_prefixes(prefixes)
 
2455
        for prefix in prefixes:
 
2456
            for suffix in self._kndx_cache[prefix][1]:
 
2457
                result.add(prefix + (suffix,))
 
2458
        return result
 
2459
    
 
2460
    def _load_prefixes(self, prefixes):
 
2461
        """Load the indices for prefixes."""
 
2462
        self._check_read()
 
2463
        for prefix in prefixes:
 
2464
            if prefix not in self._kndx_cache:
 
2465
                # the load_data interface writes to these variables.
 
2466
                self._cache = {}
 
2467
                self._history = []
 
2468
                self._filename = prefix
 
2469
                try:
 
2470
                    path = self._mapper.map(prefix) + '.kndx'
 
2471
                    fp = self._transport.get(path)
 
2472
                    try:
 
2473
                        # _load_data may raise NoSuchFile if the target knit is
 
2474
                        # completely empty.
 
2475
                        _load_data(self, fp)
 
2476
                    finally:
 
2477
                        fp.close()
 
2478
                    self._kndx_cache[prefix] = (self._cache, self._history)
 
2479
                    del self._cache
 
2480
                    del self._filename
 
2481
                    del self._history
 
2482
                except NoSuchFile:
 
2483
                    self._kndx_cache[prefix] = ({}, [])
 
2484
                    if type(self._mapper) == ConstantMapper:
 
2485
                        # preserve behaviour for revisions.kndx etc.
 
2486
                        self._init_index(path)
 
2487
                    del self._cache
 
2488
                    del self._filename
 
2489
                    del self._history
 
2490
 
 
2491
    missing_keys = _mod_index._missing_keys_from_parent_map
 
2492
 
 
2493
    def _partition_keys(self, keys):
 
2494
        """Turn keys into a dict of prefix:suffix_list."""
 
2495
        result = {}
 
2496
        for key in keys:
 
2497
            prefix_keys = result.setdefault(key[:-1], [])
 
2498
            prefix_keys.append(key[-1])
 
2499
        return result
 
2500
 
 
2501
    def _dictionary_compress(self, keys):
 
2502
        """Dictionary compress keys.
 
2503
        
 
2504
        :param keys: The keys to generate references to.
 
2505
        :return: A string representation of keys. keys which are present are
 
2506
            dictionary compressed, and others are emitted as fulltext with a
 
2507
            '.' prefix.
 
2508
        """
 
2509
        if not keys:
 
2510
            return ''
 
2511
        result_list = []
 
2512
        prefix = keys[0][:-1]
 
2513
        cache = self._kndx_cache[prefix][0]
 
2514
        for key in keys:
 
2515
            if key[:-1] != prefix:
 
2516
                # kndx indices cannot refer across partitioned storage.
 
2517
                raise ValueError("mismatched prefixes for %r" % keys)
 
2518
            if key[-1] in cache:
 
2519
                # -- inlined lookup() --
 
2520
                result_list.append(str(cache[key[-1]][5]))
 
2521
                # -- end lookup () --
 
2522
            else:
 
2523
                result_list.append('.' + key[-1])
 
2524
        return ' '.join(result_list)
 
2525
 
 
2526
    def _reset_cache(self):
 
2527
        # Possibly this should be a LRU cache. A dictionary from key_prefix to
 
2528
        # (cache_dict, history_vector) for parsed kndx files.
 
2529
        self._kndx_cache = {}
 
2530
        self._scope = self._get_scope()
 
2531
        allow_writes = self._allow_writes()
 
2532
        if allow_writes:
 
2533
            self._mode = 'w'
 
2534
        else:
 
2535
            self._mode = 'r'
 
2536
 
 
2537
    def _sort_keys_by_io(self, keys, positions):
 
2538
        """Figure out an optimal order to read the records for the given keys.
 
2539
 
 
2540
        Sort keys, grouped by index and sorted by position.
 
2541
 
 
2542
        :param keys: A list of keys whose records we want to read. This will be
 
2543
            sorted 'in-place'.
 
2544
        :param positions: A dict, such as the one returned by
 
2545
            _get_components_positions()
 
2546
        :return: None
 
2547
        """
 
2548
        def get_sort_key(key):
 
2549
            index_memo = positions[key][1]
 
2550
            # Group by prefix and position. index_memo[0] is the key, so it is
 
2551
            # (file_id, revision_id) and we don't want to sort on revision_id,
 
2552
            # index_memo[1] is the position, and index_memo[2] is the size,
 
2553
            # which doesn't matter for the sort
 
2554
            return index_memo[0][:-1], index_memo[1]
 
2555
        return keys.sort(key=get_sort_key)
 
2556
 
 
2557
    def _split_key(self, key):
 
2558
        """Split key into a prefix and suffix."""
 
2559
        return key[:-1], key[-1]
 
2560
 
 
2561
 
 
2562
class _KnitGraphIndex(object):
 
2563
    """A KnitVersionedFiles index layered on GraphIndex."""
 
2564
 
 
2565
    def __init__(self, graph_index, is_locked, deltas=False, parents=True,
 
2566
        add_callback=None):
 
2567
        """Construct a KnitGraphIndex on a graph_index.
 
2568
 
 
2569
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
 
2570
        :param is_locked: A callback to check whether the object should answer
 
2571
            queries.
 
2572
        :param deltas: Allow delta-compressed records.
 
2573
        :param parents: If True, record knits parents, if not do not record 
 
2574
            parents.
 
2575
        :param add_callback: If not None, allow additions to the index and call
 
2576
            this callback with a list of added GraphIndex nodes:
 
2577
            [(node, value, node_refs), ...]
 
2578
        :param is_locked: A callback, returns True if the index is locked and
 
2579
            thus usable.
 
2580
        """
 
2581
        self._add_callback = add_callback
 
2582
        self._graph_index = graph_index
 
2583
        self._deltas = deltas
 
2584
        self._parents = parents
 
2585
        if deltas and not parents:
 
2586
            # XXX: TODO: Delta tree and parent graph should be conceptually
 
2587
            # separate.
 
2588
            raise KnitCorrupt(self, "Cannot do delta compression without "
 
2589
                "parent tracking.")
 
2590
        self.has_graph = parents
 
2591
        self._is_locked = is_locked
 
2592
        self._missing_compression_parents = set()
 
2593
 
 
2594
    def __repr__(self):
 
2595
        return "%s(%r)" % (self.__class__.__name__, self._graph_index)
 
2596
 
 
2597
    def add_records(self, records, random_id=False):
 
2598
        """Add multiple records to the index.
 
2599
        
 
2600
        This function does not insert data into the Immutable GraphIndex
 
2601
        backing the KnitGraphIndex, instead it prepares data for insertion by
 
2602
        the caller and checks that it is safe to insert then calls
 
2603
        self._add_callback with the prepared GraphIndex nodes.
 
2604
 
 
2605
        :param records: a list of tuples:
 
2606
                         (key, options, access_memo, parents).
 
2607
        :param random_id: If True the ids being added were randomly generated
 
2608
            and no check for existence will be performed.
 
2609
        """
 
2610
        if not self._add_callback:
 
2611
            raise errors.ReadOnlyError(self)
 
2612
        # we hope there are no repositories with inconsistent parentage
 
2613
        # anymore.
 
2614
 
 
2615
        keys = {}
 
2616
        for (key, options, access_memo, parents) in records:
 
2617
            if self._parents:
 
2618
                parents = tuple(parents)
 
2619
            index, pos, size = access_memo
 
2620
            if 'no-eol' in options:
 
2621
                value = 'N'
 
2622
            else:
 
2623
                value = ' '
 
2624
            value += "%d %d" % (pos, size)
 
2625
            if not self._deltas:
 
2626
                if 'line-delta' in options:
 
2627
                    raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
 
2628
            if self._parents:
 
2629
                if self._deltas:
 
2630
                    if 'line-delta' in options:
 
2631
                        node_refs = (parents, (parents[0],))
 
2632
                    else:
 
2633
                        node_refs = (parents, ())
 
2634
                else:
 
2635
                    node_refs = (parents, )
 
2636
            else:
 
2637
                if parents:
 
2638
                    raise KnitCorrupt(self, "attempt to add node with parents "
 
2639
                        "in parentless index.")
 
2640
                node_refs = ()
 
2641
            keys[key] = (value, node_refs)
 
2642
        # check for dups
 
2643
        if not random_id:
 
2644
            present_nodes = self._get_entries(keys)
 
2645
            for (index, key, value, node_refs) in present_nodes:
 
2646
                if (value[0] != keys[key][0][0] or
 
2647
                    node_refs[:1] != keys[key][1][:1]):
 
2648
                    raise KnitCorrupt(self, "inconsistent details in add_records"
 
2649
                        ": %s %s" % ((value, node_refs), keys[key]))
 
2650
                del keys[key]
 
2651
        result = []
 
2652
        if self._parents:
 
2653
            for key, (value, node_refs) in keys.iteritems():
 
2654
                result.append((key, value, node_refs))
 
2655
        else:
 
2656
            for key, (value, node_refs) in keys.iteritems():
 
2657
                result.append((key, value))
 
2658
        self._add_callback(result)
 
2659
        
 
2660
    def scan_unvalidated_index(self, graph_index):
 
2661
        """Inform this _KnitGraphIndex that there is an unvalidated index.
 
2662
 
 
2663
        This allows this _KnitGraphIndex to keep track of any missing
 
2664
        compression parents we may want to have filled in to make those
 
2665
        indices valid.
 
2666
 
 
2667
        :param graph_index: A GraphIndex
 
2668
        """
 
2669
        if self._deltas:
 
2670
            new_missing = graph_index.external_references(ref_list_num=1)
 
2671
            new_missing.difference_update(self.get_parent_map(new_missing))
 
2672
            self._missing_compression_parents.update(new_missing)
 
2673
 
 
2674
    def get_missing_compression_parents(self):
 
2675
        """Return the keys of compression parents missing from unvalidated
 
2676
        indices.
 
2677
        """
 
2678
        return frozenset(self._missing_compression_parents)
 
2679
 
 
2680
    def _check_read(self):
 
2681
        """raise if reads are not permitted."""
 
2682
        if not self._is_locked():
 
2683
            raise errors.ObjectNotLocked(self)
 
2684
 
 
2685
    def _check_write_ok(self):
 
2686
        """Assert if writes are not permitted."""
 
2687
        if not self._is_locked():
 
2688
            raise errors.ObjectNotLocked(self)
 
2689
 
 
2690
    def _compression_parent(self, an_entry):
 
2691
        # return the key that an_entry is compressed against, or None
 
2692
        # Grab the second parent list (as deltas implies parents currently)
 
2693
        compression_parents = an_entry[3][1]
 
2694
        if not compression_parents:
 
2695
            return None
 
2696
        if len(compression_parents) != 1:
 
2697
            raise AssertionError(
 
2698
                "Too many compression parents: %r" % compression_parents)
 
2699
        return compression_parents[0]
 
2700
 
 
2701
    def get_build_details(self, keys):
 
2702
        """Get the method, index_memo and compression parent for version_ids.
 
2703
 
 
2704
        Ghosts are omitted from the result.
 
2705
 
 
2706
        :param keys: An iterable of keys.
 
2707
        :return: A dict of key:
 
2708
            (index_memo, compression_parent, parents, record_details).
 
2709
            index_memo
 
2710
                opaque structure to pass to read_records to extract the raw
 
2711
                data
 
2712
            compression_parent
 
2713
                Content that this record is built upon, may be None
 
2714
            parents
 
2715
                Logical parents of this node
 
2716
            record_details
 
2717
                extra information about the content which needs to be passed to
 
2718
                Factory.parse_record
 
2719
        """
 
2720
        self._check_read()
 
2721
        result = {}
 
2722
        entries = self._get_entries(keys, False)
 
2723
        for entry in entries:
 
2724
            key = entry[1]
 
2725
            if not self._parents:
 
2726
                parents = ()
 
2727
            else:
 
2728
                parents = entry[3][0]
 
2729
            if not self._deltas:
 
2730
                compression_parent_key = None
 
2731
            else:
 
2732
                compression_parent_key = self._compression_parent(entry)
 
2733
            noeol = (entry[2][0] == 'N')
 
2734
            if compression_parent_key:
 
2735
                method = 'line-delta'
 
2736
            else:
 
2737
                method = 'fulltext'
 
2738
            result[key] = (self._node_to_position(entry),
 
2739
                                  compression_parent_key, parents,
 
2740
                                  (method, noeol))
 
2741
        return result
 
2742
 
 
2743
    def _get_entries(self, keys, check_present=False):
 
2744
        """Get the entries for keys.
 
2745
        
 
2746
        :param keys: An iterable of index key tuples.
 
2747
        """
 
2748
        keys = set(keys)
 
2749
        found_keys = set()
 
2750
        if self._parents:
 
2751
            for node in self._graph_index.iter_entries(keys):
 
2752
                yield node
 
2753
                found_keys.add(node[1])
 
2754
        else:
 
2755
            # adapt parentless index to the rest of the code.
 
2756
            for node in self._graph_index.iter_entries(keys):
 
2757
                yield node[0], node[1], node[2], ()
 
2758
                found_keys.add(node[1])
 
2759
        if check_present:
 
2760
            missing_keys = keys.difference(found_keys)
 
2761
            if missing_keys:
 
2762
                raise RevisionNotPresent(missing_keys.pop(), self)
 
2763
 
 
2764
    def get_method(self, key):
 
2765
        """Return compression method of specified key."""
 
2766
        return self._get_method(self._get_node(key))
 
2767
 
 
2768
    def _get_method(self, node):
 
2769
        if not self._deltas:
 
2770
            return 'fulltext'
 
2771
        if self._compression_parent(node):
 
2772
            return 'line-delta'
 
2773
        else:
 
2774
            return 'fulltext'
 
2775
 
 
2776
    def _get_node(self, key):
 
2777
        try:
 
2778
            return list(self._get_entries([key]))[0]
 
2779
        except IndexError:
 
2780
            raise RevisionNotPresent(key, self)
 
2781
 
 
2782
    def get_options(self, key):
 
2783
        """Return a list representing options.
 
2784
 
 
2785
        e.g. ['foo', 'bar']
 
2786
        """
 
2787
        node = self._get_node(key)
 
2788
        options = [self._get_method(node)]
 
2789
        if node[2][0] == 'N':
 
2790
            options.append('no-eol')
 
2791
        return options
 
2792
 
 
2793
    def get_parent_map(self, keys):
 
2794
        """Get a map of the parents of keys.
 
2795
 
 
2796
        :param keys: The keys to look up parents for.
 
2797
        :return: A mapping from keys to parents. Absent keys are absent from
 
2798
            the mapping.
 
2799
        """
 
2800
        self._check_read()
 
2801
        nodes = self._get_entries(keys)
 
2802
        result = {}
 
2803
        if self._parents:
 
2804
            for node in nodes:
 
2805
                result[node[1]] = node[3][0]
 
2806
        else:
 
2807
            for node in nodes:
 
2808
                result[node[1]] = None
 
2809
        return result
 
2810
 
 
2811
    def get_position(self, key):
 
2812
        """Return details needed to access the version.
 
2813
        
 
2814
        :return: a tuple (index, data position, size) to hand to the access
 
2815
            logic to get the record.
 
2816
        """
 
2817
        node = self._get_node(key)
 
2818
        return self._node_to_position(node)
 
2819
 
 
2820
    has_key = _mod_index._has_key_from_parent_map
 
2821
 
 
2822
    def keys(self):
 
2823
        """Get all the keys in the collection.
 
2824
        
 
2825
        The keys are not ordered.
 
2826
        """
 
2827
        self._check_read()
 
2828
        return [node[1] for node in self._graph_index.iter_all_entries()]
 
2829
    
 
2830
    missing_keys = _mod_index._missing_keys_from_parent_map
 
2831
 
 
2832
    def _node_to_position(self, node):
 
2833
        """Convert an index value to position details."""
 
2834
        bits = node[2][1:].split(' ')
 
2835
        return node[0], int(bits[0]), int(bits[1])
 
2836
 
 
2837
    def _sort_keys_by_io(self, keys, positions):
 
2838
        """Figure out an optimal order to read the records for the given keys.
 
2839
 
 
2840
        Sort keys, grouped by index and sorted by position.
 
2841
 
 
2842
        :param keys: A list of keys whose records we want to read. This will be
 
2843
            sorted 'in-place'.
 
2844
        :param positions: A dict, such as the one returned by
 
2845
            _get_components_positions()
 
2846
        :return: None
 
2847
        """
 
2848
        def get_index_memo(key):
 
2849
            # index_memo is at offset [1]. It is made up of (GraphIndex,
 
2850
            # position, size). GI is an object, which will be unique for each
 
2851
            # pack file. This causes us to group by pack file, then sort by
 
2852
            # position. Size doesn't matter, but it isn't worth breaking up the
 
2853
            # tuple.
 
2854
            return positions[key][1]
 
2855
        return keys.sort(key=get_index_memo)
 
2856
 
 
2857
 
 
2858
class _KnitKeyAccess(object):
 
2859
    """Access to records in .knit files."""
 
2860
 
 
2861
    def __init__(self, transport, mapper):
 
2862
        """Create a _KnitKeyAccess with transport and mapper.
 
2863
 
 
2864
        :param transport: The transport the access object is rooted at.
 
2865
        :param mapper: The mapper used to map keys to .knit files.
 
2866
        """
 
2867
        self._transport = transport
 
2868
        self._mapper = mapper
 
2869
 
 
2870
    def add_raw_records(self, key_sizes, raw_data):
 
2871
        """Add raw knit bytes to a storage area.
 
2872
 
 
2873
        The data is spooled to the container writer in one bytes-record per
 
2874
        raw data item.
 
2875
 
 
2876
        :param sizes: An iterable of tuples containing the key and size of each
 
2877
            raw data segment.
 
2878
        :param raw_data: A bytestring containing the data.
 
2879
        :return: A list of memos to retrieve the record later. Each memo is an
 
2880
            opaque index memo. For _KnitKeyAccess the memo is (key, pos,
 
2881
            length), where the key is the record key.
 
2882
        """
 
2883
        if type(raw_data) != str:
 
2884
            raise AssertionError(
 
2885
                'data must be plain bytes was %s' % type(raw_data))
 
2886
        result = []
 
2887
        offset = 0
 
2888
        # TODO: This can be tuned for writing to sftp and other servers where
 
2889
        # append() is relatively expensive by grouping the writes to each key
 
2890
        # prefix.
 
2891
        for key, size in key_sizes:
 
2892
            path = self._mapper.map(key)
 
2893
            try:
 
2894
                base = self._transport.append_bytes(path + '.knit',
 
2895
                    raw_data[offset:offset+size])
 
2896
            except errors.NoSuchFile:
 
2897
                self._transport.mkdir(osutils.dirname(path))
 
2898
                base = self._transport.append_bytes(path + '.knit',
 
2899
                    raw_data[offset:offset+size])
 
2900
            # if base == 0:
 
2901
            # chmod.
 
2902
            offset += size
 
2903
            result.append((key, base, size))
 
2904
        return result
 
2905
 
 
2906
    def get_raw_records(self, memos_for_retrieval):
 
2907
        """Get the raw bytes for a records.
 
2908
 
 
2909
        :param memos_for_retrieval: An iterable containing the access memo for
 
2910
            retrieving the bytes.
 
2911
        :return: An iterator over the bytes of the records.
 
2912
        """
 
2913
        # first pass, group into same-index request to minimise readv's issued.
 
2914
        request_lists = []
 
2915
        current_prefix = None
 
2916
        for (key, offset, length) in memos_for_retrieval:
 
2917
            if current_prefix == key[:-1]:
 
2918
                current_list.append((offset, length))
 
2919
            else:
 
2920
                if current_prefix is not None:
 
2921
                    request_lists.append((current_prefix, current_list))
 
2922
                current_prefix = key[:-1]
 
2923
                current_list = [(offset, length)]
 
2924
        # handle the last entry
 
2925
        if current_prefix is not None:
 
2926
            request_lists.append((current_prefix, current_list))
 
2927
        for prefix, read_vector in request_lists:
 
2928
            path = self._mapper.map(prefix) + '.knit'
 
2929
            for pos, data in self._transport.readv(path, read_vector):
 
2930
                yield data
 
2931
 
 
2932
 
 
2933
class _DirectPackAccess(object):
 
2934
    """Access to data in one or more packs with less translation."""
 
2935
 
 
2936
    def __init__(self, index_to_packs, reload_func=None):
 
2937
        """Create a _DirectPackAccess object.
 
2938
 
 
2939
        :param index_to_packs: A dict mapping index objects to the transport
 
2940
            and file names for obtaining data.
 
2941
        :param reload_func: A function to call if we determine that the pack
 
2942
            files have moved and we need to reload our caches. See
 
2943
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
 
2944
        """
 
2945
        self._container_writer = None
 
2946
        self._write_index = None
 
2947
        self._indices = index_to_packs
 
2948
        self._reload_func = reload_func
 
2949
 
 
2950
    def add_raw_records(self, key_sizes, raw_data):
 
2951
        """Add raw knit bytes to a storage area.
 
2952
 
 
2953
        The data is spooled to the container writer in one bytes-record per
 
2954
        raw data item.
 
2955
 
 
2956
        :param sizes: An iterable of tuples containing the key and size of each
 
2957
            raw data segment.
 
2958
        :param raw_data: A bytestring containing the data.
 
2959
        :return: A list of memos to retrieve the record later. Each memo is an
 
2960
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
 
2961
            length), where the index field is the write_index object supplied
 
2962
            to the PackAccess object.
 
2963
        """
 
2964
        if type(raw_data) != str:
 
2965
            raise AssertionError(
 
2966
                'data must be plain bytes was %s' % type(raw_data))
 
2967
        result = []
 
2968
        offset = 0
 
2969
        for key, size in key_sizes:
 
2970
            p_offset, p_length = self._container_writer.add_bytes_record(
 
2971
                raw_data[offset:offset+size], [])
 
2972
            offset += size
 
2973
            result.append((self._write_index, p_offset, p_length))
 
2974
        return result
 
2975
 
 
2976
    def get_raw_records(self, memos_for_retrieval):
 
2977
        """Get the raw bytes for a records.
 
2978
 
 
2979
        :param memos_for_retrieval: An iterable containing the (index, pos, 
 
2980
            length) memo for retrieving the bytes. The Pack access method
 
2981
            looks up the pack to use for a given record in its index_to_pack
 
2982
            map.
 
2983
        :return: An iterator over the bytes of the records.
 
2984
        """
 
2985
        # first pass, group into same-index requests
 
2986
        request_lists = []
 
2987
        current_index = None
 
2988
        for (index, offset, length) in memos_for_retrieval:
 
2989
            if current_index == index:
 
2990
                current_list.append((offset, length))
 
2991
            else:
 
2992
                if current_index is not None:
 
2993
                    request_lists.append((current_index, current_list))
 
2994
                current_index = index
 
2995
                current_list = [(offset, length)]
 
2996
        # handle the last entry
 
2997
        if current_index is not None:
 
2998
            request_lists.append((current_index, current_list))
 
2999
        for index, offsets in request_lists:
 
3000
            try:
 
3001
                transport, path = self._indices[index]
 
3002
            except KeyError:
 
3003
                # A KeyError here indicates that someone has triggered an index
 
3004
                # reload, and this index has gone missing, we need to start
 
3005
                # over.
 
3006
                if self._reload_func is None:
 
3007
                    # If we don't have a _reload_func there is nothing that can
 
3008
                    # be done
 
3009
                    raise
 
3010
                raise errors.RetryWithNewPacks(index,
 
3011
                                               reload_occurred=True,
 
3012
                                               exc_info=sys.exc_info())
 
3013
            try:
 
3014
                reader = pack.make_readv_reader(transport, path, offsets)
 
3015
                for names, read_func in reader.iter_records():
 
3016
                    yield read_func(None)
 
3017
            except errors.NoSuchFile:
 
3018
                # A NoSuchFile error indicates that a pack file has gone
 
3019
                # missing on disk, we need to trigger a reload, and start over.
 
3020
                if self._reload_func is None:
 
3021
                    raise
 
3022
                raise errors.RetryWithNewPacks(transport.abspath(path),
 
3023
                                               reload_occurred=False,
 
3024
                                               exc_info=sys.exc_info())
 
3025
 
 
3026
    def set_writer(self, writer, index, transport_packname):
 
3027
        """Set a writer to use for adding data."""
 
3028
        if index is not None:
 
3029
            self._indices[index] = transport_packname
 
3030
        self._container_writer = writer
 
3031
        self._write_index = index
 
3032
 
 
3033
    def reload_or_raise(self, retry_exc):
 
3034
        """Try calling the reload function, or re-raise the original exception.
 
3035
 
 
3036
        This should be called after _DirectPackAccess raises a
 
3037
        RetryWithNewPacks exception. This function will handle the common logic
 
3038
        of determining when the error is fatal versus being temporary.
 
3039
        It will also make sure that the original exception is raised, rather
 
3040
        than the RetryWithNewPacks exception.
 
3041
 
 
3042
        If this function returns, then the calling function should retry
 
3043
        whatever operation was being performed. Otherwise an exception will
 
3044
        be raised.
 
3045
 
 
3046
        :param retry_exc: A RetryWithNewPacks exception.
 
3047
        """
 
3048
        is_error = False
 
3049
        if self._reload_func is None:
 
3050
            is_error = True
 
3051
        elif not self._reload_func():
 
3052
            # The reload claimed that nothing changed
 
3053
            if not retry_exc.reload_occurred:
 
3054
                # If there wasn't an earlier reload, then we really were
 
3055
                # expecting to find changes. We didn't find them, so this is a
 
3056
                # hard error
 
3057
                is_error = True
 
3058
        if is_error:
 
3059
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
 
3060
            raise exc_class, exc_value, exc_traceback
 
3061
 
 
3062
 
 
3063
# Deprecated, use PatienceSequenceMatcher instead
 
3064
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
 
3065
 
 
3066
 
 
3067
def annotate_knit(knit, revision_id):
 
3068
    """Annotate a knit with no cached annotations.
 
3069
 
 
3070
    This implementation is for knits with no cached annotations.
 
3071
    It will work for knits with cached annotations, but this is not
 
3072
    recommended.
 
3073
    """
 
3074
    annotator = _KnitAnnotator(knit)
 
3075
    return iter(annotator.annotate(revision_id))
 
3076
 
 
3077
 
 
3078
class _KnitAnnotator(object):
 
3079
    """Build up the annotations for a text."""
 
3080
 
 
3081
    def __init__(self, knit):
 
3082
        self._knit = knit
 
3083
 
 
3084
        # Content objects, differs from fulltexts because of how final newlines
 
3085
        # are treated by knits. the content objects here will always have a
 
3086
        # final newline
 
3087
        self._fulltext_contents = {}
 
3088
 
 
3089
        # Annotated lines of specific revisions
 
3090
        self._annotated_lines = {}
 
3091
 
 
3092
        # Track the raw data for nodes that we could not process yet.
 
3093
        # This maps the revision_id of the base to a list of children that will
 
3094
        # annotated from it.
 
3095
        self._pending_children = {}
 
3096
 
 
3097
        # Nodes which cannot be extracted
 
3098
        self._ghosts = set()
 
3099
 
 
3100
        # Track how many children this node has, so we know if we need to keep
 
3101
        # it
 
3102
        self._annotate_children = {}
 
3103
        self._compression_children = {}
 
3104
 
 
3105
        self._all_build_details = {}
 
3106
        # The children => parent revision_id graph
 
3107
        self._revision_id_graph = {}
 
3108
 
 
3109
        self._heads_provider = None
 
3110
 
 
3111
        self._nodes_to_keep_annotations = set()
 
3112
        self._generations_until_keep = 100
 
3113
 
 
3114
    def set_generations_until_keep(self, value):
 
3115
        """Set the number of generations before caching a node.
 
3116
 
 
3117
        Setting this to -1 will cache every merge node, setting this higher
 
3118
        will cache fewer nodes.
 
3119
        """
 
3120
        self._generations_until_keep = value
 
3121
 
 
3122
    def _add_fulltext_content(self, revision_id, content_obj):
 
3123
        self._fulltext_contents[revision_id] = content_obj
 
3124
        # TODO: jam 20080305 It might be good to check the sha1digest here
 
3125
        return content_obj.text()
 
3126
 
 
3127
    def _check_parents(self, child, nodes_to_annotate):
 
3128
        """Check if all parents have been processed.
 
3129
 
 
3130
        :param child: A tuple of (rev_id, parents, raw_content)
 
3131
        :param nodes_to_annotate: If child is ready, add it to
 
3132
            nodes_to_annotate, otherwise put it back in self._pending_children
 
3133
        """
 
3134
        for parent_id in child[1]:
 
3135
            if (parent_id not in self._annotated_lines):
 
3136
                # This parent is present, but another parent is missing
 
3137
                self._pending_children.setdefault(parent_id,
 
3138
                                                  []).append(child)
 
3139
                break
 
3140
        else:
 
3141
            # This one is ready to be processed
 
3142
            nodes_to_annotate.append(child)
 
3143
 
 
3144
    def _add_annotation(self, revision_id, fulltext, parent_ids,
 
3145
                        left_matching_blocks=None):
 
3146
        """Add an annotation entry.
 
3147
 
 
3148
        All parents should already have been annotated.
 
3149
        :return: A list of children that now have their parents satisfied.
 
3150
        """
 
3151
        a = self._annotated_lines
 
3152
        annotated_parent_lines = [a[p] for p in parent_ids]
 
3153
        annotated_lines = list(annotate.reannotate(annotated_parent_lines,
 
3154
            fulltext, revision_id, left_matching_blocks,
 
3155
            heads_provider=self._get_heads_provider()))
 
3156
        self._annotated_lines[revision_id] = annotated_lines
 
3157
        for p in parent_ids:
 
3158
            ann_children = self._annotate_children[p]
 
3159
            ann_children.remove(revision_id)
 
3160
            if (not ann_children
 
3161
                and p not in self._nodes_to_keep_annotations):
 
3162
                del self._annotated_lines[p]
 
3163
                del self._all_build_details[p]
 
3164
                if p in self._fulltext_contents:
 
3165
                    del self._fulltext_contents[p]
 
3166
        # Now that we've added this one, see if there are any pending
 
3167
        # deltas to be done, certainly this parent is finished
 
3168
        nodes_to_annotate = []
 
3169
        for child in self._pending_children.pop(revision_id, []):
 
3170
            self._check_parents(child, nodes_to_annotate)
 
3171
        return nodes_to_annotate
 
3172
 
 
3173
    def _get_build_graph(self, key):
 
3174
        """Get the graphs for building texts and annotations.
 
3175
 
 
3176
        The data you need for creating a full text may be different than the
 
3177
        data you need to annotate that text. (At a minimum, you need both
 
3178
        parents to create an annotation, but only need 1 parent to generate the
 
3179
        fulltext.)
 
3180
 
 
3181
        :return: A list of (key, index_memo) records, suitable for
 
3182
            passing to read_records_iter to start reading in the raw data fro/
 
3183
            the pack file.
 
3184
        """
 
3185
        if key in self._annotated_lines:
 
3186
            # Nothing to do
 
3187
            return []
 
3188
        pending = set([key])
 
3189
        records = []
 
3190
        generation = 0
 
3191
        kept_generation = 0
 
3192
        while pending:
 
3193
            # get all pending nodes
 
3194
            generation += 1
 
3195
            this_iteration = pending
 
3196
            build_details = self._knit._index.get_build_details(this_iteration)
 
3197
            self._all_build_details.update(build_details)
 
3198
            # new_nodes = self._knit._index._get_entries(this_iteration)
 
3199
            pending = set()
 
3200
            for key, details in build_details.iteritems():
 
3201
                (index_memo, compression_parent, parents,
 
3202
                 record_details) = details
 
3203
                self._revision_id_graph[key] = parents
 
3204
                records.append((key, index_memo))
 
3205
                # Do we actually need to check _annotated_lines?
 
3206
                pending.update(p for p in parents
 
3207
                                 if p not in self._all_build_details)
 
3208
                if compression_parent:
 
3209
                    self._compression_children.setdefault(compression_parent,
 
3210
                        []).append(key)
 
3211
                if parents:
 
3212
                    for parent in parents:
 
3213
                        self._annotate_children.setdefault(parent,
 
3214
                            []).append(key)
 
3215
                    num_gens = generation - kept_generation
 
3216
                    if ((num_gens >= self._generations_until_keep)
 
3217
                        and len(parents) > 1):
 
3218
                        kept_generation = generation
 
3219
                        self._nodes_to_keep_annotations.add(key)
 
3220
 
 
3221
            missing_versions = this_iteration.difference(build_details.keys())
 
3222
            self._ghosts.update(missing_versions)
 
3223
            for missing_version in missing_versions:
 
3224
                # add a key, no parents
 
3225
                self._revision_id_graph[missing_version] = ()
 
3226
                pending.discard(missing_version) # don't look for it
 
3227
        if self._ghosts.intersection(self._compression_children):
 
3228
            raise KnitCorrupt(
 
3229
                "We cannot have nodes which have a ghost compression parent:\n"
 
3230
                "ghosts: %r\n"
 
3231
                "compression children: %r"
 
3232
                % (self._ghosts, self._compression_children))
 
3233
        # Cleanout anything that depends on a ghost so that we don't wait for
 
3234
        # the ghost to show up
 
3235
        for node in self._ghosts:
 
3236
            if node in self._annotate_children:
 
3237
                # We won't be building this node
 
3238
                del self._annotate_children[node]
 
3239
        # Generally we will want to read the records in reverse order, because
 
3240
        # we find the parent nodes after the children
 
3241
        records.reverse()
 
3242
        return records
 
3243
 
 
3244
    def _annotate_records(self, records):
 
3245
        """Build the annotations for the listed records."""
 
3246
        # We iterate in the order read, rather than a strict order requested
 
3247
        # However, process what we can, and put off to the side things that
 
3248
        # still need parents, cleaning them up when those parents are
 
3249
        # processed.
 
3250
        for (rev_id, record,
 
3251
             digest) in self._knit._read_records_iter(records):
 
3252
            if rev_id in self._annotated_lines:
 
3253
                continue
 
3254
            parent_ids = self._revision_id_graph[rev_id]
 
3255
            parent_ids = [p for p in parent_ids if p not in self._ghosts]
 
3256
            details = self._all_build_details[rev_id]
 
3257
            (index_memo, compression_parent, parents,
 
3258
             record_details) = details
 
3259
            nodes_to_annotate = []
 
3260
            # TODO: Remove the punning between compression parents, and
 
3261
            #       parent_ids, we should be able to do this without assuming
 
3262
            #       the build order
 
3263
            if len(parent_ids) == 0:
 
3264
                # There are no parents for this node, so just add it
 
3265
                # TODO: This probably needs to be decoupled
 
3266
                fulltext_content, delta = self._knit._factory.parse_record(
 
3267
                    rev_id, record, record_details, None)
 
3268
                fulltext = self._add_fulltext_content(rev_id, fulltext_content)
 
3269
                nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
 
3270
                    parent_ids, left_matching_blocks=None))
 
3271
            else:
 
3272
                child = (rev_id, parent_ids, record)
 
3273
                # Check if all the parents are present
 
3274
                self._check_parents(child, nodes_to_annotate)
 
3275
            while nodes_to_annotate:
 
3276
                # Should we use a queue here instead of a stack?
 
3277
                (rev_id, parent_ids, record) = nodes_to_annotate.pop()
 
3278
                (index_memo, compression_parent, parents,
 
3279
                 record_details) = self._all_build_details[rev_id]
 
3280
                blocks = None
 
3281
                if compression_parent is not None:
 
3282
                    comp_children = self._compression_children[compression_parent]
 
3283
                    if rev_id not in comp_children:
 
3284
                        raise AssertionError("%r not in compression children %r"
 
3285
                            % (rev_id, comp_children))
 
3286
                    # If there is only 1 child, it is safe to reuse this
 
3287
                    # content
 
3288
                    reuse_content = (len(comp_children) == 1
 
3289
                        and compression_parent not in
 
3290
                            self._nodes_to_keep_annotations)
 
3291
                    if reuse_content:
 
3292
                        # Remove it from the cache since it will be changing
 
3293
                        parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
 
3294
                        # Make sure to copy the fulltext since it might be
 
3295
                        # modified
 
3296
                        parent_fulltext = list(parent_fulltext_content.text())
 
3297
                    else:
 
3298
                        parent_fulltext_content = self._fulltext_contents[compression_parent]
 
3299
                        parent_fulltext = parent_fulltext_content.text()
 
3300
                    comp_children.remove(rev_id)
 
3301
                    fulltext_content, delta = self._knit._factory.parse_record(
 
3302
                        rev_id, record, record_details,
 
3303
                        parent_fulltext_content,
 
3304
                        copy_base_content=(not reuse_content))
 
3305
                    fulltext = self._add_fulltext_content(rev_id,
 
3306
                                                          fulltext_content)
 
3307
                    if compression_parent == parent_ids[0]:
 
3308
                        # the compression_parent is the left parent, so we can
 
3309
                        # re-use the delta
 
3310
                        blocks = KnitContent.get_line_delta_blocks(delta,
 
3311
                                parent_fulltext, fulltext)
 
3312
                else:
 
3313
                    fulltext_content = self._knit._factory.parse_fulltext(
 
3314
                        record, rev_id)
 
3315
                    fulltext = self._add_fulltext_content(rev_id,
 
3316
                        fulltext_content)
 
3317
                nodes_to_annotate.extend(
 
3318
                    self._add_annotation(rev_id, fulltext, parent_ids,
 
3319
                                     left_matching_blocks=blocks))
 
3320
 
 
3321
    def _get_heads_provider(self):
 
3322
        """Create a heads provider for resolving ancestry issues."""
 
3323
        if self._heads_provider is not None:
 
3324
            return self._heads_provider
 
3325
        parent_provider = _mod_graph.DictParentsProvider(
 
3326
            self._revision_id_graph)
 
3327
        graph_obj = _mod_graph.Graph(parent_provider)
 
3328
        head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
 
3329
        self._heads_provider = head_cache
 
3330
        return head_cache
 
3331
 
 
3332
    def annotate(self, key):
 
3333
        """Return the annotated fulltext at the given key.
 
3334
 
 
3335
        :param key: The key to annotate.
 
3336
        """
 
3337
        if len(self._knit._fallback_vfs) > 0:
 
3338
            # stacked knits can't use the fast path at present.
 
3339
            return self._simple_annotate(key)
 
3340
        while True:
 
3341
            try:
 
3342
                records = self._get_build_graph(key)
 
3343
                if key in self._ghosts:
 
3344
                    raise errors.RevisionNotPresent(key, self._knit)
 
3345
                self._annotate_records(records)
 
3346
                return self._annotated_lines[key]
 
3347
            except errors.RetryWithNewPacks, e:
 
3348
                self._knit._access.reload_or_raise(e)
 
3349
                # The cached build_details are no longer valid
 
3350
                self._all_build_details.clear()
 
3351
 
 
3352
    def _simple_annotate(self, key):
 
3353
        """Return annotated fulltext, rediffing from the full texts.
 
3354
 
 
3355
        This is slow but makes no assumptions about the repository
 
3356
        being able to produce line deltas.
 
3357
        """
 
3358
        # TODO: this code generates a parent maps of present ancestors; it
 
3359
        # could be split out into a separate method, and probably should use
 
3360
        # iter_ancestry instead. -- mbp and robertc 20080704
 
3361
        graph = _mod_graph.Graph(self._knit)
 
3362
        head_cache = _mod_graph.FrozenHeadsCache(graph)
 
3363
        search = graph._make_breadth_first_searcher([key])
 
3364
        keys = set()
 
3365
        while True:
 
3366
            try:
 
3367
                present, ghosts = search.next_with_ghosts()
 
3368
            except StopIteration:
 
3369
                break
 
3370
            keys.update(present)
 
3371
        parent_map = self._knit.get_parent_map(keys)
 
3372
        parent_cache = {}
 
3373
        reannotate = annotate.reannotate
 
3374
        for record in self._knit.get_record_stream(keys, 'topological', True):
 
3375
            key = record.key
 
3376
            fulltext = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
 
3377
            parents = parent_map[key]
 
3378
            if parents is not None:
 
3379
                parent_lines = [parent_cache[parent] for parent in parent_map[key]]
 
3380
            else:
 
3381
                parent_lines = []
 
3382
            parent_cache[key] = list(
 
3383
                reannotate(parent_lines, fulltext, key, None, head_cache))
 
3384
        try:
 
3385
            return parent_cache[key]
 
3386
        except KeyError, e:
 
3387
            raise errors.RevisionNotPresent(key, self._knit)
 
3388
 
 
3389
 
 
3390
try:
 
3391
    from bzrlib._knit_load_data_c import _load_data_c as _load_data
 
3392
except ImportError:
 
3393
    from bzrlib._knit_load_data_py import _load_data_py as _load_data