/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/knit.py

  • Committer: John Arbash Meinel
  • Date: 2009-08-16 17:22:08 UTC
  • mto: This revision was merged to the branch mainline in revision 4629.
  • Revision ID: john@arbash-meinel.com-20090816172208-2mh7z0uapy6y0gsv
Expose KnownGraph off of VersionedFiles
handle ghosts (needs tests, doesn't seem to effect performance)
list(tuple[1:]) is a couple ms slower than using my own loop.
Net effect is:
  time bzr log -n0 -r -10..-1
  real    0m2.559s

  time wbzr log -n0 -r -10..-1
  real    0m1.170s

  time bzr log -n1 -r -10..-1
  real    0m0.453s

So the overhead for the extra graph is down from 2.1s to 0.7s

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