/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/knit.py

  • Committer: Martin Pool
  • Date: 2008-08-04 02:54:44 UTC
  • mto: This revision was merged to the branch mainline in revision 3602.
  • Revision ID: mbp@sourcefrog.net-20080804025444-su1om7v592vh8udp
Use cStringIO rather than StringIO

Show diffs side-by-side

added added

removed removed

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