/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: Frank Aspell
  • Date: 2009-02-22 16:54:02 UTC
  • mto: This revision was merged to the branch mainline in revision 4256.
  • Revision ID: frankaspell@googlemail.com-20090222165402-2myrucnu7er5w4ha
Fixing various typos

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 buffered_index_entries:
 
1539
            # There were index entries buffered at the end of the stream,
 
1540
            # So these need to be added (if the index supports holding such
 
1541
            # entries for later insertion)
 
1542
            for key in buffered_index_entries:
 
1543
                index_entries = buffered_index_entries[key]
 
1544
                self._index.add_records(index_entries,
 
1545
                    missing_compression_parents=True)
 
1546
 
 
1547
    def get_missing_compression_parent_keys(self):
 
1548
        """Return an iterable of keys of missing compression parents.
 
1549
 
 
1550
        Check this after calling insert_record_stream to find out if there are
 
1551
        any missing compression parents.  If there are, the records that
 
1552
        depend on them are not able to be inserted safely. For atomic
 
1553
        KnitVersionedFiles built on packs, the transaction should be aborted or
 
1554
        suspended - commit will fail at this point. Nonatomic knits will error
 
1555
        earlier because they have no staging area to put pending entries into.
 
1556
        """
 
1557
        return self._index.get_missing_compression_parents()
 
1558
 
 
1559
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
 
1560
        """Iterate over the lines in the versioned files from keys.
 
1561
 
 
1562
        This may return lines from other keys. Each item the returned
 
1563
        iterator yields is a tuple of a line and a text version that that line
 
1564
        is present in (not introduced in).
 
1565
 
 
1566
        Ordering of results is in whatever order is most suitable for the
 
1567
        underlying storage format.
 
1568
 
 
1569
        If a progress bar is supplied, it may be used to indicate progress.
 
1570
        The caller is responsible for cleaning up progress bars (because this
 
1571
        is an iterator).
 
1572
 
 
1573
        NOTES:
 
1574
         * Lines are normalised by the underlying store: they will all have \\n
 
1575
           terminators.
 
1576
         * Lines are returned in arbitrary order.
 
1577
         * If a requested key did not change any lines (or didn't have any
 
1578
           lines), it may not be mentioned at all in the result.
 
1579
 
 
1580
        :return: An iterator over (line, key).
 
1581
        """
 
1582
        if pb is None:
 
1583
            pb = progress.DummyProgress()
 
1584
        keys = set(keys)
 
1585
        total = len(keys)
 
1586
        done = False
 
1587
        while not done:
 
1588
            try:
 
1589
                # we don't care about inclusions, the caller cares.
 
1590
                # but we need to setup a list of records to visit.
 
1591
                # we need key, position, length
 
1592
                key_records = []
 
1593
                build_details = self._index.get_build_details(keys)
 
1594
                for key, details in build_details.iteritems():
 
1595
                    if key in keys:
 
1596
                        key_records.append((key, details[0]))
 
1597
                records_iter = enumerate(self._read_records_iter(key_records))
 
1598
                for (key_idx, (key, data, sha_value)) in records_iter:
 
1599
                    pb.update('Walking content.', key_idx, total)
 
1600
                    compression_parent = build_details[key][1]
 
1601
                    if compression_parent is None:
 
1602
                        # fulltext
 
1603
                        line_iterator = self._factory.get_fulltext_content(data)
 
1604
                    else:
 
1605
                        # Delta 
 
1606
                        line_iterator = self._factory.get_linedelta_content(data)
 
1607
                    # Now that we are yielding the data for this key, remove it
 
1608
                    # from the list
 
1609
                    keys.remove(key)
 
1610
                    # XXX: It might be more efficient to yield (key,
 
1611
                    # line_iterator) in the future. However for now, this is a
 
1612
                    # simpler change to integrate into the rest of the
 
1613
                    # codebase. RBC 20071110
 
1614
                    for line in line_iterator:
 
1615
                        yield line, key
 
1616
                done = True
 
1617
            except errors.RetryWithNewPacks, e:
 
1618
                self._access.reload_or_raise(e)
 
1619
        # If there are still keys we've not yet found, we look in the fallback
 
1620
        # vfs, and hope to find them there.  Note that if the keys are found
 
1621
        # but had no changes or no content, the fallback may not return
 
1622
        # anything.  
 
1623
        if keys and not self._fallback_vfs:
 
1624
            # XXX: strictly the second parameter is meant to be the file id
 
1625
            # but it's not easily accessible here.
 
1626
            raise RevisionNotPresent(keys, repr(self))
 
1627
        for source in self._fallback_vfs:
 
1628
            if not keys:
 
1629
                break
 
1630
            source_keys = set()
 
1631
            for line, key in source.iter_lines_added_or_present_in_keys(keys):
 
1632
                source_keys.add(key)
 
1633
                yield line, key
 
1634
            keys.difference_update(source_keys)
 
1635
        pb.update('Walking content.', total, total)
 
1636
 
 
1637
    def _make_line_delta(self, delta_seq, new_content):
 
1638
        """Generate a line delta from delta_seq and new_content."""
 
1639
        diff_hunks = []
 
1640
        for op in delta_seq.get_opcodes():
 
1641
            if op[0] == 'equal':
 
1642
                continue
 
1643
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
 
1644
        return diff_hunks
 
1645
 
 
1646
    def _merge_annotations(self, content, parents, parent_texts={},
 
1647
                           delta=None, annotated=None,
 
1648
                           left_matching_blocks=None):
 
1649
        """Merge annotations for content and generate deltas.
 
1650
        
 
1651
        This is done by comparing the annotations based on changes to the text
 
1652
        and generating a delta on the resulting full texts. If annotations are
 
1653
        not being created then a simple delta is created.
 
1654
        """
 
1655
        if left_matching_blocks is not None:
 
1656
            delta_seq = diff._PrematchedMatcher(left_matching_blocks)
 
1657
        else:
 
1658
            delta_seq = None
 
1659
        if annotated:
 
1660
            for parent_key in parents:
 
1661
                merge_content = self._get_content(parent_key, parent_texts)
 
1662
                if (parent_key == parents[0] and delta_seq is not None):
 
1663
                    seq = delta_seq
 
1664
                else:
 
1665
                    seq = patiencediff.PatienceSequenceMatcher(
 
1666
                        None, merge_content.text(), content.text())
 
1667
                for i, j, n in seq.get_matching_blocks():
 
1668
                    if n == 0:
 
1669
                        continue
 
1670
                    # this copies (origin, text) pairs across to the new
 
1671
                    # content for any line that matches the last-checked
 
1672
                    # parent.
 
1673
                    content._lines[j:j+n] = merge_content._lines[i:i+n]
 
1674
            # XXX: Robert says the following block is a workaround for a
 
1675
            # now-fixed bug and it can probably be deleted. -- mbp 20080618
 
1676
            if content._lines and content._lines[-1][1][-1] != '\n':
 
1677
                # The copied annotation was from a line without a trailing EOL,
 
1678
                # reinstate one for the content object, to ensure correct
 
1679
                # serialization.
 
1680
                line = content._lines[-1][1] + '\n'
 
1681
                content._lines[-1] = (content._lines[-1][0], line)
 
1682
        if delta:
 
1683
            if delta_seq is None:
 
1684
                reference_content = self._get_content(parents[0], parent_texts)
 
1685
                new_texts = content.text()
 
1686
                old_texts = reference_content.text()
 
1687
                delta_seq = patiencediff.PatienceSequenceMatcher(
 
1688
                                                 None, old_texts, new_texts)
 
1689
            return self._make_line_delta(delta_seq, content)
 
1690
 
 
1691
    def _parse_record(self, version_id, data):
 
1692
        """Parse an original format knit record.
 
1693
 
 
1694
        These have the last element of the key only present in the stored data.
 
1695
        """
 
1696
        rec, record_contents = self._parse_record_unchecked(data)
 
1697
        self._check_header_version(rec, version_id)
 
1698
        return record_contents, rec[3]
 
1699
 
 
1700
    def _parse_record_header(self, key, raw_data):
 
1701
        """Parse a record header for consistency.
 
1702
 
 
1703
        :return: the header and the decompressor stream.
 
1704
                 as (stream, header_record)
 
1705
        """
 
1706
        df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
 
1707
        try:
 
1708
            # Current serialise
 
1709
            rec = self._check_header(key, df.readline())
 
1710
        except Exception, e:
 
1711
            raise KnitCorrupt(self,
 
1712
                              "While reading {%s} got %s(%s)"
 
1713
                              % (key, e.__class__.__name__, str(e)))
 
1714
        return df, rec
 
1715
 
 
1716
    def _parse_record_unchecked(self, data):
 
1717
        # profiling notes:
 
1718
        # 4168 calls in 2880 217 internal
 
1719
        # 4168 calls to _parse_record_header in 2121
 
1720
        # 4168 calls to readlines in 330
 
1721
        df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(data))
 
1722
        try:
 
1723
            record_contents = df.readlines()
 
1724
        except Exception, e:
 
1725
            raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
 
1726
                (data, e.__class__.__name__, str(e)))
 
1727
        header = record_contents.pop(0)
 
1728
        rec = self._split_header(header)
 
1729
        last_line = record_contents.pop()
 
1730
        if len(record_contents) != int(rec[2]):
 
1731
            raise KnitCorrupt(self,
 
1732
                              'incorrect number of lines %s != %s'
 
1733
                              ' for version {%s} %s'
 
1734
                              % (len(record_contents), int(rec[2]),
 
1735
                                 rec[1], record_contents))
 
1736
        if last_line != 'end %s\n' % rec[1]:
 
1737
            raise KnitCorrupt(self,
 
1738
                              'unexpected version end line %r, wanted %r' 
 
1739
                              % (last_line, rec[1]))
 
1740
        df.close()
 
1741
        return rec, record_contents
 
1742
 
 
1743
    def _read_records_iter(self, records):
 
1744
        """Read text records from data file and yield result.
 
1745
 
 
1746
        The result will be returned in whatever is the fastest to read.
 
1747
        Not by the order requested. Also, multiple requests for the same
 
1748
        record will only yield 1 response.
 
1749
        :param records: A list of (key, access_memo) entries
 
1750
        :return: Yields (key, contents, digest) in the order
 
1751
                 read, not the order requested
 
1752
        """
 
1753
        if not records:
 
1754
            return
 
1755
 
 
1756
        # XXX: This smells wrong, IO may not be getting ordered right.
 
1757
        needed_records = sorted(set(records), key=operator.itemgetter(1))
 
1758
        if not needed_records:
 
1759
            return
 
1760
 
 
1761
        # The transport optimizes the fetching as well 
 
1762
        # (ie, reads continuous ranges.)
 
1763
        raw_data = self._access.get_raw_records(
 
1764
            [index_memo for key, index_memo in needed_records])
 
1765
 
 
1766
        for (key, index_memo), data in \
 
1767
                izip(iter(needed_records), raw_data):
 
1768
            content, digest = self._parse_record(key[-1], data)
 
1769
            yield key, content, digest
 
1770
 
 
1771
    def _read_records_iter_raw(self, records):
 
1772
        """Read text records from data file and yield raw data.
 
1773
 
 
1774
        This unpacks enough of the text record to validate the id is
 
1775
        as expected but thats all.
 
1776
 
 
1777
        Each item the iterator yields is (key, bytes,
 
1778
            expected_sha1_of_full_text).
 
1779
        """
 
1780
        for key, data in self._read_records_iter_unchecked(records):
 
1781
            # validate the header (note that we can only use the suffix in
 
1782
            # current knit records).
 
1783
            df, rec = self._parse_record_header(key, data)
 
1784
            df.close()
 
1785
            yield key, data, rec[3]
 
1786
 
 
1787
    def _read_records_iter_unchecked(self, records):
 
1788
        """Read text records from data file and yield raw data.
 
1789
 
 
1790
        No validation is done.
 
1791
 
 
1792
        Yields tuples of (key, data).
 
1793
        """
 
1794
        # setup an iterator of the external records:
 
1795
        # uses readv so nice and fast we hope.
 
1796
        if len(records):
 
1797
            # grab the disk data needed.
 
1798
            needed_offsets = [index_memo for key, index_memo
 
1799
                                           in records]
 
1800
            raw_records = self._access.get_raw_records(needed_offsets)
 
1801
 
 
1802
        for key, index_memo in records:
 
1803
            data = raw_records.next()
 
1804
            yield key, data
 
1805
 
 
1806
    def _record_to_data(self, key, digest, lines, dense_lines=None):
 
1807
        """Convert key, digest, lines into a raw data block.
 
1808
        
 
1809
        :param key: The key of the record. Currently keys are always serialised
 
1810
            using just the trailing component.
 
1811
        :param dense_lines: The bytes of lines but in a denser form. For
 
1812
            instance, if lines is a list of 1000 bytestrings each ending in \n,
 
1813
            dense_lines may be a list with one line in it, containing all the
 
1814
            1000's lines and their \n's. Using dense_lines if it is already
 
1815
            known is a win because the string join to create bytes in this
 
1816
            function spends less time resizing the final string.
 
1817
        :return: (len, a StringIO instance with the raw data ready to read.)
 
1818
        """
 
1819
        # Note: using a string copy here increases memory pressure with e.g.
 
1820
        # ISO's, but it is about 3 seconds faster on a 1.2Ghz intel machine
 
1821
        # when doing the initial commit of a mozilla tree. RBC 20070921
 
1822
        bytes = ''.join(chain(
 
1823
            ["version %s %d %s\n" % (key[-1],
 
1824
                                     len(lines),
 
1825
                                     digest)],
 
1826
            dense_lines or lines,
 
1827
            ["end %s\n" % key[-1]]))
 
1828
        if type(bytes) != str:
 
1829
            raise AssertionError(
 
1830
                'data must be plain bytes was %s' % type(bytes))
 
1831
        if lines and lines[-1][-1] != '\n':
 
1832
            raise ValueError('corrupt lines value %r' % lines)
 
1833
        compressed_bytes = tuned_gzip.bytes_to_gzip(bytes)
 
1834
        return len(compressed_bytes), compressed_bytes
 
1835
 
 
1836
    def _split_header(self, line):
 
1837
        rec = line.split()
 
1838
        if len(rec) != 4:
 
1839
            raise KnitCorrupt(self,
 
1840
                              'unexpected number of elements in record header')
 
1841
        return rec
 
1842
 
 
1843
    def keys(self):
 
1844
        """See VersionedFiles.keys."""
 
1845
        if 'evil' in debug.debug_flags:
 
1846
            trace.mutter_callsite(2, "keys scales with size of history")
 
1847
        sources = [self._index] + self._fallback_vfs
 
1848
        result = set()
 
1849
        for source in sources:
 
1850
            result.update(source.keys())
 
1851
        return result
 
1852
 
 
1853
 
 
1854
class _ContentMapGenerator(object):
 
1855
    """Generate texts or expose raw deltas for a set of texts."""
 
1856
 
 
1857
    def _get_content(self, key):
 
1858
        """Get the content object for key."""
 
1859
        # Note that _get_content is only called when the _ContentMapGenerator
 
1860
        # has been constructed with just one key requested for reconstruction.
 
1861
        if key in self.nonlocal_keys:
 
1862
            record = self.get_record_stream().next()
 
1863
            # Create a content object on the fly
 
1864
            lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
 
1865
            return PlainKnitContent(lines, record.key)
 
1866
        else:
 
1867
            # local keys we can ask for directly
 
1868
            return self._get_one_work(key)
 
1869
 
 
1870
    def get_record_stream(self):
 
1871
        """Get a record stream for the keys requested during __init__."""
 
1872
        for record in self._work():
 
1873
            yield record
 
1874
 
 
1875
    def _work(self):
 
1876
        """Produce maps of text and KnitContents as dicts.
 
1877
        
 
1878
        :return: (text_map, content_map) where text_map contains the texts for
 
1879
            the requested versions and content_map contains the KnitContents.
 
1880
        """
 
1881
        # NB: By definition we never need to read remote sources unless texts
 
1882
        # are requested from them: we don't delta across stores - and we
 
1883
        # explicitly do not want to to prevent data loss situations.
 
1884
        if self.global_map is None:
 
1885
            self.global_map = self.vf.get_parent_map(self.keys)
 
1886
        nonlocal_keys = self.nonlocal_keys
 
1887
 
 
1888
        missing_keys = set(nonlocal_keys)
 
1889
        # Read from remote versioned file instances and provide to our caller.
 
1890
        for source in self.vf._fallback_vfs:
 
1891
            if not missing_keys:
 
1892
                break
 
1893
            # Loop over fallback repositories asking them for texts - ignore
 
1894
            # any missing from a particular fallback.
 
1895
            for record in source.get_record_stream(missing_keys,
 
1896
                'unordered', True):
 
1897
                if record.storage_kind == 'absent':
 
1898
                    # Not in thie particular stream, may be in one of the
 
1899
                    # other fallback vfs objects.
 
1900
                    continue
 
1901
                missing_keys.remove(record.key)
 
1902
                yield record
 
1903
 
 
1904
        self._raw_record_map = self.vf._get_record_map_unparsed(self.keys,
 
1905
            allow_missing=True)
 
1906
        first = True
 
1907
        for key in self.keys:
 
1908
            if key in self.nonlocal_keys:
 
1909
                continue
 
1910
            yield LazyKnitContentFactory(key, self.global_map[key], self, first)
 
1911
            first = False
 
1912
 
 
1913
    def _get_one_work(self, requested_key):
 
1914
        # Now, if we have calculated everything already, just return the
 
1915
        # desired text.
 
1916
        if requested_key in self._contents_map:
 
1917
            return self._contents_map[requested_key]
 
1918
        # To simplify things, parse everything at once - code that wants one text
 
1919
        # probably wants them all.
 
1920
        # FUTURE: This function could be improved for the 'extract many' case
 
1921
        # by tracking each component and only doing the copy when the number of
 
1922
        # children than need to apply delta's to it is > 1 or it is part of the
 
1923
        # final output.
 
1924
        multiple_versions = len(self.keys) != 1
 
1925
        if self._record_map is None:
 
1926
            self._record_map = self.vf._raw_map_to_record_map(
 
1927
                self._raw_record_map)
 
1928
        record_map = self._record_map
 
1929
        # raw_record_map is key:
 
1930
        # Have read and parsed records at this point. 
 
1931
        for key in self.keys:
 
1932
            if key in self.nonlocal_keys:
 
1933
                # already handled
 
1934
                continue
 
1935
            components = []
 
1936
            cursor = key
 
1937
            while cursor is not None:
 
1938
                try:
 
1939
                    record, record_details, digest, next = record_map[cursor]
 
1940
                except KeyError:
 
1941
                    raise RevisionNotPresent(cursor, self)
 
1942
                components.append((cursor, record, record_details, digest))
 
1943
                cursor = next
 
1944
                if cursor in self._contents_map:
 
1945
                    # no need to plan further back
 
1946
                    components.append((cursor, None, None, None))
 
1947
                    break
 
1948
 
 
1949
            content = None
 
1950
            for (component_id, record, record_details,
 
1951
                 digest) in reversed(components):
 
1952
                if component_id in self._contents_map:
 
1953
                    content = self._contents_map[component_id]
 
1954
                else:
 
1955
                    content, delta = self._factory.parse_record(key[-1],
 
1956
                        record, record_details, content,
 
1957
                        copy_base_content=multiple_versions)
 
1958
                    if multiple_versions:
 
1959
                        self._contents_map[component_id] = content
 
1960
 
 
1961
            # digest here is the digest from the last applied component.
 
1962
            text = content.text()
 
1963
            actual_sha = sha_strings(text)
 
1964
            if actual_sha != digest:
 
1965
                raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
 
1966
        if multiple_versions:
 
1967
            return self._contents_map[requested_key]
 
1968
        else:
 
1969
            return content
 
1970
 
 
1971
    def _wire_bytes(self):
 
1972
        """Get the bytes to put on the wire for 'key'.
 
1973
 
 
1974
        The first collection of bytes asked for returns the serialised
 
1975
        raw_record_map and the additional details (key, parent) for key.
 
1976
        Subsequent calls return just the additional details (key, parent).
 
1977
        The wire storage_kind given for the first key is 'knit-delta-closure',
 
1978
        For subsequent keys it is 'knit-delta-closure-ref'.
 
1979
 
 
1980
        :param key: A key from the content generator.
 
1981
        :return: Bytes to put on the wire.
 
1982
        """
 
1983
        lines = []
 
1984
        # kind marker for dispatch on the far side,
 
1985
        lines.append('knit-delta-closure')
 
1986
        # Annotated or not
 
1987
        if self.vf._factory.annotated:
 
1988
            lines.append('annotated')
 
1989
        else:
 
1990
            lines.append('')
 
1991
        # then the list of keys
 
1992
        lines.append('\t'.join(['\x00'.join(key) for key in self.keys
 
1993
            if key not in self.nonlocal_keys]))
 
1994
        # then the _raw_record_map in serialised form:
 
1995
        map_byte_list = []
 
1996
        # for each item in the map:
 
1997
        # 1 line with key
 
1998
        # 1 line with parents if the key is to be yielded (None: for None, '' for ())
 
1999
        # one line with method
 
2000
        # one line with noeol
 
2001
        # one line with next ('' for None)
 
2002
        # one line with byte count of the record bytes
 
2003
        # the record bytes
 
2004
        for key, (record_bytes, (method, noeol), next) in \
 
2005
            self._raw_record_map.iteritems():
 
2006
            key_bytes = '\x00'.join(key)
 
2007
            parents = self.global_map.get(key, None)
 
2008
            if parents is None:
 
2009
                parent_bytes = 'None:'
 
2010
            else:
 
2011
                parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
 
2012
            method_bytes = method
 
2013
            if noeol:
 
2014
                noeol_bytes = "T"
 
2015
            else:
 
2016
                noeol_bytes = "F"
 
2017
            if next:
 
2018
                next_bytes = '\x00'.join(next)
 
2019
            else:
 
2020
                next_bytes = ''
 
2021
            map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
 
2022
                key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
 
2023
                len(record_bytes), record_bytes))
 
2024
        map_bytes = ''.join(map_byte_list)
 
2025
        lines.append(map_bytes)
 
2026
        bytes = '\n'.join(lines)
 
2027
        return bytes
 
2028
 
 
2029
 
 
2030
class _VFContentMapGenerator(_ContentMapGenerator):
 
2031
    """Content map generator reading from a VersionedFiles object."""
 
2032
 
 
2033
    def __init__(self, versioned_files, keys, nonlocal_keys=None,
 
2034
        global_map=None, raw_record_map=None):
 
2035
        """Create a _ContentMapGenerator.
 
2036
        
 
2037
        :param versioned_files: The versioned files that the texts are being
 
2038
            extracted from.
 
2039
        :param keys: The keys to produce content maps for.
 
2040
        :param nonlocal_keys: An iterable of keys(possibly intersecting keys)
 
2041
            which are known to not be in this knit, but rather in one of the
 
2042
            fallback knits.
 
2043
        :param global_map: The result of get_parent_map(keys) (or a supermap).
 
2044
            This is required if get_record_stream() is to be used.
 
2045
        :param raw_record_map: A unparsed raw record map to use for answering
 
2046
            contents.
 
2047
        """
 
2048
        # The vf to source data from
 
2049
        self.vf = versioned_files
 
2050
        # The keys desired
 
2051
        self.keys = list(keys)
 
2052
        # Keys known to be in fallback vfs objects
 
2053
        if nonlocal_keys is None:
 
2054
            self.nonlocal_keys = set()
 
2055
        else:
 
2056
            self.nonlocal_keys = frozenset(nonlocal_keys)
 
2057
        # Parents data for keys to be returned in get_record_stream
 
2058
        self.global_map = global_map
 
2059
        # The chunked lists for self.keys in text form
 
2060
        self._text_map = {}
 
2061
        # A cache of KnitContent objects used in extracting texts.
 
2062
        self._contents_map = {}
 
2063
        # All the knit records needed to assemble the requested keys as full
 
2064
        # texts.
 
2065
        self._record_map = None
 
2066
        if raw_record_map is None:
 
2067
            self._raw_record_map = self.vf._get_record_map_unparsed(keys,
 
2068
                allow_missing=True)
 
2069
        else:
 
2070
            self._raw_record_map = raw_record_map
 
2071
        # the factory for parsing records
 
2072
        self._factory = self.vf._factory
 
2073
 
 
2074
 
 
2075
class _NetworkContentMapGenerator(_ContentMapGenerator):
 
2076
    """Content map generator sourced from a network stream."""
 
2077
 
 
2078
    def __init__(self, bytes, line_end):
 
2079
        """Construct a _NetworkContentMapGenerator from a bytes block."""
 
2080
        self._bytes = bytes
 
2081
        self.global_map = {}
 
2082
        self._raw_record_map = {}
 
2083
        self._contents_map = {}
 
2084
        self._record_map = None
 
2085
        self.nonlocal_keys = []
 
2086
        # Get access to record parsing facilities
 
2087
        self.vf = KnitVersionedFiles(None, None)
 
2088
        start = line_end
 
2089
        # Annotated or not
 
2090
        line_end = bytes.find('\n', start)
 
2091
        line = bytes[start:line_end]
 
2092
        start = line_end + 1
 
2093
        if line == 'annotated':
 
2094
            self._factory = KnitAnnotateFactory()
 
2095
        else:
 
2096
            self._factory = KnitPlainFactory()
 
2097
        # list of keys to emit in get_record_stream
 
2098
        line_end = bytes.find('\n', start)
 
2099
        line = bytes[start:line_end]
 
2100
        start = line_end + 1
 
2101
        self.keys = [
 
2102
            tuple(segment.split('\x00')) for segment in line.split('\t')
 
2103
            if segment]
 
2104
        # now a loop until the end. XXX: It would be nice if this was just a
 
2105
        # bunch of the same records as get_record_stream(..., False) gives, but
 
2106
        # there is a decent sized gap stopping that at the moment.
 
2107
        end = len(bytes)
 
2108
        while start < end:
 
2109
            # 1 line with key
 
2110
            line_end = bytes.find('\n', start)
 
2111
            key = tuple(bytes[start:line_end].split('\x00'))
 
2112
            start = line_end + 1
 
2113
            # 1 line with parents (None: for None, '' for ())
 
2114
            line_end = bytes.find('\n', start)
 
2115
            line = bytes[start:line_end]
 
2116
            if line == 'None:':
 
2117
                parents = None
 
2118
            else:
 
2119
                parents = tuple(
 
2120
                    [tuple(segment.split('\x00')) for segment in line.split('\t')
 
2121
                     if segment])
 
2122
            self.global_map[key] = parents
 
2123
            start = line_end + 1
 
2124
            # one line with method
 
2125
            line_end = bytes.find('\n', start)
 
2126
            line = bytes[start:line_end]
 
2127
            method = line
 
2128
            start = line_end + 1
 
2129
            # one line with noeol
 
2130
            line_end = bytes.find('\n', start)
 
2131
            line = bytes[start:line_end]
 
2132
            noeol = line == "T"
 
2133
            start = line_end + 1
 
2134
            # one line with next ('' for None)
 
2135
            line_end = bytes.find('\n', start)
 
2136
            line = bytes[start:line_end]
 
2137
            if not line:
 
2138
                next = None
 
2139
            else:
 
2140
                next = tuple(bytes[start:line_end].split('\x00'))
 
2141
            start = line_end + 1
 
2142
            # one line with byte count of the record bytes
 
2143
            line_end = bytes.find('\n', start)
 
2144
            line = bytes[start:line_end]
 
2145
            count = int(line)
 
2146
            start = line_end + 1
 
2147
            # the record bytes
 
2148
            record_bytes = bytes[start:start+count]
 
2149
            start = start + count
 
2150
            # put it in the map
 
2151
            self._raw_record_map[key] = (record_bytes, (method, noeol), next)
 
2152
 
 
2153
    def get_record_stream(self):
 
2154
        """Get a record stream for for keys requested by the bytestream."""
 
2155
        first = True
 
2156
        for key in self.keys:
 
2157
            yield LazyKnitContentFactory(key, self.global_map[key], self, first)
 
2158
            first = False
 
2159
 
 
2160
    def _wire_bytes(self):
 
2161
        return self._bytes
 
2162
 
 
2163
 
 
2164
class _KndxIndex(object):
 
2165
    """Manages knit index files
 
2166
 
 
2167
    The index is kept in memory and read on startup, to enable
 
2168
    fast lookups of revision information.  The cursor of the index
 
2169
    file is always pointing to the end, making it easy to append
 
2170
    entries.
 
2171
 
 
2172
    _cache is a cache for fast mapping from version id to a Index
 
2173
    object.
 
2174
 
 
2175
    _history is a cache for fast mapping from indexes to version ids.
 
2176
 
 
2177
    The index data format is dictionary compressed when it comes to
 
2178
    parent references; a index entry may only have parents that with a
 
2179
    lover index number.  As a result, the index is topological sorted.
 
2180
 
 
2181
    Duplicate entries may be written to the index for a single version id
 
2182
    if this is done then the latter one completely replaces the former:
 
2183
    this allows updates to correct version and parent information. 
 
2184
    Note that the two entries may share the delta, and that successive
 
2185
    annotations and references MUST point to the first entry.
 
2186
 
 
2187
    The index file on disc contains a header, followed by one line per knit
 
2188
    record. The same revision can be present in an index file more than once.
 
2189
    The first occurrence gets assigned a sequence number starting from 0. 
 
2190
    
 
2191
    The format of a single line is
 
2192
    REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
 
2193
    REVISION_ID is a utf8-encoded revision id
 
2194
    FLAGS is a comma separated list of flags about the record. Values include 
 
2195
        no-eol, line-delta, fulltext.
 
2196
    BYTE_OFFSET is the ascii representation of the byte offset in the data file
 
2197
        that the the compressed data starts at.
 
2198
    LENGTH is the ascii representation of the length of the data file.
 
2199
    PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
 
2200
        REVISION_ID.
 
2201
    PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
 
2202
        revision id already in the knit that is a parent of REVISION_ID.
 
2203
    The ' :' marker is the end of record marker.
 
2204
    
 
2205
    partial writes:
 
2206
    when a write is interrupted to the index file, it will result in a line
 
2207
    that does not end in ' :'. If the ' :' is not present at the end of a line,
 
2208
    or at the end of the file, then the record that is missing it will be
 
2209
    ignored by the parser.
 
2210
 
 
2211
    When writing new records to the index file, the data is preceded by '\n'
 
2212
    to ensure that records always start on new lines even if the last write was
 
2213
    interrupted. As a result its normal for the last line in the index to be
 
2214
    missing a trailing newline. One can be added with no harmful effects.
 
2215
 
 
2216
    :ivar _kndx_cache: dict from prefix to the old state of KnitIndex objects,
 
2217
        where prefix is e.g. the (fileid,) for .texts instances or () for
 
2218
        constant-mapped things like .revisions, and the old state is
 
2219
        tuple(history_vector, cache_dict).  This is used to prevent having an
 
2220
        ABI change with the C extension that reads .kndx files.
 
2221
    """
 
2222
 
 
2223
    HEADER = "# bzr knit index 8\n"
 
2224
 
 
2225
    def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
 
2226
        """Create a _KndxIndex on transport using mapper."""
 
2227
        self._transport = transport
 
2228
        self._mapper = mapper
 
2229
        self._get_scope = get_scope
 
2230
        self._allow_writes = allow_writes
 
2231
        self._is_locked = is_locked
 
2232
        self._reset_cache()
 
2233
        self.has_graph = True
 
2234
 
 
2235
    def add_records(self, records, random_id=False, missing_compression_parents=False):
 
2236
        """Add multiple records to the index.
 
2237
        
 
2238
        :param records: a list of tuples:
 
2239
                         (key, options, access_memo, parents).
 
2240
        :param random_id: If True the ids being added were randomly generated
 
2241
            and no check for existence will be performed.
 
2242
        :param missing_compression_parents: If True the records being added are
 
2243
            only compressed against texts already in the index (or inside
 
2244
            records). If False the records all refer to unavailable texts (or
 
2245
            texts inside records) as compression parents.
 
2246
        """
 
2247
        if missing_compression_parents:
 
2248
            # It might be nice to get the edge of the records. But keys isn't
 
2249
            # _wrong_.
 
2250
            keys = sorted(record[0] for record in records)
 
2251
            raise errors.RevisionNotPresent(keys, self)
 
2252
        paths = {}
 
2253
        for record in records:
 
2254
            key = record[0]
 
2255
            prefix = key[:-1]
 
2256
            path = self._mapper.map(key) + '.kndx'
 
2257
            path_keys = paths.setdefault(path, (prefix, []))
 
2258
            path_keys[1].append(record)
 
2259
        for path in sorted(paths):
 
2260
            prefix, path_keys = paths[path]
 
2261
            self._load_prefixes([prefix])
 
2262
            lines = []
 
2263
            orig_history = self._kndx_cache[prefix][1][:]
 
2264
            orig_cache = self._kndx_cache[prefix][0].copy()
 
2265
 
 
2266
            try:
 
2267
                for key, options, (_, pos, size), parents in path_keys:
 
2268
                    if parents is None:
 
2269
                        # kndx indices cannot be parentless.
 
2270
                        parents = ()
 
2271
                    line = "\n%s %s %s %s %s :" % (
 
2272
                        key[-1], ','.join(options), pos, size,
 
2273
                        self._dictionary_compress(parents))
 
2274
                    if type(line) != str:
 
2275
                        raise AssertionError(
 
2276
                            'data must be utf8 was %s' % type(line))
 
2277
                    lines.append(line)
 
2278
                    self._cache_key(key, options, pos, size, parents)
 
2279
                if len(orig_history):
 
2280
                    self._transport.append_bytes(path, ''.join(lines))
 
2281
                else:
 
2282
                    self._init_index(path, lines)
 
2283
            except:
 
2284
                # If any problems happen, restore the original values and re-raise
 
2285
                self._kndx_cache[prefix] = (orig_cache, orig_history)
 
2286
                raise
 
2287
 
 
2288
    def scan_unvalidated_index(self, graph_index):
 
2289
        """See _KnitGraphIndex.scan_unvalidated_index."""
 
2290
        # Because kndx files do not support atomic insertion via separate index
 
2291
        # files, they do not support this method.
 
2292
        raise NotImplementedError(self.scan_unvalidated_index)
 
2293
 
 
2294
    def get_missing_compression_parents(self):
 
2295
        """See _KnitGraphIndex.get_missing_compression_parents."""
 
2296
        # Because kndx files do not support atomic insertion via separate index
 
2297
        # files, they do not support this method.
 
2298
        raise NotImplementedError(self.get_missing_compression_parents)
 
2299
    
 
2300
    def _cache_key(self, key, options, pos, size, parent_keys):
 
2301
        """Cache a version record in the history array and index cache.
 
2302
 
 
2303
        This is inlined into _load_data for performance. KEEP IN SYNC.
 
2304
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
 
2305
         indexes).
 
2306
        """
 
2307
        prefix = key[:-1]
 
2308
        version_id = key[-1]
 
2309
        # last-element only for compatibilty with the C load_data.
 
2310
        parents = tuple(parent[-1] for parent in parent_keys)
 
2311
        for parent in parent_keys:
 
2312
            if parent[:-1] != prefix:
 
2313
                raise ValueError("mismatched prefixes for %r, %r" % (
 
2314
                    key, parent_keys))
 
2315
        cache, history = self._kndx_cache[prefix]
 
2316
        # only want the _history index to reference the 1st index entry
 
2317
        # for version_id
 
2318
        if version_id not in cache:
 
2319
            index = len(history)
 
2320
            history.append(version_id)
 
2321
        else:
 
2322
            index = cache[version_id][5]
 
2323
        cache[version_id] = (version_id,
 
2324
                                   options,
 
2325
                                   pos,
 
2326
                                   size,
 
2327
                                   parents,
 
2328
                                   index)
 
2329
 
 
2330
    def check_header(self, fp):
 
2331
        line = fp.readline()
 
2332
        if line == '':
 
2333
            # An empty file can actually be treated as though the file doesn't
 
2334
            # exist yet.
 
2335
            raise errors.NoSuchFile(self)
 
2336
        if line != self.HEADER:
 
2337
            raise KnitHeaderError(badline=line, filename=self)
 
2338
 
 
2339
    def _check_read(self):
 
2340
        if not self._is_locked():
 
2341
            raise errors.ObjectNotLocked(self)
 
2342
        if self._get_scope() != self._scope:
 
2343
            self._reset_cache()
 
2344
 
 
2345
    def _check_write_ok(self):
 
2346
        """Assert if not writes are permitted."""
 
2347
        if not self._is_locked():
 
2348
            raise errors.ObjectNotLocked(self)
 
2349
        if self._get_scope() != self._scope:
 
2350
            self._reset_cache()
 
2351
        if self._mode != 'w':
 
2352
            raise errors.ReadOnlyObjectDirtiedError(self)
 
2353
 
 
2354
    def get_build_details(self, keys):
 
2355
        """Get the method, index_memo and compression parent for keys.
 
2356
 
 
2357
        Ghosts are omitted from the result.
 
2358
 
 
2359
        :param keys: An iterable of keys.
 
2360
        :return: A dict of key:(index_memo, compression_parent, parents,
 
2361
            record_details).
 
2362
            index_memo
 
2363
                opaque structure to pass to read_records to extract the raw
 
2364
                data
 
2365
            compression_parent
 
2366
                Content that this record is built upon, may be None
 
2367
            parents
 
2368
                Logical parents of this node
 
2369
            record_details
 
2370
                extra information about the content which needs to be passed to
 
2371
                Factory.parse_record
 
2372
        """
 
2373
        parent_map = self.get_parent_map(keys)
 
2374
        result = {}
 
2375
        for key in keys:
 
2376
            if key not in parent_map:
 
2377
                continue # Ghost
 
2378
            method = self.get_method(key)
 
2379
            parents = parent_map[key]
 
2380
            if method == 'fulltext':
 
2381
                compression_parent = None
 
2382
            else:
 
2383
                compression_parent = parents[0]
 
2384
            noeol = 'no-eol' in self.get_options(key)
 
2385
            index_memo = self.get_position(key)
 
2386
            result[key] = (index_memo, compression_parent,
 
2387
                                  parents, (method, noeol))
 
2388
        return result
 
2389
 
 
2390
    def get_method(self, key):
 
2391
        """Return compression method of specified key."""
 
2392
        options = self.get_options(key)
 
2393
        if 'fulltext' in options:
 
2394
            return 'fulltext'
 
2395
        elif 'line-delta' in options:
 
2396
            return 'line-delta'
 
2397
        else:
 
2398
            raise errors.KnitIndexUnknownMethod(self, options)
 
2399
 
 
2400
    def get_options(self, key):
 
2401
        """Return a list representing options.
 
2402
 
 
2403
        e.g. ['foo', 'bar']
 
2404
        """
 
2405
        prefix, suffix = self._split_key(key)
 
2406
        self._load_prefixes([prefix])
 
2407
        try:
 
2408
            return self._kndx_cache[prefix][0][suffix][1]
 
2409
        except KeyError:
 
2410
            raise RevisionNotPresent(key, self)
 
2411
 
 
2412
    def get_parent_map(self, keys):
 
2413
        """Get a map of the parents of keys.
 
2414
 
 
2415
        :param keys: The keys to look up parents for.
 
2416
        :return: A mapping from keys to parents. Absent keys are absent from
 
2417
            the mapping.
 
2418
        """
 
2419
        # Parse what we need to up front, this potentially trades off I/O
 
2420
        # locality (.kndx and .knit in the same block group for the same file
 
2421
        # id) for less checking in inner loops.
 
2422
        prefixes = set(key[:-1] for key in keys)
 
2423
        self._load_prefixes(prefixes)
 
2424
        result = {}
 
2425
        for key in keys:
 
2426
            prefix = key[:-1]
 
2427
            try:
 
2428
                suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
 
2429
            except KeyError:
 
2430
                pass
 
2431
            else:
 
2432
                result[key] = tuple(prefix + (suffix,) for
 
2433
                    suffix in suffix_parents)
 
2434
        return result
 
2435
 
 
2436
    def get_position(self, key):
 
2437
        """Return details needed to access the version.
 
2438
        
 
2439
        :return: a tuple (key, data position, size) to hand to the access
 
2440
            logic to get the record.
 
2441
        """
 
2442
        prefix, suffix = self._split_key(key)
 
2443
        self._load_prefixes([prefix])
 
2444
        entry = self._kndx_cache[prefix][0][suffix]
 
2445
        return key, entry[2], entry[3]
 
2446
 
 
2447
    has_key = _mod_index._has_key_from_parent_map
 
2448
    
 
2449
    def _init_index(self, path, extra_lines=[]):
 
2450
        """Initialize an index."""
 
2451
        sio = StringIO()
 
2452
        sio.write(self.HEADER)
 
2453
        sio.writelines(extra_lines)
 
2454
        sio.seek(0)
 
2455
        self._transport.put_file_non_atomic(path, sio,
 
2456
                            create_parent_dir=True)
 
2457
                           # self._create_parent_dir)
 
2458
                           # mode=self._file_mode,
 
2459
                           # dir_mode=self._dir_mode)
 
2460
 
 
2461
    def keys(self):
 
2462
        """Get all the keys in the collection.
 
2463
        
 
2464
        The keys are not ordered.
 
2465
        """
 
2466
        result = set()
 
2467
        # Identify all key prefixes.
 
2468
        # XXX: A bit hacky, needs polish.
 
2469
        if type(self._mapper) == ConstantMapper:
 
2470
            prefixes = [()]
 
2471
        else:
 
2472
            relpaths = set()
 
2473
            for quoted_relpath in self._transport.iter_files_recursive():
 
2474
                path, ext = os.path.splitext(quoted_relpath)
 
2475
                relpaths.add(path)
 
2476
            prefixes = [self._mapper.unmap(path) for path in relpaths]
 
2477
        self._load_prefixes(prefixes)
 
2478
        for prefix in prefixes:
 
2479
            for suffix in self._kndx_cache[prefix][1]:
 
2480
                result.add(prefix + (suffix,))
 
2481
        return result
 
2482
    
 
2483
    def _load_prefixes(self, prefixes):
 
2484
        """Load the indices for prefixes."""
 
2485
        self._check_read()
 
2486
        for prefix in prefixes:
 
2487
            if prefix not in self._kndx_cache:
 
2488
                # the load_data interface writes to these variables.
 
2489
                self._cache = {}
 
2490
                self._history = []
 
2491
                self._filename = prefix
 
2492
                try:
 
2493
                    path = self._mapper.map(prefix) + '.kndx'
 
2494
                    fp = self._transport.get(path)
 
2495
                    try:
 
2496
                        # _load_data may raise NoSuchFile if the target knit is
 
2497
                        # completely empty.
 
2498
                        _load_data(self, fp)
 
2499
                    finally:
 
2500
                        fp.close()
 
2501
                    self._kndx_cache[prefix] = (self._cache, self._history)
 
2502
                    del self._cache
 
2503
                    del self._filename
 
2504
                    del self._history
 
2505
                except NoSuchFile:
 
2506
                    self._kndx_cache[prefix] = ({}, [])
 
2507
                    if type(self._mapper) == ConstantMapper:
 
2508
                        # preserve behaviour for revisions.kndx etc.
 
2509
                        self._init_index(path)
 
2510
                    del self._cache
 
2511
                    del self._filename
 
2512
                    del self._history
 
2513
 
 
2514
    missing_keys = _mod_index._missing_keys_from_parent_map
 
2515
 
 
2516
    def _partition_keys(self, keys):
 
2517
        """Turn keys into a dict of prefix:suffix_list."""
 
2518
        result = {}
 
2519
        for key in keys:
 
2520
            prefix_keys = result.setdefault(key[:-1], [])
 
2521
            prefix_keys.append(key[-1])
 
2522
        return result
 
2523
 
 
2524
    def _dictionary_compress(self, keys):
 
2525
        """Dictionary compress keys.
 
2526
        
 
2527
        :param keys: The keys to generate references to.
 
2528
        :return: A string representation of keys. keys which are present are
 
2529
            dictionary compressed, and others are emitted as fulltext with a
 
2530
            '.' prefix.
 
2531
        """
 
2532
        if not keys:
 
2533
            return ''
 
2534
        result_list = []
 
2535
        prefix = keys[0][:-1]
 
2536
        cache = self._kndx_cache[prefix][0]
 
2537
        for key in keys:
 
2538
            if key[:-1] != prefix:
 
2539
                # kndx indices cannot refer across partitioned storage.
 
2540
                raise ValueError("mismatched prefixes for %r" % keys)
 
2541
            if key[-1] in cache:
 
2542
                # -- inlined lookup() --
 
2543
                result_list.append(str(cache[key[-1]][5]))
 
2544
                # -- end lookup () --
 
2545
            else:
 
2546
                result_list.append('.' + key[-1])
 
2547
        return ' '.join(result_list)
 
2548
 
 
2549
    def _reset_cache(self):
 
2550
        # Possibly this should be a LRU cache. A dictionary from key_prefix to
 
2551
        # (cache_dict, history_vector) for parsed kndx files.
 
2552
        self._kndx_cache = {}
 
2553
        self._scope = self._get_scope()
 
2554
        allow_writes = self._allow_writes()
 
2555
        if allow_writes:
 
2556
            self._mode = 'w'
 
2557
        else:
 
2558
            self._mode = 'r'
 
2559
 
 
2560
    def _sort_keys_by_io(self, keys, positions):
 
2561
        """Figure out an optimal order to read the records for the given keys.
 
2562
 
 
2563
        Sort keys, grouped by index and sorted by position.
 
2564
 
 
2565
        :param keys: A list of keys whose records we want to read. This will be
 
2566
            sorted 'in-place'.
 
2567
        :param positions: A dict, such as the one returned by
 
2568
            _get_components_positions()
 
2569
        :return: None
 
2570
        """
 
2571
        def get_sort_key(key):
 
2572
            index_memo = positions[key][1]
 
2573
            # Group by prefix and position. index_memo[0] is the key, so it is
 
2574
            # (file_id, revision_id) and we don't want to sort on revision_id,
 
2575
            # index_memo[1] is the position, and index_memo[2] is the size,
 
2576
            # which doesn't matter for the sort
 
2577
            return index_memo[0][:-1], index_memo[1]
 
2578
        return keys.sort(key=get_sort_key)
 
2579
 
 
2580
    def _split_key(self, key):
 
2581
        """Split key into a prefix and suffix."""
 
2582
        return key[:-1], key[-1]
 
2583
 
 
2584
 
 
2585
class _KnitGraphIndex(object):
 
2586
    """A KnitVersionedFiles index layered on GraphIndex."""
 
2587
 
 
2588
    def __init__(self, graph_index, is_locked, deltas=False, parents=True,
 
2589
        add_callback=None):
 
2590
        """Construct a KnitGraphIndex on a graph_index.
 
2591
 
 
2592
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
 
2593
        :param is_locked: A callback to check whether the object should answer
 
2594
            queries.
 
2595
        :param deltas: Allow delta-compressed records.
 
2596
        :param parents: If True, record knits parents, if not do not record 
 
2597
            parents.
 
2598
        :param add_callback: If not None, allow additions to the index and call
 
2599
            this callback with a list of added GraphIndex nodes:
 
2600
            [(node, value, node_refs), ...]
 
2601
        :param is_locked: A callback, returns True if the index is locked and
 
2602
            thus usable.
 
2603
        """
 
2604
        self._add_callback = add_callback
 
2605
        self._graph_index = graph_index
 
2606
        self._deltas = deltas
 
2607
        self._parents = parents
 
2608
        if deltas and not parents:
 
2609
            # XXX: TODO: Delta tree and parent graph should be conceptually
 
2610
            # separate.
 
2611
            raise KnitCorrupt(self, "Cannot do delta compression without "
 
2612
                "parent tracking.")
 
2613
        self.has_graph = parents
 
2614
        self._is_locked = is_locked
 
2615
        self._missing_compression_parents = set()
 
2616
 
 
2617
    def __repr__(self):
 
2618
        return "%s(%r)" % (self.__class__.__name__, self._graph_index)
 
2619
 
 
2620
    def add_records(self, records, random_id=False,
 
2621
        missing_compression_parents=False):
 
2622
        """Add multiple records to the index.
 
2623
        
 
2624
        This function does not insert data into the Immutable GraphIndex
 
2625
        backing the KnitGraphIndex, instead it prepares data for insertion by
 
2626
        the caller and checks that it is safe to insert then calls
 
2627
        self._add_callback with the prepared GraphIndex nodes.
 
2628
 
 
2629
        :param records: a list of tuples:
 
2630
                         (key, options, access_memo, parents).
 
2631
        :param random_id: If True the ids being added were randomly generated
 
2632
            and no check for existence will be performed.
 
2633
        :param missing_compression_parents: If True the records being added are
 
2634
            only compressed against texts already in the index (or inside
 
2635
            records). If False the records all refer to unavailable texts (or
 
2636
            texts inside records) as compression parents.
 
2637
        """
 
2638
        if not self._add_callback:
 
2639
            raise errors.ReadOnlyError(self)
 
2640
        # we hope there are no repositories with inconsistent parentage
 
2641
        # anymore.
 
2642
 
 
2643
        keys = {}
 
2644
        compression_parents = set()
 
2645
        for (key, options, access_memo, parents) in records:
 
2646
            if self._parents:
 
2647
                parents = tuple(parents)
 
2648
            index, pos, size = access_memo
 
2649
            if 'no-eol' in options:
 
2650
                value = 'N'
 
2651
            else:
 
2652
                value = ' '
 
2653
            value += "%d %d" % (pos, size)
 
2654
            if not self._deltas:
 
2655
                if 'line-delta' in options:
 
2656
                    raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
 
2657
            if self._parents:
 
2658
                if self._deltas:
 
2659
                    if 'line-delta' in options:
 
2660
                        node_refs = (parents, (parents[0],))
 
2661
                        if missing_compression_parents:
 
2662
                            compression_parents.add(parents[0])
 
2663
                    else:
 
2664
                        node_refs = (parents, ())
 
2665
                else:
 
2666
                    node_refs = (parents, )
 
2667
            else:
 
2668
                if parents:
 
2669
                    raise KnitCorrupt(self, "attempt to add node with parents "
 
2670
                        "in parentless index.")
 
2671
                node_refs = ()
 
2672
            keys[key] = (value, node_refs)
 
2673
        # check for dups
 
2674
        if not random_id:
 
2675
            present_nodes = self._get_entries(keys)
 
2676
            for (index, key, value, node_refs) in present_nodes:
 
2677
                if (value[0] != keys[key][0][0] or
 
2678
                    node_refs[:1] != keys[key][1][:1]):
 
2679
                    raise KnitCorrupt(self, "inconsistent details in add_records"
 
2680
                        ": %s %s" % ((value, node_refs), keys[key]))
 
2681
                del keys[key]
 
2682
        result = []
 
2683
        if self._parents:
 
2684
            for key, (value, node_refs) in keys.iteritems():
 
2685
                result.append((key, value, node_refs))
 
2686
        else:
 
2687
            for key, (value, node_refs) in keys.iteritems():
 
2688
                result.append((key, value))
 
2689
        self._add_callback(result)
 
2690
        if missing_compression_parents:
 
2691
            # This may appear to be incorrect (it does not check for
 
2692
            # compression parents that are in the existing graph index),
 
2693
            # but such records won't have been buffered, so this is
 
2694
            # actually correct: every entry when
 
2695
            # missing_compression_parents==True either has a missing parent, or
 
2696
            # a parent that is one of the keys in records.
 
2697
            compression_parents.difference_update(keys)
 
2698
            self._missing_compression_parents.update(compression_parents)
 
2699
        # Adding records may have satisfied missing compression parents.
 
2700
        self._missing_compression_parents.difference_update(keys)
 
2701
        
 
2702
    def scan_unvalidated_index(self, graph_index):
 
2703
        """Inform this _KnitGraphIndex that there is an unvalidated index.
 
2704
 
 
2705
        This allows this _KnitGraphIndex to keep track of any missing
 
2706
        compression parents we may want to have filled in to make those
 
2707
        indices valid.
 
2708
 
 
2709
        :param graph_index: A GraphIndex
 
2710
        """
 
2711
        if self._deltas:
 
2712
            new_missing = graph_index.external_references(ref_list_num=1)
 
2713
            new_missing.difference_update(self.get_parent_map(new_missing))
 
2714
            self._missing_compression_parents.update(new_missing)
 
2715
 
 
2716
    def get_missing_compression_parents(self):
 
2717
        """Return the keys of missing compression parents.
 
2718
 
 
2719
        Missing compression parents occur when a record stream was missing
 
2720
        basis texts, or a index was scanned that had missing basis texts.
 
2721
        """
 
2722
        return frozenset(self._missing_compression_parents)
 
2723
 
 
2724
    def _check_read(self):
 
2725
        """raise if reads are not permitted."""
 
2726
        if not self._is_locked():
 
2727
            raise errors.ObjectNotLocked(self)
 
2728
 
 
2729
    def _check_write_ok(self):
 
2730
        """Assert if writes are not permitted."""
 
2731
        if not self._is_locked():
 
2732
            raise errors.ObjectNotLocked(self)
 
2733
 
 
2734
    def _compression_parent(self, an_entry):
 
2735
        # return the key that an_entry is compressed against, or None
 
2736
        # Grab the second parent list (as deltas implies parents currently)
 
2737
        compression_parents = an_entry[3][1]
 
2738
        if not compression_parents:
 
2739
            return None
 
2740
        if len(compression_parents) != 1:
 
2741
            raise AssertionError(
 
2742
                "Too many compression parents: %r" % compression_parents)
 
2743
        return compression_parents[0]
 
2744
 
 
2745
    def get_build_details(self, keys):
 
2746
        """Get the method, index_memo and compression parent for version_ids.
 
2747
 
 
2748
        Ghosts are omitted from the result.
 
2749
 
 
2750
        :param keys: An iterable of keys.
 
2751
        :return: A dict of key:
 
2752
            (index_memo, compression_parent, parents, record_details).
 
2753
            index_memo
 
2754
                opaque structure to pass to read_records to extract the raw
 
2755
                data
 
2756
            compression_parent
 
2757
                Content that this record is built upon, may be None
 
2758
            parents
 
2759
                Logical parents of this node
 
2760
            record_details
 
2761
                extra information about the content which needs to be passed to
 
2762
                Factory.parse_record
 
2763
        """
 
2764
        self._check_read()
 
2765
        result = {}
 
2766
        entries = self._get_entries(keys, False)
 
2767
        for entry in entries:
 
2768
            key = entry[1]
 
2769
            if not self._parents:
 
2770
                parents = ()
 
2771
            else:
 
2772
                parents = entry[3][0]
 
2773
            if not self._deltas:
 
2774
                compression_parent_key = None
 
2775
            else:
 
2776
                compression_parent_key = self._compression_parent(entry)
 
2777
            noeol = (entry[2][0] == 'N')
 
2778
            if compression_parent_key:
 
2779
                method = 'line-delta'
 
2780
            else:
 
2781
                method = 'fulltext'
 
2782
            result[key] = (self._node_to_position(entry),
 
2783
                                  compression_parent_key, parents,
 
2784
                                  (method, noeol))
 
2785
        return result
 
2786
 
 
2787
    def _get_entries(self, keys, check_present=False):
 
2788
        """Get the entries for keys.
 
2789
        
 
2790
        :param keys: An iterable of index key tuples.
 
2791
        """
 
2792
        keys = set(keys)
 
2793
        found_keys = set()
 
2794
        if self._parents:
 
2795
            for node in self._graph_index.iter_entries(keys):
 
2796
                yield node
 
2797
                found_keys.add(node[1])
 
2798
        else:
 
2799
            # adapt parentless index to the rest of the code.
 
2800
            for node in self._graph_index.iter_entries(keys):
 
2801
                yield node[0], node[1], node[2], ()
 
2802
                found_keys.add(node[1])
 
2803
        if check_present:
 
2804
            missing_keys = keys.difference(found_keys)
 
2805
            if missing_keys:
 
2806
                raise RevisionNotPresent(missing_keys.pop(), self)
 
2807
 
 
2808
    def get_method(self, key):
 
2809
        """Return compression method of specified key."""
 
2810
        return self._get_method(self._get_node(key))
 
2811
 
 
2812
    def _get_method(self, node):
 
2813
        if not self._deltas:
 
2814
            return 'fulltext'
 
2815
        if self._compression_parent(node):
 
2816
            return 'line-delta'
 
2817
        else:
 
2818
            return 'fulltext'
 
2819
 
 
2820
    def _get_node(self, key):
 
2821
        try:
 
2822
            return list(self._get_entries([key]))[0]
 
2823
        except IndexError:
 
2824
            raise RevisionNotPresent(key, self)
 
2825
 
 
2826
    def get_options(self, key):
 
2827
        """Return a list representing options.
 
2828
 
 
2829
        e.g. ['foo', 'bar']
 
2830
        """
 
2831
        node = self._get_node(key)
 
2832
        options = [self._get_method(node)]
 
2833
        if node[2][0] == 'N':
 
2834
            options.append('no-eol')
 
2835
        return options
 
2836
 
 
2837
    def get_parent_map(self, keys):
 
2838
        """Get a map of the parents of keys.
 
2839
 
 
2840
        :param keys: The keys to look up parents for.
 
2841
        :return: A mapping from keys to parents. Absent keys are absent from
 
2842
            the mapping.
 
2843
        """
 
2844
        self._check_read()
 
2845
        nodes = self._get_entries(keys)
 
2846
        result = {}
 
2847
        if self._parents:
 
2848
            for node in nodes:
 
2849
                result[node[1]] = node[3][0]
 
2850
        else:
 
2851
            for node in nodes:
 
2852
                result[node[1]] = None
 
2853
        return result
 
2854
 
 
2855
    def get_position(self, key):
 
2856
        """Return details needed to access the version.
 
2857
        
 
2858
        :return: a tuple (index, data position, size) to hand to the access
 
2859
            logic to get the record.
 
2860
        """
 
2861
        node = self._get_node(key)
 
2862
        return self._node_to_position(node)
 
2863
 
 
2864
    has_key = _mod_index._has_key_from_parent_map
 
2865
 
 
2866
    def keys(self):
 
2867
        """Get all the keys in the collection.
 
2868
        
 
2869
        The keys are not ordered.
 
2870
        """
 
2871
        self._check_read()
 
2872
        return [node[1] for node in self._graph_index.iter_all_entries()]
 
2873
    
 
2874
    missing_keys = _mod_index._missing_keys_from_parent_map
 
2875
 
 
2876
    def _node_to_position(self, node):
 
2877
        """Convert an index value to position details."""
 
2878
        bits = node[2][1:].split(' ')
 
2879
        return node[0], int(bits[0]), int(bits[1])
 
2880
 
 
2881
    def _sort_keys_by_io(self, keys, positions):
 
2882
        """Figure out an optimal order to read the records for the given keys.
 
2883
 
 
2884
        Sort keys, grouped by index and sorted by position.
 
2885
 
 
2886
        :param keys: A list of keys whose records we want to read. This will be
 
2887
            sorted 'in-place'.
 
2888
        :param positions: A dict, such as the one returned by
 
2889
            _get_components_positions()
 
2890
        :return: None
 
2891
        """
 
2892
        def get_index_memo(key):
 
2893
            # index_memo is at offset [1]. It is made up of (GraphIndex,
 
2894
            # position, size). GI is an object, which will be unique for each
 
2895
            # pack file. This causes us to group by pack file, then sort by
 
2896
            # position. Size doesn't matter, but it isn't worth breaking up the
 
2897
            # tuple.
 
2898
            return positions[key][1]
 
2899
        return keys.sort(key=get_index_memo)
 
2900
 
 
2901
 
 
2902
class _KnitKeyAccess(object):
 
2903
    """Access to records in .knit files."""
 
2904
 
 
2905
    def __init__(self, transport, mapper):
 
2906
        """Create a _KnitKeyAccess with transport and mapper.
 
2907
 
 
2908
        :param transport: The transport the access object is rooted at.
 
2909
        :param mapper: The mapper used to map keys to .knit files.
 
2910
        """
 
2911
        self._transport = transport
 
2912
        self._mapper = mapper
 
2913
 
 
2914
    def add_raw_records(self, key_sizes, raw_data):
 
2915
        """Add raw knit bytes to a storage area.
 
2916
 
 
2917
        The data is spooled to the container writer in one bytes-record per
 
2918
        raw data item.
 
2919
 
 
2920
        :param sizes: An iterable of tuples containing the key and size of each
 
2921
            raw data segment.
 
2922
        :param raw_data: A bytestring containing the data.
 
2923
        :return: A list of memos to retrieve the record later. Each memo is an
 
2924
            opaque index memo. For _KnitKeyAccess the memo is (key, pos,
 
2925
            length), where the key is the record key.
 
2926
        """
 
2927
        if type(raw_data) != str:
 
2928
            raise AssertionError(
 
2929
                'data must be plain bytes was %s' % type(raw_data))
 
2930
        result = []
 
2931
        offset = 0
 
2932
        # TODO: This can be tuned for writing to sftp and other servers where
 
2933
        # append() is relatively expensive by grouping the writes to each key
 
2934
        # prefix.
 
2935
        for key, size in key_sizes:
 
2936
            path = self._mapper.map(key)
 
2937
            try:
 
2938
                base = self._transport.append_bytes(path + '.knit',
 
2939
                    raw_data[offset:offset+size])
 
2940
            except errors.NoSuchFile:
 
2941
                self._transport.mkdir(osutils.dirname(path))
 
2942
                base = self._transport.append_bytes(path + '.knit',
 
2943
                    raw_data[offset:offset+size])
 
2944
            # if base == 0:
 
2945
            # chmod.
 
2946
            offset += size
 
2947
            result.append((key, base, size))
 
2948
        return result
 
2949
 
 
2950
    def get_raw_records(self, memos_for_retrieval):
 
2951
        """Get the raw bytes for a records.
 
2952
 
 
2953
        :param memos_for_retrieval: An iterable containing the access memo for
 
2954
            retrieving the bytes.
 
2955
        :return: An iterator over the bytes of the records.
 
2956
        """
 
2957
        # first pass, group into same-index request to minimise readv's issued.
 
2958
        request_lists = []
 
2959
        current_prefix = None
 
2960
        for (key, offset, length) in memos_for_retrieval:
 
2961
            if current_prefix == key[:-1]:
 
2962
                current_list.append((offset, length))
 
2963
            else:
 
2964
                if current_prefix is not None:
 
2965
                    request_lists.append((current_prefix, current_list))
 
2966
                current_prefix = key[:-1]
 
2967
                current_list = [(offset, length)]
 
2968
        # handle the last entry
 
2969
        if current_prefix is not None:
 
2970
            request_lists.append((current_prefix, current_list))
 
2971
        for prefix, read_vector in request_lists:
 
2972
            path = self._mapper.map(prefix) + '.knit'
 
2973
            for pos, data in self._transport.readv(path, read_vector):
 
2974
                yield data
 
2975
 
 
2976
 
 
2977
class _DirectPackAccess(object):
 
2978
    """Access to data in one or more packs with less translation."""
 
2979
 
 
2980
    def __init__(self, index_to_packs, reload_func=None):
 
2981
        """Create a _DirectPackAccess object.
 
2982
 
 
2983
        :param index_to_packs: A dict mapping index objects to the transport
 
2984
            and file names for obtaining data.
 
2985
        :param reload_func: A function to call if we determine that the pack
 
2986
            files have moved and we need to reload our caches. See
 
2987
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
 
2988
        """
 
2989
        self._container_writer = None
 
2990
        self._write_index = None
 
2991
        self._indices = index_to_packs
 
2992
        self._reload_func = reload_func
 
2993
 
 
2994
    def add_raw_records(self, key_sizes, raw_data):
 
2995
        """Add raw knit bytes to a storage area.
 
2996
 
 
2997
        The data is spooled to the container writer in one bytes-record per
 
2998
        raw data item.
 
2999
 
 
3000
        :param sizes: An iterable of tuples containing the key and size of each
 
3001
            raw data segment.
 
3002
        :param raw_data: A bytestring containing the data.
 
3003
        :return: A list of memos to retrieve the record later. Each memo is an
 
3004
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
 
3005
            length), where the index field is the write_index object supplied
 
3006
            to the PackAccess object.
 
3007
        """
 
3008
        if type(raw_data) != str:
 
3009
            raise AssertionError(
 
3010
                'data must be plain bytes was %s' % type(raw_data))
 
3011
        result = []
 
3012
        offset = 0
 
3013
        for key, size in key_sizes:
 
3014
            p_offset, p_length = self._container_writer.add_bytes_record(
 
3015
                raw_data[offset:offset+size], [])
 
3016
            offset += size
 
3017
            result.append((self._write_index, p_offset, p_length))
 
3018
        return result
 
3019
 
 
3020
    def get_raw_records(self, memos_for_retrieval):
 
3021
        """Get the raw bytes for a records.
 
3022
 
 
3023
        :param memos_for_retrieval: An iterable containing the (index, pos, 
 
3024
            length) memo for retrieving the bytes. The Pack access method
 
3025
            looks up the pack to use for a given record in its index_to_pack
 
3026
            map.
 
3027
        :return: An iterator over the bytes of the records.
 
3028
        """
 
3029
        # first pass, group into same-index requests
 
3030
        request_lists = []
 
3031
        current_index = None
 
3032
        for (index, offset, length) in memos_for_retrieval:
 
3033
            if current_index == index:
 
3034
                current_list.append((offset, length))
 
3035
            else:
 
3036
                if current_index is not None:
 
3037
                    request_lists.append((current_index, current_list))
 
3038
                current_index = index
 
3039
                current_list = [(offset, length)]
 
3040
        # handle the last entry
 
3041
        if current_index is not None:
 
3042
            request_lists.append((current_index, current_list))
 
3043
        for index, offsets in request_lists:
 
3044
            try:
 
3045
                transport, path = self._indices[index]
 
3046
            except KeyError:
 
3047
                # A KeyError here indicates that someone has triggered an index
 
3048
                # reload, and this index has gone missing, we need to start
 
3049
                # over.
 
3050
                if self._reload_func is None:
 
3051
                    # If we don't have a _reload_func there is nothing that can
 
3052
                    # be done
 
3053
                    raise
 
3054
                raise errors.RetryWithNewPacks(index,
 
3055
                                               reload_occurred=True,
 
3056
                                               exc_info=sys.exc_info())
 
3057
            try:
 
3058
                reader = pack.make_readv_reader(transport, path, offsets)
 
3059
                for names, read_func in reader.iter_records():
 
3060
                    yield read_func(None)
 
3061
            except errors.NoSuchFile:
 
3062
                # A NoSuchFile error indicates that a pack file has gone
 
3063
                # missing on disk, we need to trigger a reload, and start over.
 
3064
                if self._reload_func is None:
 
3065
                    raise
 
3066
                raise errors.RetryWithNewPacks(transport.abspath(path),
 
3067
                                               reload_occurred=False,
 
3068
                                               exc_info=sys.exc_info())
 
3069
 
 
3070
    def set_writer(self, writer, index, transport_packname):
 
3071
        """Set a writer to use for adding data."""
 
3072
        if index is not None:
 
3073
            self._indices[index] = transport_packname
 
3074
        self._container_writer = writer
 
3075
        self._write_index = index
 
3076
 
 
3077
    def reload_or_raise(self, retry_exc):
 
3078
        """Try calling the reload function, or re-raise the original exception.
 
3079
 
 
3080
        This should be called after _DirectPackAccess raises a
 
3081
        RetryWithNewPacks exception. This function will handle the common logic
 
3082
        of determining when the error is fatal versus being temporary.
 
3083
        It will also make sure that the original exception is raised, rather
 
3084
        than the RetryWithNewPacks exception.
 
3085
 
 
3086
        If this function returns, then the calling function should retry
 
3087
        whatever operation was being performed. Otherwise an exception will
 
3088
        be raised.
 
3089
 
 
3090
        :param retry_exc: A RetryWithNewPacks exception.
 
3091
        """
 
3092
        is_error = False
 
3093
        if self._reload_func is None:
 
3094
            is_error = True
 
3095
        elif not self._reload_func():
 
3096
            # The reload claimed that nothing changed
 
3097
            if not retry_exc.reload_occurred:
 
3098
                # If there wasn't an earlier reload, then we really were
 
3099
                # expecting to find changes. We didn't find them, so this is a
 
3100
                # hard error
 
3101
                is_error = True
 
3102
        if is_error:
 
3103
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
 
3104
            raise exc_class, exc_value, exc_traceback
 
3105
 
 
3106
 
 
3107
# Deprecated, use PatienceSequenceMatcher instead
 
3108
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
 
3109
 
 
3110
 
 
3111
def annotate_knit(knit, revision_id):
 
3112
    """Annotate a knit with no cached annotations.
 
3113
 
 
3114
    This implementation is for knits with no cached annotations.
 
3115
    It will work for knits with cached annotations, but this is not
 
3116
    recommended.
 
3117
    """
 
3118
    annotator = _KnitAnnotator(knit)
 
3119
    return iter(annotator.annotate(revision_id))
 
3120
 
 
3121
 
 
3122
class _KnitAnnotator(object):
 
3123
    """Build up the annotations for a text."""
 
3124
 
 
3125
    def __init__(self, knit):
 
3126
        self._knit = knit
 
3127
 
 
3128
        # Content objects, differs from fulltexts because of how final newlines
 
3129
        # are treated by knits. the content objects here will always have a
 
3130
        # final newline
 
3131
        self._fulltext_contents = {}
 
3132
 
 
3133
        # Annotated lines of specific revisions
 
3134
        self._annotated_lines = {}
 
3135
 
 
3136
        # Track the raw data for nodes that we could not process yet.
 
3137
        # This maps the revision_id of the base to a list of children that will
 
3138
        # annotated from it.
 
3139
        self._pending_children = {}
 
3140
 
 
3141
        # Nodes which cannot be extracted
 
3142
        self._ghosts = set()
 
3143
 
 
3144
        # Track how many children this node has, so we know if we need to keep
 
3145
        # it
 
3146
        self._annotate_children = {}
 
3147
        self._compression_children = {}
 
3148
 
 
3149
        self._all_build_details = {}
 
3150
        # The children => parent revision_id graph
 
3151
        self._revision_id_graph = {}
 
3152
 
 
3153
        self._heads_provider = None
 
3154
 
 
3155
        self._nodes_to_keep_annotations = set()
 
3156
        self._generations_until_keep = 100
 
3157
 
 
3158
    def set_generations_until_keep(self, value):
 
3159
        """Set the number of generations before caching a node.
 
3160
 
 
3161
        Setting this to -1 will cache every merge node, setting this higher
 
3162
        will cache fewer nodes.
 
3163
        """
 
3164
        self._generations_until_keep = value
 
3165
 
 
3166
    def _add_fulltext_content(self, revision_id, content_obj):
 
3167
        self._fulltext_contents[revision_id] = content_obj
 
3168
        # TODO: jam 20080305 It might be good to check the sha1digest here
 
3169
        return content_obj.text()
 
3170
 
 
3171
    def _check_parents(self, child, nodes_to_annotate):
 
3172
        """Check if all parents have been processed.
 
3173
 
 
3174
        :param child: A tuple of (rev_id, parents, raw_content)
 
3175
        :param nodes_to_annotate: If child is ready, add it to
 
3176
            nodes_to_annotate, otherwise put it back in self._pending_children
 
3177
        """
 
3178
        for parent_id in child[1]:
 
3179
            if (parent_id not in self._annotated_lines):
 
3180
                # This parent is present, but another parent is missing
 
3181
                self._pending_children.setdefault(parent_id,
 
3182
                                                  []).append(child)
 
3183
                break
 
3184
        else:
 
3185
            # This one is ready to be processed
 
3186
            nodes_to_annotate.append(child)
 
3187
 
 
3188
    def _add_annotation(self, revision_id, fulltext, parent_ids,
 
3189
                        left_matching_blocks=None):
 
3190
        """Add an annotation entry.
 
3191
 
 
3192
        All parents should already have been annotated.
 
3193
        :return: A list of children that now have their parents satisfied.
 
3194
        """
 
3195
        a = self._annotated_lines
 
3196
        annotated_parent_lines = [a[p] for p in parent_ids]
 
3197
        annotated_lines = list(annotate.reannotate(annotated_parent_lines,
 
3198
            fulltext, revision_id, left_matching_blocks,
 
3199
            heads_provider=self._get_heads_provider()))
 
3200
        self._annotated_lines[revision_id] = annotated_lines
 
3201
        for p in parent_ids:
 
3202
            ann_children = self._annotate_children[p]
 
3203
            ann_children.remove(revision_id)
 
3204
            if (not ann_children
 
3205
                and p not in self._nodes_to_keep_annotations):
 
3206
                del self._annotated_lines[p]
 
3207
                del self._all_build_details[p]
 
3208
                if p in self._fulltext_contents:
 
3209
                    del self._fulltext_contents[p]
 
3210
        # Now that we've added this one, see if there are any pending
 
3211
        # deltas to be done, certainly this parent is finished
 
3212
        nodes_to_annotate = []
 
3213
        for child in self._pending_children.pop(revision_id, []):
 
3214
            self._check_parents(child, nodes_to_annotate)
 
3215
        return nodes_to_annotate
 
3216
 
 
3217
    def _get_build_graph(self, key):
 
3218
        """Get the graphs for building texts and annotations.
 
3219
 
 
3220
        The data you need for creating a full text may be different than the
 
3221
        data you need to annotate that text. (At a minimum, you need both
 
3222
        parents to create an annotation, but only need 1 parent to generate the
 
3223
        fulltext.)
 
3224
 
 
3225
        :return: A list of (key, index_memo) records, suitable for
 
3226
            passing to read_records_iter to start reading in the raw data fro/
 
3227
            the pack file.
 
3228
        """
 
3229
        if key in self._annotated_lines:
 
3230
            # Nothing to do
 
3231
            return []
 
3232
        pending = set([key])
 
3233
        records = []
 
3234
        generation = 0
 
3235
        kept_generation = 0
 
3236
        while pending:
 
3237
            # get all pending nodes
 
3238
            generation += 1
 
3239
            this_iteration = pending
 
3240
            build_details = self._knit._index.get_build_details(this_iteration)
 
3241
            self._all_build_details.update(build_details)
 
3242
            # new_nodes = self._knit._index._get_entries(this_iteration)
 
3243
            pending = set()
 
3244
            for key, details in build_details.iteritems():
 
3245
                (index_memo, compression_parent, parents,
 
3246
                 record_details) = details
 
3247
                self._revision_id_graph[key] = parents
 
3248
                records.append((key, index_memo))
 
3249
                # Do we actually need to check _annotated_lines?
 
3250
                pending.update(p for p in parents
 
3251
                                 if p not in self._all_build_details)
 
3252
                if compression_parent:
 
3253
                    self._compression_children.setdefault(compression_parent,
 
3254
                        []).append(key)
 
3255
                if parents:
 
3256
                    for parent in parents:
 
3257
                        self._annotate_children.setdefault(parent,
 
3258
                            []).append(key)
 
3259
                    num_gens = generation - kept_generation
 
3260
                    if ((num_gens >= self._generations_until_keep)
 
3261
                        and len(parents) > 1):
 
3262
                        kept_generation = generation
 
3263
                        self._nodes_to_keep_annotations.add(key)
 
3264
 
 
3265
            missing_versions = this_iteration.difference(build_details.keys())
 
3266
            self._ghosts.update(missing_versions)
 
3267
            for missing_version in missing_versions:
 
3268
                # add a key, no parents
 
3269
                self._revision_id_graph[missing_version] = ()
 
3270
                pending.discard(missing_version) # don't look for it
 
3271
        if self._ghosts.intersection(self._compression_children):
 
3272
            raise KnitCorrupt(
 
3273
                "We cannot have nodes which have a ghost compression parent:\n"
 
3274
                "ghosts: %r\n"
 
3275
                "compression children: %r"
 
3276
                % (self._ghosts, self._compression_children))
 
3277
        # Cleanout anything that depends on a ghost so that we don't wait for
 
3278
        # the ghost to show up
 
3279
        for node in self._ghosts:
 
3280
            if node in self._annotate_children:
 
3281
                # We won't be building this node
 
3282
                del self._annotate_children[node]
 
3283
        # Generally we will want to read the records in reverse order, because
 
3284
        # we find the parent nodes after the children
 
3285
        records.reverse()
 
3286
        return records
 
3287
 
 
3288
    def _annotate_records(self, records):
 
3289
        """Build the annotations for the listed records."""
 
3290
        # We iterate in the order read, rather than a strict order requested
 
3291
        # However, process what we can, and put off to the side things that
 
3292
        # still need parents, cleaning them up when those parents are
 
3293
        # processed.
 
3294
        for (rev_id, record,
 
3295
             digest) in self._knit._read_records_iter(records):
 
3296
            if rev_id in self._annotated_lines:
 
3297
                continue
 
3298
            parent_ids = self._revision_id_graph[rev_id]
 
3299
            parent_ids = [p for p in parent_ids if p not in self._ghosts]
 
3300
            details = self._all_build_details[rev_id]
 
3301
            (index_memo, compression_parent, parents,
 
3302
             record_details) = details
 
3303
            nodes_to_annotate = []
 
3304
            # TODO: Remove the punning between compression parents, and
 
3305
            #       parent_ids, we should be able to do this without assuming
 
3306
            #       the build order
 
3307
            if len(parent_ids) == 0:
 
3308
                # There are no parents for this node, so just add it
 
3309
                # TODO: This probably needs to be decoupled
 
3310
                fulltext_content, delta = self._knit._factory.parse_record(
 
3311
                    rev_id, record, record_details, None)
 
3312
                fulltext = self._add_fulltext_content(rev_id, fulltext_content)
 
3313
                nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
 
3314
                    parent_ids, left_matching_blocks=None))
 
3315
            else:
 
3316
                child = (rev_id, parent_ids, record)
 
3317
                # Check if all the parents are present
 
3318
                self._check_parents(child, nodes_to_annotate)
 
3319
            while nodes_to_annotate:
 
3320
                # Should we use a queue here instead of a stack?
 
3321
                (rev_id, parent_ids, record) = nodes_to_annotate.pop()
 
3322
                (index_memo, compression_parent, parents,
 
3323
                 record_details) = self._all_build_details[rev_id]
 
3324
                blocks = None
 
3325
                if compression_parent is not None:
 
3326
                    comp_children = self._compression_children[compression_parent]
 
3327
                    if rev_id not in comp_children:
 
3328
                        raise AssertionError("%r not in compression children %r"
 
3329
                            % (rev_id, comp_children))
 
3330
                    # If there is only 1 child, it is safe to reuse this
 
3331
                    # content
 
3332
                    reuse_content = (len(comp_children) == 1
 
3333
                        and compression_parent not in
 
3334
                            self._nodes_to_keep_annotations)
 
3335
                    if reuse_content:
 
3336
                        # Remove it from the cache since it will be changing
 
3337
                        parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
 
3338
                        # Make sure to copy the fulltext since it might be
 
3339
                        # modified
 
3340
                        parent_fulltext = list(parent_fulltext_content.text())
 
3341
                    else:
 
3342
                        parent_fulltext_content = self._fulltext_contents[compression_parent]
 
3343
                        parent_fulltext = parent_fulltext_content.text()
 
3344
                    comp_children.remove(rev_id)
 
3345
                    fulltext_content, delta = self._knit._factory.parse_record(
 
3346
                        rev_id, record, record_details,
 
3347
                        parent_fulltext_content,
 
3348
                        copy_base_content=(not reuse_content))
 
3349
                    fulltext = self._add_fulltext_content(rev_id,
 
3350
                                                          fulltext_content)
 
3351
                    if compression_parent == parent_ids[0]:
 
3352
                        # the compression_parent is the left parent, so we can
 
3353
                        # re-use the delta
 
3354
                        blocks = KnitContent.get_line_delta_blocks(delta,
 
3355
                                parent_fulltext, fulltext)
 
3356
                else:
 
3357
                    fulltext_content = self._knit._factory.parse_fulltext(
 
3358
                        record, rev_id)
 
3359
                    fulltext = self._add_fulltext_content(rev_id,
 
3360
                        fulltext_content)
 
3361
                nodes_to_annotate.extend(
 
3362
                    self._add_annotation(rev_id, fulltext, parent_ids,
 
3363
                                     left_matching_blocks=blocks))
 
3364
 
 
3365
    def _get_heads_provider(self):
 
3366
        """Create a heads provider for resolving ancestry issues."""
 
3367
        if self._heads_provider is not None:
 
3368
            return self._heads_provider
 
3369
        parent_provider = _mod_graph.DictParentsProvider(
 
3370
            self._revision_id_graph)
 
3371
        graph_obj = _mod_graph.Graph(parent_provider)
 
3372
        head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
 
3373
        self._heads_provider = head_cache
 
3374
        return head_cache
 
3375
 
 
3376
    def annotate(self, key):
 
3377
        """Return the annotated fulltext at the given key.
 
3378
 
 
3379
        :param key: The key to annotate.
 
3380
        """
 
3381
        if len(self._knit._fallback_vfs) > 0:
 
3382
            # stacked knits can't use the fast path at present.
 
3383
            return self._simple_annotate(key)
 
3384
        while True:
 
3385
            try:
 
3386
                records = self._get_build_graph(key)
 
3387
                if key in self._ghosts:
 
3388
                    raise errors.RevisionNotPresent(key, self._knit)
 
3389
                self._annotate_records(records)
 
3390
                return self._annotated_lines[key]
 
3391
            except errors.RetryWithNewPacks, e:
 
3392
                self._knit._access.reload_or_raise(e)
 
3393
                # The cached build_details are no longer valid
 
3394
                self._all_build_details.clear()
 
3395
 
 
3396
    def _simple_annotate(self, key):
 
3397
        """Return annotated fulltext, rediffing from the full texts.
 
3398
 
 
3399
        This is slow but makes no assumptions about the repository
 
3400
        being able to produce line deltas.
 
3401
        """
 
3402
        # TODO: this code generates a parent maps of present ancestors; it
 
3403
        # could be split out into a separate method, and probably should use
 
3404
        # iter_ancestry instead. -- mbp and robertc 20080704
 
3405
        graph = _mod_graph.Graph(self._knit)
 
3406
        head_cache = _mod_graph.FrozenHeadsCache(graph)
 
3407
        search = graph._make_breadth_first_searcher([key])
 
3408
        keys = set()
 
3409
        while True:
 
3410
            try:
 
3411
                present, ghosts = search.next_with_ghosts()
 
3412
            except StopIteration:
 
3413
                break
 
3414
            keys.update(present)
 
3415
        parent_map = self._knit.get_parent_map(keys)
 
3416
        parent_cache = {}
 
3417
        reannotate = annotate.reannotate
 
3418
        for record in self._knit.get_record_stream(keys, 'topological', True):
 
3419
            key = record.key
 
3420
            fulltext = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
 
3421
            parents = parent_map[key]
 
3422
            if parents is not None:
 
3423
                parent_lines = [parent_cache[parent] for parent in parent_map[key]]
 
3424
            else:
 
3425
                parent_lines = []
 
3426
            parent_cache[key] = list(
 
3427
                reannotate(parent_lines, fulltext, key, None, head_cache))
 
3428
        try:
 
3429
            return parent_cache[key]
 
3430
        except KeyError, e:
 
3431
            raise errors.RevisionNotPresent(key, self._knit)
 
3432
 
 
3433
 
 
3434
try:
 
3435
    from bzrlib._knit_load_data_c import _load_data_c as _load_data
 
3436
except ImportError:
 
3437
    from bzrlib._knit_load_data_py import _load_data_py as _load_data