~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/knit.py

  • Committer: Vincent Ladeuil
  • Date: 2011-04-11 09:38:59 UTC
  • mfrom: (5609.33.1 2.3)
  • mto: This revision was merged to the branch mainline in revision 5783.
  • Revision ID: v.ladeuil+lp@free.fr-20110411093859-0gyunr0tkvnoskrm
Merge 2.3 to trunk

Show diffs side-by-side

added added

removed removed

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