/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 breezy/bzr/knit.py

  • Committer: Jelmer Vernooij
  • Date: 2018-12-19 01:30:58 UTC
  • mto: This revision was merged to the branch mainline in revision 7226.
  • Revision ID: jelmer@jelmer.uk-20181219013058-6d0q4wadil9athc2
Install launchpadlib.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
51
51
 
52
52
"""
53
53
 
 
54
from __future__ import absolute_import
54
55
 
55
 
from cStringIO import StringIO
56
 
from itertools import izip
57
56
import operator
58
57
import os
59
 
import sys
60
58
 
61
 
from bzrlib.lazy_import import lazy_import
 
59
from ..lazy_import import lazy_import
62
60
lazy_import(globals(), """
63
 
from bzrlib import (
64
 
    annotate,
 
61
import gzip
 
62
 
 
63
from breezy import (
65
64
    debug,
66
65
    diff,
67
 
    graph as _mod_graph,
68
 
    index as _mod_index,
69
 
    lru_cache,
70
 
    pack,
71
 
    progress,
 
66
    patiencediff,
72
67
    static_tuple,
73
68
    trace,
74
69
    tsort,
75
70
    tuned_gzip,
76
71
    ui,
77
72
    )
 
73
from breezy.bzr import (
 
74
    index as _mod_index,
 
75
    pack,
 
76
    )
 
77
 
 
78
from breezy.bzr import pack_repo
 
79
from breezy.i18n import gettext
78
80
""")
79
 
from bzrlib import (
 
81
from .. import (
 
82
    annotate,
80
83
    errors,
81
84
    osutils,
82
 
    patiencediff,
83
85
    )
84
 
from bzrlib.errors import (
85
 
    FileExists,
 
86
from ..errors import (
 
87
    InternalBzrError,
 
88
    InvalidRevisionId,
86
89
    NoSuchFile,
87
 
    KnitError,
88
 
    InvalidRevisionId,
89
 
    KnitCorrupt,
90
 
    KnitHeaderError,
91
90
    RevisionNotPresent,
92
 
    RevisionAlreadyPresent,
93
 
    SHA1KnitCorrupt,
94
91
    )
95
 
from bzrlib.osutils import (
 
92
from ..osutils import (
96
93
    contains_whitespace,
97
 
    contains_linebreaks,
98
94
    sha_string,
99
95
    sha_strings,
100
96
    split_lines,
101
97
    )
102
 
from bzrlib.versionedfile import (
 
98
from ..sixish import (
 
99
    BytesIO,
 
100
    range,
 
101
    viewitems,
 
102
    viewvalues,
 
103
    )
 
104
from ..bzr.versionedfile import (
 
105
    _KeyRefs,
103
106
    AbsentContentFactory,
104
107
    adapter_registry,
105
108
    ConstantMapper,
106
109
    ContentFactory,
107
 
    ChunkedContentFactory,
108
110
    sort_groupcompress,
109
 
    VersionedFile,
110
 
    VersionedFiles,
 
111
    VersionedFilesWithFallbacks,
111
112
    )
112
113
 
113
114
 
126
127
 
127
128
DATA_SUFFIX = '.knit'
128
129
INDEX_SUFFIX = '.kndx'
129
 
_STREAM_MIN_BUFFER_SIZE = 5*1024*1024
 
130
_STREAM_MIN_BUFFER_SIZE = 5 * 1024 * 1024
 
131
 
 
132
 
 
133
class KnitError(InternalBzrError):
 
134
 
 
135
    _fmt = "Knit error"
 
136
 
 
137
 
 
138
class KnitCorrupt(KnitError):
 
139
 
 
140
    _fmt = "Knit %(filename)s corrupt: %(how)s"
 
141
 
 
142
    def __init__(self, filename, how):
 
143
        KnitError.__init__(self)
 
144
        self.filename = filename
 
145
        self.how = how
 
146
 
 
147
 
 
148
class SHA1KnitCorrupt(KnitCorrupt):
 
149
 
 
150
    _fmt = ("Knit %(filename)s corrupt: sha-1 of reconstructed text does not "
 
151
            "match expected sha-1. key %(key)s expected sha %(expected)s actual "
 
152
            "sha %(actual)s")
 
153
 
 
154
    def __init__(self, filename, actual, expected, key, content):
 
155
        KnitError.__init__(self)
 
156
        self.filename = filename
 
157
        self.actual = actual
 
158
        self.expected = expected
 
159
        self.key = key
 
160
        self.content = content
 
161
 
 
162
 
 
163
class KnitDataStreamIncompatible(KnitError):
 
164
    # Not raised anymore, as we can convert data streams.  In future we may
 
165
    # need it again for more exotic cases, so we're keeping it around for now.
 
166
 
 
167
    _fmt = "Cannot insert knit data stream of format \"%(stream_format)s\" into knit of format \"%(target_format)s\"."
 
168
 
 
169
    def __init__(self, stream_format, target_format):
 
170
        self.stream_format = stream_format
 
171
        self.target_format = target_format
 
172
 
 
173
 
 
174
class KnitDataStreamUnknown(KnitError):
 
175
    # Indicates a data stream we don't know how to handle.
 
176
 
 
177
    _fmt = "Cannot parse knit data stream of format \"%(stream_format)s\"."
 
178
 
 
179
    def __init__(self, stream_format):
 
180
        self.stream_format = stream_format
 
181
 
 
182
 
 
183
class KnitHeaderError(KnitError):
 
184
 
 
185
    _fmt = 'Knit header error: %(badline)r unexpected for file "%(filename)s".'
 
186
 
 
187
    def __init__(self, badline, filename):
 
188
        KnitError.__init__(self)
 
189
        self.badline = badline
 
190
        self.filename = filename
 
191
 
 
192
 
 
193
class KnitIndexUnknownMethod(KnitError):
 
194
    """Raised when we don't understand the storage method.
 
195
 
 
196
    Currently only 'fulltext' and 'line-delta' are supported.
 
197
    """
 
198
 
 
199
    _fmt = ("Knit index %(filename)s does not have a known method"
 
200
            " in options: %(options)r")
 
201
 
 
202
    def __init__(self, filename, options):
 
203
        KnitError.__init__(self)
 
204
        self.filename = filename
 
205
        self.options = options
130
206
 
131
207
 
132
208
class KnitAdapter(object):
152
228
        rec, contents = \
153
229
            self._data._parse_record_unchecked(annotated_compressed_bytes)
154
230
        content = self._annotate_factory.parse_fulltext(contents, rec[1])
155
 
        size, bytes = self._data._record_to_data((rec[1],), rec[3], content.text())
 
231
        size, bytes = self._data._record_to_data(
 
232
            (rec[1],), rec[3], content.text())
156
233
        return bytes
157
234
 
158
235
 
164
241
        rec, contents = \
165
242
            self._data._parse_record_unchecked(annotated_compressed_bytes)
166
243
        delta = self._annotate_factory.parse_line_delta(contents, rec[1],
167
 
            plain=True)
 
244
                                                        plain=True)
168
245
        contents = self._plain_factory.lower_line_delta(delta)
169
246
        size, bytes = self._data._record_to_data((rec[1],), rec[3], contents)
170
247
        return bytes
178
255
        rec, contents = \
179
256
            self._data._parse_record_unchecked(annotated_compressed_bytes)
180
257
        content, delta = self._annotate_factory.parse_record(factory.key[-1],
181
 
            contents, factory._build_details, None)
182
 
        return ''.join(content.text())
 
258
                                                             contents, factory._build_details, None)
 
259
        return b''.join(content.text())
183
260
 
184
261
 
185
262
class DeltaAnnotatedToFullText(KnitAdapter):
190
267
        rec, contents = \
191
268
            self._data._parse_record_unchecked(annotated_compressed_bytes)
192
269
        delta = self._annotate_factory.parse_line_delta(contents, rec[1],
193
 
            plain=True)
 
270
                                                        plain=True)
194
271
        compression_parent = factory.parents[0]
195
 
        basis_entry = self._basis_vf.get_record_stream(
196
 
            [compression_parent], 'unordered', True).next()
 
272
        basis_entry = next(self._basis_vf.get_record_stream(
 
273
            [compression_parent], 'unordered', True))
197
274
        if basis_entry.storage_kind == 'absent':
198
275
            raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
199
276
        basis_chunks = basis_entry.get_bytes_as('chunked')
203
280
        basis_content = PlainKnitContent(basis_lines, compression_parent)
204
281
        basis_content.apply_delta(delta, rec[1])
205
282
        basis_content._should_strip_eol = factory._build_details[1]
206
 
        return ''.join(basis_content.text())
 
283
        return b''.join(basis_content.text())
207
284
 
208
285
 
209
286
class FTPlainToFullText(KnitAdapter):
214
291
        rec, contents = \
215
292
            self._data._parse_record_unchecked(compressed_bytes)
216
293
        content, delta = self._plain_factory.parse_record(factory.key[-1],
217
 
            contents, factory._build_details, None)
218
 
        return ''.join(content.text())
 
294
                                                          contents, factory._build_details, None)
 
295
        return b''.join(content.text())
219
296
 
220
297
 
221
298
class DeltaPlainToFullText(KnitAdapter):
228
305
        delta = self._plain_factory.parse_line_delta(contents, rec[1])
229
306
        compression_parent = factory.parents[0]
230
307
        # XXX: string splitting overhead.
231
 
        basis_entry = self._basis_vf.get_record_stream(
232
 
            [compression_parent], 'unordered', True).next()
 
308
        basis_entry = next(self._basis_vf.get_record_stream(
 
309
            [compression_parent], 'unordered', True))
233
310
        if basis_entry.storage_kind == 'absent':
234
311
            raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
235
312
        basis_chunks = basis_entry.get_bytes_as('chunked')
238
315
        # Manually apply the delta because we have one annotated content and
239
316
        # one plain.
240
317
        content, _ = self._plain_factory.parse_record(rec[1], contents,
241
 
            factory._build_details, basis_content)
242
 
        return ''.join(content.text())
 
318
                                                      factory._build_details, basis_content)
 
319
        return b''.join(content.text())
243
320
 
244
321
 
245
322
class KnitContentFactory(ContentFactory):
249
326
    """
250
327
 
251
328
    def __init__(self, key, parents, build_details, sha1, raw_record,
252
 
        annotated, knit=None, network_bytes=None):
 
329
                 annotated, knit=None, network_bytes=None):
253
330
        """Create a KnitContentFactory for key.
254
331
 
255
332
        :param key: The key.
283
360
    def _create_network_bytes(self):
284
361
        """Create a fully serialised network version for transmission."""
285
362
        # storage_kind, key, parents, Noeol, raw_record
286
 
        key_bytes = '\x00'.join(self.key)
 
363
        key_bytes = b'\x00'.join(self.key)
287
364
        if self.parents is None:
288
 
            parent_bytes = 'None:'
 
365
            parent_bytes = b'None:'
289
366
        else:
290
 
            parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
 
367
            parent_bytes = b'\t'.join(b'\x00'.join(key)
 
368
                                      for key in self.parents)
291
369
        if self._build_details[1]:
292
 
            noeol = 'N'
 
370
            noeol = b'N'
293
371
        else:
294
 
            noeol = ' '
295
 
        network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
 
372
            noeol = b' '
 
373
        network_bytes = b"%s\n%s\n%s\n%s%s" % (
 
374
            self.storage_kind.encode('ascii'), key_bytes,
296
375
            parent_bytes, noeol, self._raw_record)
297
376
        self._network_bytes = network_bytes
298
377
 
301
380
            if self._network_bytes is None:
302
381
                self._create_network_bytes()
303
382
            return self._network_bytes
304
 
        if ('-ft-' in self.storage_kind and
305
 
            storage_kind in ('chunked', 'fulltext')):
 
383
        if ('-ft-' in self.storage_kind
 
384
                and storage_kind in ('chunked', 'fulltext')):
306
385
            adapter_key = (self.storage_kind, 'fulltext')
307
386
            adapter_factory = adapter_registry.get(adapter_key)
308
387
            adapter = adapter_factory(None)
319
398
            elif storage_kind == 'fulltext':
320
399
                return self._knit.get_text(self.key[0])
321
400
        raise errors.UnavailableRepresentation(self.key, storage_kind,
322
 
            self.storage_kind)
 
401
                                               self.storage_kind)
323
402
 
324
403
 
325
404
class LazyKnitContentFactory(ContentFactory):
355
434
            else:
356
435
                # all the keys etc are contained in the bytes returned in the
357
436
                # first record.
358
 
                return ''
 
437
                return b''
359
438
        if storage_kind in ('chunked', 'fulltext'):
360
439
            chunks = self._generator._get_one_work(self.key).text()
361
440
            if storage_kind == 'chunked':
362
441
                return chunks
363
442
            else:
364
 
                return ''.join(chunks)
 
443
                return b''.join(chunks)
365
444
        raise errors.UnavailableRepresentation(self.key, storage_kind,
366
 
            self.storage_kind)
 
445
                                               self.storage_kind)
367
446
 
368
447
 
369
448
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
384
463
    :param bytes: The bytes of the record on the network.
385
464
    """
386
465
    start = line_end
387
 
    line_end = bytes.find('\n', start)
388
 
    key = tuple(bytes[start:line_end].split('\x00'))
 
466
    line_end = bytes.find(b'\n', start)
 
467
    key = tuple(bytes[start:line_end].split(b'\x00'))
389
468
    start = line_end + 1
390
 
    line_end = bytes.find('\n', start)
 
469
    line_end = bytes.find(b'\n', start)
391
470
    parent_line = bytes[start:line_end]
392
 
    if parent_line == 'None:':
 
471
    if parent_line == b'None:':
393
472
        parents = None
394
473
    else:
395
474
        parents = tuple(
396
 
            [tuple(segment.split('\x00')) for segment in parent_line.split('\t')
 
475
            [tuple(segment.split(b'\x00')) for segment in parent_line.split(b'\t')
397
476
             if segment])
398
477
    start = line_end + 1
399
 
    noeol = bytes[start] == 'N'
 
478
    noeol = bytes[start:start + 1] == b'N'
400
479
    if 'ft' in storage_kind:
401
480
        method = 'fulltext'
402
481
    else:
406
485
    raw_record = bytes[start:]
407
486
    annotated = 'annotated' in storage_kind
408
487
    return [KnitContentFactory(key, parents, build_details, None, raw_record,
409
 
        annotated, network_bytes=bytes)]
 
488
                               annotated, network_bytes=bytes)]
410
489
 
411
490
 
412
491
class KnitContent(object):
413
492
    """Content of a knit version to which deltas can be applied.
414
493
 
415
 
    This is always stored in memory as a list of lines with \n at the end,
 
494
    This is always stored in memory as a list of lines with \\n at the end,
416
495
    plus a flag saying if the final ending is really there or not, because that
417
496
    corresponds to the on-disk knit representation.
418
497
    """
450
529
            if n > 0:
451
530
                # knit deltas do not provide reliable info about whether the
452
531
                # last line of a file matches, due to eol handling.
453
 
                if source[s_pos + n -1] != target[t_pos + n -1]:
454
 
                    n-=1
 
532
                if source[s_pos + n - 1] != target[t_pos + n - 1]:
 
533
                    n -= 1
455
534
                if n > 0:
456
535
                    yield s_pos, t_pos, n
457
536
            t_pos += t_len + true_n
458
537
            s_pos = s_end
459
538
        n = target_len - t_pos
460
539
        if n > 0:
461
 
            if source[s_pos + n -1] != target[t_pos + n -1]:
462
 
                n-=1
 
540
            if source[s_pos + n - 1] != target[t_pos + n - 1]:
 
541
                n -= 1
463
542
            if n > 0:
464
543
                yield s_pos, t_pos, n
465
544
        yield s_pos + (target_len - t_pos), target_len, 0
470
549
 
471
550
    def __init__(self, lines):
472
551
        KnitContent.__init__(self)
473
 
        self._lines = lines
 
552
        self._lines = list(lines)
474
553
 
475
554
    def annotate(self):
476
555
        """Return a list of (origin, text) for each content line."""
477
556
        lines = self._lines[:]
478
557
        if self._should_strip_eol:
479
558
            origin, last_line = lines[-1]
480
 
            lines[-1] = (origin, last_line.rstrip('\n'))
 
559
            lines[-1] = (origin, last_line.rstrip(b'\n'))
481
560
        return lines
482
561
 
483
562
    def apply_delta(self, delta, new_version_id):
485
564
        offset = 0
486
565
        lines = self._lines
487
566
        for start, end, count, delta_lines in delta:
488
 
            lines[offset+start:offset+end] = delta_lines
 
567
            lines[offset + start:offset + end] = delta_lines
489
568
            offset = offset + (start - end) + count
490
569
 
491
570
    def text(self):
492
571
        try:
493
572
            lines = [text for origin, text in self._lines]
494
 
        except ValueError, e:
 
573
        except ValueError as e:
495
574
            # most commonly (only?) caused by the internal form of the knit
496
575
            # missing annotation information because of a bug - see thread
497
576
            # around 20071015
498
577
            raise KnitCorrupt(self,
499
 
                "line in annotated knit missing annotation information: %s"
500
 
                % (e,))
 
578
                              "line in annotated knit missing annotation information: %s"
 
579
                              % (e,))
501
580
        if self._should_strip_eol:
502
 
            lines[-1] = lines[-1].rstrip('\n')
 
581
            lines[-1] = lines[-1].rstrip(b'\n')
503
582
        return lines
504
583
 
505
584
    def copy(self):
506
 
        return AnnotatedKnitContent(self._lines[:])
 
585
        return AnnotatedKnitContent(self._lines)
507
586
 
508
587
 
509
588
class PlainKnitContent(KnitContent):
528
607
        offset = 0
529
608
        lines = self._lines
530
609
        for start, end, count, delta_lines in delta:
531
 
            lines[offset+start:offset+end] = delta_lines
 
610
            lines[offset + start:offset + end] = delta_lines
532
611
            offset = offset + (start - end) + count
533
612
        self._version_id = new_version_id
534
613
 
539
618
        lines = self._lines
540
619
        if self._should_strip_eol:
541
620
            lines = lines[:]
542
 
            lines[-1] = lines[-1].rstrip('\n')
 
621
            lines[-1] = lines[-1].rstrip(b'\n')
543
622
        return lines
544
623
 
545
624
 
598
677
        #       but the code itself doesn't really depend on that.
599
678
        #       Figure out a way to not require the overhead of turning the
600
679
        #       list back into tuples.
601
 
        lines = [tuple(line.split(' ', 1)) for line in content]
 
680
        lines = (tuple(line.split(b' ', 1)) for line in content)
602
681
        return AnnotatedKnitContent(lines)
603
682
 
604
683
    def parse_line_delta_iter(self, lines):
620
699
        """
621
700
        result = []
622
701
        lines = iter(lines)
623
 
        next = lines.next
624
702
 
625
703
        cache = {}
 
704
 
626
705
        def cache_and_return(line):
627
 
            origin, text = line.split(' ', 1)
 
706
            origin, text = line.split(b' ', 1)
628
707
            return cache.setdefault(origin, origin), text
629
708
 
630
709
        # walk through the lines parsing.
632
711
        # loop to minimise any performance impact
633
712
        if plain:
634
713
            for header in lines:
635
 
                start, end, count = [int(n) for n in header.split(',')]
636
 
                contents = [next().split(' ', 1)[1] for i in xrange(count)]
 
714
                start, end, count = [int(n) for n in header.split(b',')]
 
715
                contents = [next(lines).split(b' ', 1)[1]
 
716
                            for _ in range(count)]
637
717
                result.append((start, end, count, contents))
638
718
        else:
639
719
            for header in lines:
640
 
                start, end, count = [int(n) for n in header.split(',')]
641
 
                contents = [tuple(next().split(' ', 1)) for i in xrange(count)]
 
720
                start, end, count = [int(n) for n in header.split(b',')]
 
721
                contents = [tuple(next(lines).split(b' ', 1))
 
722
                            for _ in range(count)]
642
723
                result.append((start, end, count, contents))
643
724
        return result
644
725
 
645
726
    def get_fulltext_content(self, lines):
646
727
        """Extract just the content lines from a fulltext."""
647
 
        return (line.split(' ', 1)[1] for line in lines)
 
728
        return (line.split(b' ', 1)[1] for line in lines)
648
729
 
649
730
    def get_linedelta_content(self, lines):
650
731
        """Extract just the content from a line delta.
653
734
        Only the actual content lines.
654
735
        """
655
736
        lines = iter(lines)
656
 
        next = lines.next
657
737
        for header in lines:
658
 
            header = header.split(',')
 
738
            header = header.split(b',')
659
739
            count = int(header[2])
660
 
            for i in xrange(count):
661
 
                origin, text = next().split(' ', 1)
 
740
            for _ in range(count):
 
741
                origin, text = next(lines).split(b' ', 1)
662
742
                yield text
663
743
 
664
744
    def lower_fulltext(self, content):
666
746
 
667
747
        see parse_fulltext which this inverts.
668
748
        """
669
 
        return ['%s %s' % (o, t) for o, t in content._lines]
 
749
        return [b'%s %s' % (o, t) for o, t in content._lines]
670
750
 
671
751
    def lower_line_delta(self, delta):
672
752
        """convert a delta into a serializable form.
677
757
        #       the origin is a valid utf-8 line, eventually we could remove it
678
758
        out = []
679
759
        for start, end, c, lines in delta:
680
 
            out.append('%d,%d,%d\n' % (start, end, c))
681
 
            out.extend(origin + ' ' + text
 
760
            out.append(b'%d,%d,%d\n' % (start, end, c))
 
761
            out.extend(origin + b' ' + text
682
762
                       for origin, text in lines)
683
763
        return out
684
764
 
686
766
        content = knit._get_content(key)
687
767
        # adjust for the fact that serialised annotations are only key suffixes
688
768
        # for this factory.
689
 
        if type(key) is tuple:
 
769
        if isinstance(key, tuple):
690
770
            prefix = key[:-1]
691
771
            origins = content.annotate()
692
772
            result = []
721
801
        while cur < num_lines:
722
802
            header = lines[cur]
723
803
            cur += 1
724
 
            start, end, c = [int(n) for n in header.split(',')]
725
 
            yield start, end, c, lines[cur:cur+c]
 
804
            start, end, c = [int(n) for n in header.split(b',')]
 
805
            yield start, end, c, lines[cur:cur + c]
726
806
            cur += c
727
807
 
728
808
    def parse_line_delta(self, lines, version_id):
739
819
        Only the actual content lines.
740
820
        """
741
821
        lines = iter(lines)
742
 
        next = lines.next
743
822
        for header in lines:
744
 
            header = header.split(',')
 
823
            header = header.split(b',')
745
824
            count = int(header[2])
746
 
            for i in xrange(count):
747
 
                yield next()
 
825
            for _ in range(count):
 
826
                yield next(lines)
748
827
 
749
828
    def lower_fulltext(self, content):
750
829
        return content.text()
752
831
    def lower_line_delta(self, delta):
753
832
        out = []
754
833
        for start, end, c, lines in delta:
755
 
            out.append('%d,%d,%d\n' % (start, end, c))
 
834
            out.append(b'%d,%d,%d\n' % (start, end, c))
756
835
            out.extend(lines)
757
836
        return out
758
837
 
761
840
        return annotator.annotate_flat(key)
762
841
 
763
842
 
764
 
 
765
843
def make_file_factory(annotated, mapper):
766
844
    """Create a factory for creating a file based KnitVersionedFiles.
767
845
 
772
850
    :param mapper: The mapper from keys to paths.
773
851
    """
774
852
    def factory(transport):
775
 
        index = _KndxIndex(transport, mapper, lambda:None, lambda:True, lambda:True)
 
853
        index = _KndxIndex(transport, mapper, lambda: None,
 
854
                           lambda: True, lambda: True)
776
855
        access = _KnitKeyAccess(transport, mapper)
777
856
        return KnitVersionedFiles(index, access, annotated=annotated)
778
857
    return factory
799
878
        else:
800
879
            max_delta_chain = 0
801
880
        graph_index = _mod_index.InMemoryGraphIndex(reference_lists=ref_length,
802
 
            key_elements=keylength)
 
881
                                                    key_elements=keylength)
803
882
        stream = transport.open_write_stream('newpack')
804
883
        writer = pack.ContainerWriter(stream.write)
805
884
        writer.begin()
806
 
        index = _KnitGraphIndex(graph_index, lambda:True, parents=parents,
807
 
            deltas=delta, add_callback=graph_index.add_nodes)
808
 
        access = _DirectPackAccess({})
 
885
        index = _KnitGraphIndex(graph_index, lambda: True, parents=parents,
 
886
                                deltas=delta, add_callback=graph_index.add_nodes)
 
887
        access = pack_repo._DirectPackAccess({})
809
888
        access.set_writer(writer, graph_index, (transport, 'newpack'))
810
889
        result = KnitVersionedFiles(index, access,
811
 
            max_delta_chain=max_delta_chain)
 
890
                                    max_delta_chain=max_delta_chain)
812
891
        result.stream = stream
813
892
        result.writer = writer
814
893
        return result
845
924
            if compression_parent not in all_build_index_memos:
846
925
                next_keys.add(compression_parent)
847
926
        build_keys = next_keys
848
 
    return sum([index_memo[2] for index_memo
849
 
                in all_build_index_memos.itervalues()])
850
 
 
851
 
 
852
 
class KnitVersionedFiles(VersionedFiles):
 
927
    return sum(index_memo[2]
 
928
               for index_memo in viewvalues(all_build_index_memos))
 
929
 
 
930
 
 
931
class KnitVersionedFiles(VersionedFilesWithFallbacks):
853
932
    """Storage for many versioned files using knit compression.
854
933
 
855
934
    Backend storage is managed by indices and data objects.
873
952
            stored during insertion.
874
953
        :param reload_func: An function that can be called if we think we need
875
954
            to reload the pack listing and try again. See
876
 
            'bzrlib.repofmt.pack_repo.AggregateIndex' for the signature.
 
955
            'breezy.bzr.pack_repo.AggregateIndex' for the signature.
877
956
        """
878
957
        self._index = index
879
958
        self._access = data_access
882
961
            self._factory = KnitAnnotateFactory()
883
962
        else:
884
963
            self._factory = KnitPlainFactory()
885
 
        self._fallback_vfs = []
 
964
        self._immediate_fallback_vfs = []
886
965
        self._reload_func = reload_func
887
966
 
888
967
    def __repr__(self):
891
970
            self._index,
892
971
            self._access)
893
972
 
 
973
    def without_fallbacks(self):
 
974
        """Return a clone of this object without any fallbacks configured."""
 
975
        return KnitVersionedFiles(self._index, self._access,
 
976
                                  self._max_delta_chain, self._factory.annotated,
 
977
                                  self._reload_func)
 
978
 
894
979
    def add_fallback_versioned_files(self, a_versioned_files):
895
980
        """Add a source of texts for texts not present in this knit.
896
981
 
897
982
        :param a_versioned_files: A VersionedFiles object.
898
983
        """
899
 
        self._fallback_vfs.append(a_versioned_files)
 
984
        self._immediate_fallback_vfs.append(a_versioned_files)
900
985
 
901
986
    def add_lines(self, key, parents, lines, parent_texts=None,
902
 
        left_matching_blocks=None, nostore_sha=None, random_id=False,
903
 
        check_content=True):
 
987
                  left_matching_blocks=None, nostore_sha=None, random_id=False,
 
988
                  check_content=True):
904
989
        """See VersionedFiles.add_lines()."""
905
990
        self._index._check_write_ok()
906
991
        self._check_add(key, lines, random_id, check_content)
909
994
            # indexes can't directly store that, so we give them
910
995
            # an empty tuple instead.
911
996
            parents = ()
912
 
        line_bytes = ''.join(lines)
 
997
        line_bytes = b''.join(lines)
913
998
        return self._add(key, lines, parents,
914
 
            parent_texts, left_matching_blocks, nostore_sha, random_id,
915
 
            line_bytes=line_bytes)
916
 
 
917
 
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
918
 
        """See VersionedFiles._add_text()."""
919
 
        self._index._check_write_ok()
920
 
        self._check_add(key, None, random_id, check_content=False)
921
 
        if text.__class__ is not str:
922
 
            raise errors.BzrBadParameterUnicode("text")
923
 
        if parents is None:
924
 
            # The caller might pass None if there is no graph data, but kndx
925
 
            # indexes can't directly store that, so we give them
926
 
            # an empty tuple instead.
927
 
            parents = ()
928
 
        return self._add(key, None, parents,
929
 
            None, None, nostore_sha, random_id,
930
 
            line_bytes=text)
 
999
                         parent_texts, left_matching_blocks, nostore_sha, random_id,
 
1000
                         line_bytes=line_bytes)
931
1001
 
932
1002
    def _add(self, key, lines, parents, parent_texts,
933
 
        left_matching_blocks, nostore_sha, random_id,
934
 
        line_bytes):
 
1003
             left_matching_blocks, nostore_sha, random_id,
 
1004
             line_bytes):
935
1005
        """Add a set of lines on top of version specified by parents.
936
1006
 
937
1007
        Any versions not present will be converted into ghosts.
963
1033
                present_parents.append(parent)
964
1034
 
965
1035
        # Currently we can only compress against the left most present parent.
966
 
        if (len(present_parents) == 0 or
967
 
            present_parents[0] != parents[0]):
 
1036
        if (len(present_parents) == 0
 
1037
                or present_parents[0] != parents[0]):
968
1038
            delta = False
969
1039
        else:
970
1040
            # To speed the extract of texts the delta chain is limited
978
1048
        # Note: line_bytes is not modified to add a newline, that is tracked
979
1049
        #       via the no_eol flag. 'lines' *is* modified, because that is the
980
1050
        #       general values needed by the Content code.
981
 
        if line_bytes and line_bytes[-1] != '\n':
982
 
            options.append('no-eol')
 
1051
        if line_bytes and not line_bytes.endswith(b'\n'):
 
1052
            options.append(b'no-eol')
983
1053
            no_eol = True
984
1054
            # Copy the existing list, or create a new one
985
1055
            if lines is None:
987
1057
            else:
988
1058
                lines = lines[:]
989
1059
            # Replace the last line with one that ends in a final newline
990
 
            lines[-1] = lines[-1] + '\n'
 
1060
            lines[-1] = lines[-1] + b'\n'
991
1061
        if lines is None:
992
1062
            lines = osutils.split_lines(line_bytes)
993
1063
 
994
1064
        for element in key[:-1]:
995
 
            if type(element) is not str:
996
 
                raise TypeError("key contains non-strings: %r" % (key,))
 
1065
            if not isinstance(element, bytes):
 
1066
                raise TypeError("key contains non-bytestrings: %r" % (key,))
997
1067
        if key[-1] is None:
998
 
            key = key[:-1] + ('sha1:' + digest,)
999
 
        elif type(key[-1]) is not str:
1000
 
                raise TypeError("key contains non-strings: %r" % (key,))
 
1068
            key = key[:-1] + (b'sha1:' + digest,)
 
1069
        elif not isinstance(key[-1], bytes):
 
1070
            raise TypeError("key contains non-bytestrings: %r" % (key,))
1001
1071
        # Knit hunks are still last-element only
1002
1072
        version_id = key[-1]
1003
1073
        content = self._factory.make(lines, version_id)
1008
1078
        if delta or (self._factory.annotated and len(present_parents) > 0):
1009
1079
            # Merge annotations from parent texts if needed.
1010
1080
            delta_hunks = self._merge_annotations(content, present_parents,
1011
 
                parent_texts, delta, self._factory.annotated,
1012
 
                left_matching_blocks)
 
1081
                                                  parent_texts, delta, self._factory.annotated,
 
1082
                                                  left_matching_blocks)
1013
1083
 
1014
1084
        if delta:
1015
 
            options.append('line-delta')
 
1085
            options.append(b'line-delta')
1016
1086
            store_lines = self._factory.lower_line_delta(delta_hunks)
1017
 
            size, bytes = self._record_to_data(key, digest,
1018
 
                store_lines)
 
1087
            size, data = self._record_to_data(key, digest,
 
1088
                                              store_lines)
1019
1089
        else:
1020
 
            options.append('fulltext')
 
1090
            options.append(b'fulltext')
1021
1091
            # isinstance is slower and we have no hierarchy.
1022
1092
            if self._factory.__class__ is KnitPlainFactory:
1023
1093
                # Use the already joined bytes saving iteration time in
1024
1094
                # _record_to_data.
1025
1095
                dense_lines = [line_bytes]
1026
1096
                if no_eol:
1027
 
                    dense_lines.append('\n')
1028
 
                size, bytes = self._record_to_data(key, digest,
1029
 
                    lines, dense_lines)
 
1097
                    dense_lines.append(b'\n')
 
1098
                size, data = self._record_to_data(key, digest,
 
1099
                                                  lines, dense_lines)
1030
1100
            else:
1031
1101
                # get mixed annotation + content and feed it into the
1032
1102
                # serialiser.
1033
1103
                store_lines = self._factory.lower_fulltext(content)
1034
 
                size, bytes = self._record_to_data(key, digest,
1035
 
                    store_lines)
 
1104
                size, data = self._record_to_data(key, digest,
 
1105
                                                  store_lines)
1036
1106
 
1037
 
        access_memo = self._access.add_raw_records([(key, size)], bytes)[0]
 
1107
        access_memo = self._access.add_raw_records([(key, size)], data)[0]
1038
1108
        self._index.add_records(
1039
1109
            ((key, options, access_memo, parents),),
1040
1110
            random_id=random_id)
1066
1136
            if self._index.get_method(key) != 'fulltext':
1067
1137
                compression_parent = parent_map[key][0]
1068
1138
                if compression_parent not in parent_map:
1069
 
                    raise errors.KnitCorrupt(self,
1070
 
                        "Missing basis parent %s for %s" % (
1071
 
                        compression_parent, key))
1072
 
        for fallback_vfs in self._fallback_vfs:
 
1139
                    raise KnitCorrupt(self,
 
1140
                                      "Missing basis parent %s for %s" % (
 
1141
                                          compression_parent, key))
 
1142
        for fallback_vfs in self._immediate_fallback_vfs:
1073
1143
            fallback_vfs.check()
1074
1144
 
1075
1145
    def _check_add(self, key, lines, random_id, check_content):
1076
1146
        """check that version_id and lines are safe to add."""
 
1147
        if not all(isinstance(x, bytes) or x is None for x in key):
 
1148
            raise TypeError(key)
1077
1149
        version_id = key[-1]
1078
1150
        if version_id is not None:
1079
1151
            if contains_whitespace(version_id):
1099
1171
        """
1100
1172
        if rec[1] != version_id:
1101
1173
            raise KnitCorrupt(self,
1102
 
                'unexpected version, wanted %r, got %r' % (version_id, rec[1]))
 
1174
                              'unexpected version, wanted %r, got %r' % (version_id, rec[1]))
1103
1175
 
1104
1176
    def _check_should_delta(self, parent):
1105
1177
        """Iterate back through the parent listing, looking for a fulltext.
1114
1186
        """
1115
1187
        delta_size = 0
1116
1188
        fulltext_size = None
1117
 
        for count in xrange(self._max_delta_chain):
 
1189
        for count in range(self._max_delta_chain):
1118
1190
            try:
1119
1191
                # Note that this only looks in the index of this particular
1120
1192
                # KnitVersionedFiles, not in the fallbacks.  This ensures that
1122
1194
                # boundaries.
1123
1195
                build_details = self._index.get_build_details([parent])
1124
1196
                parent_details = build_details[parent]
1125
 
            except (RevisionNotPresent, KeyError), e:
 
1197
            except (RevisionNotPresent, KeyError) as e:
1126
1198
                # Some basis is not locally present: always fulltext
1127
1199
                return False
1128
1200
            index_memo, compression_parent, _, _ = parent_details
1153
1225
 
1154
1226
        A dict of key to (record_details, index_memo, next, parents) is
1155
1227
        returned.
1156
 
        method is the way referenced data should be applied.
1157
 
        index_memo is the handle to pass to the data access to actually get the
1158
 
            data
1159
 
        next is the build-parent of the version, or None for fulltexts.
1160
 
        parents is the version_ids of the parents of this version
1161
 
 
1162
 
        :param allow_missing: If True do not raise an error on a missing component,
1163
 
            just ignore it.
 
1228
 
 
1229
        * method is the way referenced data should be applied.
 
1230
        * index_memo is the handle to pass to the data access to actually get
 
1231
          the data
 
1232
        * next is the build-parent of the version, or None for fulltexts.
 
1233
        * parents is the version_ids of the parents of this version
 
1234
 
 
1235
        :param allow_missing: If True do not raise an error on a missing
 
1236
            component, just ignore it.
1164
1237
        """
1165
1238
        component_data = {}
1166
1239
        pending_components = keys
1168
1241
            build_details = self._index.get_build_details(pending_components)
1169
1242
            current_components = set(pending_components)
1170
1243
            pending_components = set()
1171
 
            for key, details in build_details.iteritems():
 
1244
            for key, details in viewitems(build_details):
1172
1245
                (index_memo, compression_parent, parents,
1173
1246
                 record_details) = details
1174
 
                method = record_details[0]
1175
1247
                if compression_parent is not None:
1176
1248
                    pending_components.add(compression_parent)
1177
 
                component_data[key] = self._build_details_to_components(details)
 
1249
                component_data[key] = self._build_details_to_components(
 
1250
                    details)
1178
1251
            missing = current_components.difference(build_details)
1179
1252
            if missing and not allow_missing:
1180
1253
                raise errors.RevisionNotPresent(missing.pop(), self)
1192
1265
        generator = _VFContentMapGenerator(self, [key])
1193
1266
        return generator._get_content(key)
1194
1267
 
1195
 
    def get_known_graph_ancestry(self, keys):
1196
 
        """Get a KnownGraph instance with the ancestry of keys."""
1197
 
        parent_map, missing_keys = self._index.find_ancestry(keys)
1198
 
        for fallback in self._fallback_vfs:
1199
 
            if not missing_keys:
1200
 
                break
1201
 
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1202
 
                                                missing_keys)
1203
 
            parent_map.update(f_parent_map)
1204
 
            missing_keys = f_missing_keys
1205
 
        kg = _mod_graph.KnownGraph(parent_map)
1206
 
        return kg
1207
 
 
1208
1268
    def get_parent_map(self, keys):
1209
1269
        """Get a map of the graph parents of keys.
1210
1270
 
1225
1285
            and so on.
1226
1286
        """
1227
1287
        result = {}
1228
 
        sources = [self._index] + self._fallback_vfs
 
1288
        sources = [self._index] + self._immediate_fallback_vfs
1229
1289
        source_results = []
1230
1290
        missing = set(keys)
1231
1291
        for source in sources:
1241
1301
        """Produce a dictionary of knit records.
1242
1302
 
1243
1303
        :return: {key:(record, record_details, digest, next)}
1244
 
            record
1245
 
                data returned from read_records (a KnitContentobject)
1246
 
            record_details
1247
 
                opaque information to pass to parse_record
1248
 
            digest
1249
 
                SHA1 digest of the full text after all steps are done
1250
 
            next
1251
 
                build-parent of the version, i.e. the leftmost ancestor.
 
1304
 
 
1305
            * record: data returned from read_records (a KnitContentobject)
 
1306
            * record_details: opaque information to pass to parse_record
 
1307
            * digest: SHA1 digest of the full text after all steps are done
 
1308
            * next: build-parent of the version, i.e. the leftmost ancestor.
1252
1309
                Will be None if the record is not a delta.
 
1310
 
1253
1311
        :param keys: The keys to build a map for
1254
1312
        :param allow_missing: If some records are missing, rather than
1255
1313
            error, just return the data that could be generated.
1256
1314
        """
1257
1315
        raw_map = self._get_record_map_unparsed(keys,
1258
 
            allow_missing=allow_missing)
 
1316
                                                allow_missing=allow_missing)
1259
1317
        return self._raw_map_to_record_map(raw_map)
1260
1318
 
1261
1319
    def _raw_map_to_record_map(self, raw_map):
1286
1344
        while True:
1287
1345
            try:
1288
1346
                position_map = self._get_components_positions(keys,
1289
 
                    allow_missing=allow_missing)
 
1347
                                                              allow_missing=allow_missing)
1290
1348
                # key = component_id, r = record_details, i_m = index_memo,
1291
1349
                # n = next
1292
1350
                records = [(key, i_m) for key, (r, i_m, n)
1293
 
                                       in position_map.iteritems()]
 
1351
                           in viewitems(position_map)]
1294
1352
                # Sort by the index memo, so that we request records from the
1295
1353
                # same pack file together, and in forward-sorted order
1296
1354
                records.sort(key=operator.itemgetter(1))
1299
1357
                    (record_details, index_memo, next) = position_map[key]
1300
1358
                    raw_record_map[key] = data, record_details, next
1301
1359
                return raw_record_map
1302
 
            except errors.RetryWithNewPacks, e:
 
1360
            except errors.RetryWithNewPacks as e:
1303
1361
                self._access.reload_or_raise(e)
1304
1362
 
1305
1363
    @classmethod
1325
1383
        prefix_order = []
1326
1384
        for key in keys:
1327
1385
            if len(key) == 1:
1328
 
                prefix = ''
 
1386
                prefix = b''
1329
1387
            else:
1330
1388
                prefix = key[0]
1331
1389
 
1404
1462
            try:
1405
1463
                keys = set(remaining_keys)
1406
1464
                for content_factory in self._get_remaining_record_stream(keys,
1407
 
                                            ordering, include_delta_closure):
 
1465
                                                                         ordering, include_delta_closure):
1408
1466
                    remaining_keys.discard(content_factory.key)
1409
1467
                    yield content_factory
1410
1468
                return
1411
 
            except errors.RetryWithNewPacks, e:
 
1469
            except errors.RetryWithNewPacks as e:
1412
1470
                self._access.reload_or_raise(e)
1413
1471
 
1414
1472
    def _get_remaining_record_stream(self, keys, ordering,
1415
1473
                                     include_delta_closure):
1416
1474
        """This function is the 'retry' portion for get_record_stream."""
1417
1475
        if include_delta_closure:
1418
 
            positions = self._get_components_positions(keys, allow_missing=True)
 
1476
            positions = self._get_components_positions(
 
1477
                keys, allow_missing=True)
1419
1478
        else:
1420
1479
            build_details = self._index.get_build_details(keys)
1421
1480
            # map from key to
1422
1481
            # (record_details, access_memo, compression_parent_key)
1423
1482
            positions = dict((key, self._build_details_to_components(details))
1424
 
                for key, details in build_details.iteritems())
 
1483
                             for key, details in viewitems(build_details))
1425
1484
        absent_keys = keys.difference(set(positions))
1426
1485
        # There may be more absent keys : if we're missing the basis component
1427
1486
        # and are trying to include the delta closure.
1479
1538
        else:
1480
1539
            if ordering != 'unordered':
1481
1540
                raise AssertionError('valid values for ordering are:'
1482
 
                    ' "unordered", "groupcompress" or "topological" not: %r'
1483
 
                    % (ordering,))
 
1541
                                     ' "unordered", "groupcompress" or "topological" not: %r'
 
1542
                                     % (ordering,))
1484
1543
            # Just group by source; remote sources first.
1485
1544
            present_keys = []
1486
1545
            source_keys = []
1523
1582
                    for key, raw_data in self._read_records_iter_unchecked(records):
1524
1583
                        (record_details, index_memo, _) = positions[key]
1525
1584
                        yield KnitContentFactory(key, global_map[key],
1526
 
                            record_details, None, raw_data, self._factory.annotated, None)
 
1585
                                                 record_details, None, raw_data, self._factory.annotated, None)
1527
1586
                else:
1528
 
                    vf = self._fallback_vfs[parent_maps.index(source) - 1]
 
1587
                    vf = self._immediate_fallback_vfs[parent_maps.index(
 
1588
                        source) - 1]
1529
1589
                    for record in vf.get_record_stream(keys, ordering,
1530
 
                        include_delta_closure):
 
1590
                                                       include_delta_closure):
1531
1591
                        yield record
1532
1592
 
1533
1593
    def get_sha1s(self, keys):
1535
1595
        missing = set(keys)
1536
1596
        record_map = self._get_record_map(missing, allow_missing=True)
1537
1597
        result = {}
1538
 
        for key, details in record_map.iteritems():
 
1598
        for key, details in viewitems(record_map):
1539
1599
            if key not in missing:
1540
1600
                continue
1541
1601
            # record entry 2 is the 'digest'.
1542
1602
            result[key] = details[2]
1543
1603
        missing.difference_update(set(result))
1544
 
        for source in self._fallback_vfs:
 
1604
        for source in self._immediate_fallback_vfs:
1545
1605
            if not missing:
1546
1606
                break
1547
1607
            new_result = source.get_sha1s(missing)
1572
1632
        else:
1573
1633
            # self is not annotated, but we can strip annotations cheaply.
1574
1634
            annotated = ""
1575
 
            convertibles = set(["knit-annotated-ft-gz"])
 
1635
            convertibles = {"knit-annotated-ft-gz"}
1576
1636
            if self._max_delta_chain:
1577
1637
                delta_types.add("knit-annotated-delta-gz")
1578
1638
                convertibles.add("knit-annotated-delta-gz")
1616
1676
            # Raise an error when a record is missing.
1617
1677
            if record.storage_kind == 'absent':
1618
1678
                raise RevisionNotPresent([record.key], self)
1619
 
            elif ((record.storage_kind in knit_types)
1620
 
                  and (compression_parent is None
1621
 
                       or not self._fallback_vfs
1622
 
                       or self._index.has_key(compression_parent)
1623
 
                       or not self.has_key(compression_parent))):
 
1679
            elif ((record.storage_kind in knit_types) and
 
1680
                  (compression_parent is None or
 
1681
                   not self._immediate_fallback_vfs or
 
1682
                   compression_parent in self._index or
 
1683
                   compression_parent not in self)):
1624
1684
                # we can insert the knit record literally if either it has no
1625
1685
                # compression parent OR we already have its basis in this kvf
1626
1686
                # OR the basis is not present even in the fallbacks.  In the
1628
1688
                # will be well, or it won't turn up at all and we'll raise an
1629
1689
                # error at the end.
1630
1690
                #
1631
 
                # TODO: self.has_key is somewhat redundant with
1632
 
                # self._index.has_key; we really want something that directly
 
1691
                # TODO: self.__contains__ is somewhat redundant with
 
1692
                # self._index.__contains__; we really want something that directly
1633
1693
                # asks if it's only present in the fallbacks. -- mbp 20081119
1634
1694
                if record.storage_kind not in native_types:
1635
1695
                    try:
1643
1703
                    # It's a knit record, it has a _raw_record field (even if
1644
1704
                    # it was reconstituted from a network stream).
1645
1705
                    bytes = record._raw_record
1646
 
                options = [record._build_details[0]]
 
1706
                options = [record._build_details[0].encode('ascii')]
1647
1707
                if record._build_details[1]:
1648
 
                    options.append('no-eol')
 
1708
                    options.append(b'no-eol')
1649
1709
                # Just blat it across.
1650
1710
                # Note: This does end up adding data on duplicate keys. As
1651
1711
                # modern repositories use atomic insertions this should not
1657
1717
                access_memo = self._access.add_raw_records(
1658
1718
                    [(record.key, len(bytes))], bytes)[0]
1659
1719
                index_entry = (record.key, options, access_memo, parents)
1660
 
                if 'fulltext' not in options:
 
1720
                if b'fulltext' not in options:
1661
1721
                    # Not a fulltext, so we need to make sure the compression
1662
1722
                    # parent will also be present.
1663
1723
                    # Note that pack backed knits don't need to buffer here
1668
1728
                    #
1669
1729
                    # They're required to be physically in this
1670
1730
                    # KnitVersionedFiles, not in a fallback.
1671
 
                    if not self._index.has_key(compression_parent):
 
1731
                    if compression_parent not in self._index:
1672
1732
                        pending = buffered_index_entries.setdefault(
1673
1733
                            compression_parent, [])
1674
1734
                        pending.append(index_entry)
1677
1737
                    self._index.add_records([index_entry])
1678
1738
            elif record.storage_kind == 'chunked':
1679
1739
                self.add_lines(record.key, parents,
1680
 
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
 
1740
                               osutils.chunks_to_lines(record.get_bytes_as('chunked')))
1681
1741
            else:
1682
1742
                # Not suitable for direct insertion as a
1683
1743
                # delta, either because it's not the right format, or this
1767
1827
                # we need key, position, length
1768
1828
                key_records = []
1769
1829
                build_details = self._index.get_build_details(keys)
1770
 
                for key, details in build_details.iteritems():
 
1830
                for key, details in viewitems(build_details):
1771
1831
                    if key in keys:
1772
1832
                        key_records.append((key, details[0]))
1773
1833
                records_iter = enumerate(self._read_records_iter(key_records))
1774
1834
                for (key_idx, (key, data, sha_value)) in records_iter:
1775
 
                    pb.update('Walking content', key_idx, total)
 
1835
                    pb.update(gettext('Walking content'), key_idx, total)
1776
1836
                    compression_parent = build_details[key][1]
1777
1837
                    if compression_parent is None:
1778
1838
                        # fulltext
1779
 
                        line_iterator = self._factory.get_fulltext_content(data)
 
1839
                        line_iterator = self._factory.get_fulltext_content(
 
1840
                            data)
1780
1841
                    else:
1781
1842
                        # Delta
1782
 
                        line_iterator = self._factory.get_linedelta_content(data)
 
1843
                        line_iterator = self._factory.get_linedelta_content(
 
1844
                            data)
1783
1845
                    # Now that we are yielding the data for this key, remove it
1784
1846
                    # from the list
1785
1847
                    keys.remove(key)
1790
1852
                    for line in line_iterator:
1791
1853
                        yield line, key
1792
1854
                done = True
1793
 
            except errors.RetryWithNewPacks, e:
 
1855
            except errors.RetryWithNewPacks as e:
1794
1856
                self._access.reload_or_raise(e)
1795
1857
        # If there are still keys we've not yet found, we look in the fallback
1796
1858
        # vfs, and hope to find them there.  Note that if the keys are found
1797
1859
        # but had no changes or no content, the fallback may not return
1798
1860
        # anything.
1799
 
        if keys and not self._fallback_vfs:
 
1861
        if keys and not self._immediate_fallback_vfs:
1800
1862
            # XXX: strictly the second parameter is meant to be the file id
1801
1863
            # but it's not easily accessible here.
1802
1864
            raise RevisionNotPresent(keys, repr(self))
1803
 
        for source in self._fallback_vfs:
 
1865
        for source in self._immediate_fallback_vfs:
1804
1866
            if not keys:
1805
1867
                break
1806
1868
            source_keys = set()
1808
1870
                source_keys.add(key)
1809
1871
                yield line, key
1810
1872
            keys.difference_update(source_keys)
1811
 
        pb.update('Walking content', total, total)
 
1873
        pb.update(gettext('Walking content'), total, total)
1812
1874
 
1813
1875
    def _make_line_delta(self, delta_seq, new_content):
1814
1876
        """Generate a line delta from delta_seq and new_content."""
1816
1878
        for op in delta_seq.get_opcodes():
1817
1879
            if op[0] == 'equal':
1818
1880
                continue
1819
 
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
 
1881
            diff_hunks.append(
 
1882
                (op[1], op[2], op[4] - op[3], new_content._lines[op[3]:op[4]]))
1820
1883
        return diff_hunks
1821
1884
 
1822
1885
    def _merge_annotations(self, content, parents, parent_texts={},
1846
1909
                    # this copies (origin, text) pairs across to the new
1847
1910
                    # content for any line that matches the last-checked
1848
1911
                    # parent.
1849
 
                    content._lines[j:j+n] = merge_content._lines[i:i+n]
 
1912
                    content._lines[j:j + n] = merge_content._lines[i:i + n]
1850
1913
            # XXX: Robert says the following block is a workaround for a
1851
1914
            # now-fixed bug and it can probably be deleted. -- mbp 20080618
1852
 
            if content._lines and content._lines[-1][1][-1] != '\n':
 
1915
            if content._lines and not content._lines[-1][1].endswith(b'\n'):
1853
1916
                # The copied annotation was from a line without a trailing EOL,
1854
1917
                # reinstate one for the content object, to ensure correct
1855
1918
                # serialization.
1856
 
                line = content._lines[-1][1] + '\n'
 
1919
                line = content._lines[-1][1] + b'\n'
1857
1920
                content._lines[-1] = (content._lines[-1][0], line)
1858
1921
        if delta:
1859
1922
            if delta_seq is None:
1861
1924
                new_texts = content.text()
1862
1925
                old_texts = reference_content.text()
1863
1926
                delta_seq = patiencediff.PatienceSequenceMatcher(
1864
 
                                                 None, old_texts, new_texts)
 
1927
                    None, old_texts, new_texts)
1865
1928
            return self._make_line_delta(delta_seq, content)
1866
1929
 
1867
1930
    def _parse_record(self, version_id, data):
1879
1942
        :return: the header and the decompressor stream.
1880
1943
                 as (stream, header_record)
1881
1944
        """
1882
 
        df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
 
1945
        df = gzip.GzipFile(mode='rb', fileobj=BytesIO(raw_data))
1883
1946
        try:
1884
1947
            # Current serialise
1885
1948
            rec = self._check_header(key, df.readline())
1886
 
        except Exception, e:
 
1949
        except Exception as e:
1887
1950
            raise KnitCorrupt(self,
1888
1951
                              "While reading {%s} got %s(%s)"
1889
1952
                              % (key, e.__class__.__name__, str(e)))
1894
1957
        # 4168 calls in 2880 217 internal
1895
1958
        # 4168 calls to _parse_record_header in 2121
1896
1959
        # 4168 calls to readlines in 330
1897
 
        df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(data))
1898
 
        try:
1899
 
            record_contents = df.readlines()
1900
 
        except Exception, e:
1901
 
            raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1902
 
                (data, e.__class__.__name__, str(e)))
1903
 
        header = record_contents.pop(0)
1904
 
        rec = self._split_header(header)
1905
 
        last_line = record_contents.pop()
1906
 
        if len(record_contents) != int(rec[2]):
1907
 
            raise KnitCorrupt(self,
1908
 
                              'incorrect number of lines %s != %s'
1909
 
                              ' for version {%s} %s'
1910
 
                              % (len(record_contents), int(rec[2]),
1911
 
                                 rec[1], record_contents))
1912
 
        if last_line != 'end %s\n' % rec[1]:
1913
 
            raise KnitCorrupt(self,
1914
 
                              'unexpected version end line %r, wanted %r'
1915
 
                              % (last_line, rec[1]))
1916
 
        df.close()
 
1960
        with gzip.GzipFile(mode='rb', fileobj=BytesIO(data)) as df:
 
1961
            try:
 
1962
                record_contents = df.readlines()
 
1963
            except Exception as e:
 
1964
                raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
 
1965
                                  (data, e.__class__.__name__, str(e)))
 
1966
            header = record_contents.pop(0)
 
1967
            rec = self._split_header(header)
 
1968
            last_line = record_contents.pop()
 
1969
            if len(record_contents) != int(rec[2]):
 
1970
                raise KnitCorrupt(self,
 
1971
                                  'incorrect number of lines %s != %s'
 
1972
                                  ' for version {%s} %s'
 
1973
                                  % (len(record_contents), int(rec[2]),
 
1974
                                     rec[1], record_contents))
 
1975
            if last_line != b'end %s\n' % rec[1]:
 
1976
                raise KnitCorrupt(self,
 
1977
                                  'unexpected version end line %r, wanted %r'
 
1978
                                  % (last_line, rec[1]))
1917
1979
        return rec, record_contents
1918
1980
 
1919
1981
    def _read_records_iter(self, records):
1922
1984
        The result will be returned in whatever is the fastest to read.
1923
1985
        Not by the order requested. Also, multiple requests for the same
1924
1986
        record will only yield 1 response.
 
1987
 
1925
1988
        :param records: A list of (key, access_memo) entries
1926
1989
        :return: Yields (key, contents, digest) in the order
1927
1990
                 read, not the order requested
1939
2002
        raw_data = self._access.get_raw_records(
1940
2003
            [index_memo for key, index_memo in needed_records])
1941
2004
 
1942
 
        for (key, index_memo), data in \
1943
 
                izip(iter(needed_records), raw_data):
 
2005
        for (key, index_memo), data in zip(needed_records, raw_data):
1944
2006
            content, digest = self._parse_record(key[-1], data)
1945
2007
            yield key, content, digest
1946
2008
 
1972
2034
        if len(records):
1973
2035
            # grab the disk data needed.
1974
2036
            needed_offsets = [index_memo for key, index_memo
1975
 
                                           in records]
 
2037
                              in records]
1976
2038
            raw_records = self._access.get_raw_records(needed_offsets)
1977
2039
 
1978
2040
        for key, index_memo in records:
1979
 
            data = raw_records.next()
 
2041
            data = next(raw_records)
1980
2042
            yield key, data
1981
2043
 
1982
2044
    def _record_to_data(self, key, digest, lines, dense_lines=None):
1985
2047
        :param key: The key of the record. Currently keys are always serialised
1986
2048
            using just the trailing component.
1987
2049
        :param dense_lines: The bytes of lines but in a denser form. For
1988
 
            instance, if lines is a list of 1000 bytestrings each ending in \n,
1989
 
            dense_lines may be a list with one line in it, containing all the
1990
 
            1000's lines and their \n's. Using dense_lines if it is already
1991
 
            known is a win because the string join to create bytes in this
1992
 
            function spends less time resizing the final string.
1993
 
        :return: (len, a StringIO instance with the raw data ready to read.)
 
2050
            instance, if lines is a list of 1000 bytestrings each ending in
 
2051
            \\n, dense_lines may be a list with one line in it, containing all
 
2052
            the 1000's lines and their \\n's. Using dense_lines if it is
 
2053
            already known is a win because the string join to create bytes in
 
2054
            this function spends less time resizing the final string.
 
2055
        :return: (len, a BytesIO instance with the raw data ready to read.)
1994
2056
        """
1995
 
        chunks = ["version %s %d %s\n" % (key[-1], len(lines), digest)]
 
2057
        chunks = [b"version %s %d %s\n" % (key[-1], len(lines), digest)]
1996
2058
        chunks.extend(dense_lines or lines)
1997
 
        chunks.append("end %s\n" % key[-1])
 
2059
        chunks.append(b"end " + key[-1] + b"\n")
1998
2060
        for chunk in chunks:
1999
 
            if type(chunk) is not str:
 
2061
            if not isinstance(chunk, bytes):
2000
2062
                raise AssertionError(
2001
2063
                    'data must be plain bytes was %s' % type(chunk))
2002
 
        if lines and lines[-1][-1] != '\n':
 
2064
        if lines and not lines[-1].endswith(b'\n'):
2003
2065
            raise ValueError('corrupt lines value %r' % lines)
2004
 
        compressed_bytes = tuned_gzip.chunks_to_gzip(chunks)
 
2066
        compressed_bytes = b''.join(tuned_gzip.chunks_to_gzip(chunks))
2005
2067
        return len(compressed_bytes), compressed_bytes
2006
2068
 
2007
2069
    def _split_header(self, line):
2015
2077
        """See VersionedFiles.keys."""
2016
2078
        if 'evil' in debug.debug_flags:
2017
2079
            trace.mutter_callsite(2, "keys scales with size of history")
2018
 
        sources = [self._index] + self._fallback_vfs
 
2080
        sources = [self._index] + self._immediate_fallback_vfs
2019
2081
        result = set()
2020
2082
        for source in sources:
2021
2083
            result.update(source.keys())
2033
2095
        # Note that _get_content is only called when the _ContentMapGenerator
2034
2096
        # has been constructed with just one key requested for reconstruction.
2035
2097
        if key in self.nonlocal_keys:
2036
 
            record = self.get_record_stream().next()
 
2098
            record = next(self.get_record_stream())
2037
2099
            # Create a content object on the fly
2038
2100
            lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
2039
2101
            return PlainKnitContent(lines, record.key)
2061
2123
 
2062
2124
        missing_keys = set(nonlocal_keys)
2063
2125
        # Read from remote versioned file instances and provide to our caller.
2064
 
        for source in self.vf._fallback_vfs:
 
2126
        for source in self.vf._immediate_fallback_vfs:
2065
2127
            if not missing_keys:
2066
2128
                break
2067
2129
            # Loop over fallback repositories asking them for texts - ignore
2068
2130
            # any missing from a particular fallback.
2069
2131
            for record in source.get_record_stream(missing_keys,
2070
 
                self._ordering, True):
 
2132
                                                   self._ordering, True):
2071
2133
                if record.storage_kind == 'absent':
2072
2134
                    # Not in thie particular stream, may be in one of the
2073
2135
                    # other fallback vfs objects.
2127
2189
                    content = self._contents_map[component_id]
2128
2190
                else:
2129
2191
                    content, delta = self._factory.parse_record(key[-1],
2130
 
                        record, record_details, content,
2131
 
                        copy_base_content=multiple_versions)
 
2192
                                                                record, record_details, content,
 
2193
                                                                copy_base_content=multiple_versions)
2132
2194
                    if multiple_versions:
2133
2195
                        self._contents_map[component_id] = content
2134
2196
 
2156
2218
        """
2157
2219
        lines = []
2158
2220
        # kind marker for dispatch on the far side,
2159
 
        lines.append('knit-delta-closure')
 
2221
        lines.append(b'knit-delta-closure')
2160
2222
        # Annotated or not
2161
2223
        if self.vf._factory.annotated:
2162
 
            lines.append('annotated')
 
2224
            lines.append(b'annotated')
2163
2225
        else:
2164
 
            lines.append('')
 
2226
            lines.append(b'')
2165
2227
        # then the list of keys
2166
 
        lines.append('\t'.join(['\x00'.join(key) for key in self.keys
2167
 
            if key not in self.nonlocal_keys]))
 
2228
        lines.append(b'\t'.join(b'\x00'.join(key) for key in self.keys
 
2229
                                if key not in self.nonlocal_keys))
2168
2230
        # then the _raw_record_map in serialised form:
2169
2231
        map_byte_list = []
2170
2232
        # for each item in the map:
2175
2237
        # one line with next ('' for None)
2176
2238
        # one line with byte count of the record bytes
2177
2239
        # the record bytes
2178
 
        for key, (record_bytes, (method, noeol), next) in \
2179
 
            self._raw_record_map.iteritems():
2180
 
            key_bytes = '\x00'.join(key)
 
2240
        for key, (record_bytes, (method, noeol), next) in viewitems(
 
2241
                self._raw_record_map):
 
2242
            key_bytes = b'\x00'.join(key)
2181
2243
            parents = self.global_map.get(key, None)
2182
2244
            if parents is None:
2183
 
                parent_bytes = 'None:'
 
2245
                parent_bytes = b'None:'
2184
2246
            else:
2185
 
                parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2186
 
            method_bytes = method
 
2247
                parent_bytes = b'\t'.join(b'\x00'.join(key) for key in parents)
 
2248
            method_bytes = method.encode('ascii')
2187
2249
            if noeol:
2188
 
                noeol_bytes = "T"
 
2250
                noeol_bytes = b"T"
2189
2251
            else:
2190
 
                noeol_bytes = "F"
 
2252
                noeol_bytes = b"F"
2191
2253
            if next:
2192
 
                next_bytes = '\x00'.join(next)
 
2254
                next_bytes = b'\x00'.join(next)
2193
2255
            else:
2194
 
                next_bytes = ''
2195
 
            map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2196
 
                key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2197
 
                len(record_bytes), record_bytes))
2198
 
        map_bytes = ''.join(map_byte_list)
 
2256
                next_bytes = b''
 
2257
            map_byte_list.append(b'\n'.join(
 
2258
                [key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
 
2259
                 b'%d' % len(record_bytes), record_bytes]))
 
2260
        map_bytes = b''.join(map_byte_list)
2199
2261
        lines.append(map_bytes)
2200
 
        bytes = '\n'.join(lines)
 
2262
        bytes = b'\n'.join(lines)
2201
2263
        return bytes
2202
2264
 
2203
2265
 
2205
2267
    """Content map generator reading from a VersionedFiles object."""
2206
2268
 
2207
2269
    def __init__(self, versioned_files, keys, nonlocal_keys=None,
2208
 
        global_map=None, raw_record_map=None, ordering='unordered'):
 
2270
                 global_map=None, raw_record_map=None, ordering='unordered'):
2209
2271
        """Create a _ContentMapGenerator.
2210
2272
 
2211
2273
        :param versioned_files: The versioned files that the texts are being
2240
2302
        self._record_map = None
2241
2303
        if raw_record_map is None:
2242
2304
            self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2243
 
                allow_missing=True)
 
2305
                                                                    allow_missing=True)
2244
2306
        else:
2245
2307
            self._raw_record_map = raw_record_map
2246
2308
        # the factory for parsing records
2262
2324
        self.vf = KnitVersionedFiles(None, None)
2263
2325
        start = line_end
2264
2326
        # Annotated or not
2265
 
        line_end = bytes.find('\n', start)
 
2327
        line_end = bytes.find(b'\n', start)
2266
2328
        line = bytes[start:line_end]
2267
2329
        start = line_end + 1
2268
 
        if line == 'annotated':
 
2330
        if line == b'annotated':
2269
2331
            self._factory = KnitAnnotateFactory()
2270
2332
        else:
2271
2333
            self._factory = KnitPlainFactory()
2272
2334
        # list of keys to emit in get_record_stream
2273
 
        line_end = bytes.find('\n', start)
 
2335
        line_end = bytes.find(b'\n', start)
2274
2336
        line = bytes[start:line_end]
2275
2337
        start = line_end + 1
2276
2338
        self.keys = [
2277
 
            tuple(segment.split('\x00')) for segment in line.split('\t')
 
2339
            tuple(segment.split(b'\x00')) for segment in line.split(b'\t')
2278
2340
            if segment]
2279
2341
        # now a loop until the end. XXX: It would be nice if this was just a
2280
2342
        # bunch of the same records as get_record_stream(..., False) gives, but
2282
2344
        end = len(bytes)
2283
2345
        while start < end:
2284
2346
            # 1 line with key
2285
 
            line_end = bytes.find('\n', start)
2286
 
            key = tuple(bytes[start:line_end].split('\x00'))
 
2347
            line_end = bytes.find(b'\n', start)
 
2348
            key = tuple(bytes[start:line_end].split(b'\x00'))
2287
2349
            start = line_end + 1
2288
2350
            # 1 line with parents (None: for None, '' for ())
2289
 
            line_end = bytes.find('\n', start)
 
2351
            line_end = bytes.find(b'\n', start)
2290
2352
            line = bytes[start:line_end]
2291
 
            if line == 'None:':
 
2353
            if line == b'None:':
2292
2354
                parents = None
2293
2355
            else:
2294
2356
                parents = tuple(
2295
 
                    [tuple(segment.split('\x00')) for segment in line.split('\t')
2296
 
                     if segment])
 
2357
                    tuple(segment.split(b'\x00')) for segment in line.split(b'\t')
 
2358
                    if segment)
2297
2359
            self.global_map[key] = parents
2298
2360
            start = line_end + 1
2299
2361
            # one line with method
2300
 
            line_end = bytes.find('\n', start)
 
2362
            line_end = bytes.find(b'\n', start)
2301
2363
            line = bytes[start:line_end]
2302
 
            method = line
 
2364
            method = line.decode('ascii')
2303
2365
            start = line_end + 1
2304
2366
            # one line with noeol
2305
 
            line_end = bytes.find('\n', start)
 
2367
            line_end = bytes.find(b'\n', start)
2306
2368
            line = bytes[start:line_end]
2307
 
            noeol = line == "T"
 
2369
            noeol = line == b"T"
2308
2370
            start = line_end + 1
2309
 
            # one line with next ('' for None)
2310
 
            line_end = bytes.find('\n', start)
 
2371
            # one line with next (b'' for None)
 
2372
            line_end = bytes.find(b'\n', start)
2311
2373
            line = bytes[start:line_end]
2312
2374
            if not line:
2313
2375
                next = None
2314
2376
            else:
2315
 
                next = tuple(bytes[start:line_end].split('\x00'))
 
2377
                next = tuple(bytes[start:line_end].split(b'\x00'))
2316
2378
            start = line_end + 1
2317
2379
            # one line with byte count of the record bytes
2318
 
            line_end = bytes.find('\n', start)
 
2380
            line_end = bytes.find(b'\n', start)
2319
2381
            line = bytes[start:line_end]
2320
2382
            count = int(line)
2321
2383
            start = line_end + 1
2322
2384
            # the record bytes
2323
 
            record_bytes = bytes[start:start+count]
 
2385
            record_bytes = bytes[start:start + count]
2324
2386
            start = start + count
2325
2387
            # put it in the map
2326
2388
            self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2395
2457
        ABI change with the C extension that reads .kndx files.
2396
2458
    """
2397
2459
 
2398
 
    HEADER = "# bzr knit index 8\n"
 
2460
    HEADER = b"# bzr knit index 8\n"
2399
2461
 
2400
2462
    def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
2401
2463
        """Create a _KndxIndex on transport using mapper."""
2440
2502
 
2441
2503
            try:
2442
2504
                for key, options, (_, pos, size), parents in path_keys:
 
2505
                    if not all(isinstance(option, bytes) for option in options):
 
2506
                        raise TypeError(options)
2443
2507
                    if parents is None:
2444
2508
                        # kndx indices cannot be parentless.
2445
2509
                        parents = ()
2446
 
                    line = "\n%s %s %s %s %s :" % (
2447
 
                        key[-1], ','.join(options), pos, size,
2448
 
                        self._dictionary_compress(parents))
2449
 
                    if type(line) is not str:
 
2510
                    line = b' '.join([
 
2511
                        b'\n'
 
2512
                        + key[-1], b','.join(options), b'%d' % pos, b'%d' % size,
 
2513
                        self._dictionary_compress(parents), b':'])
 
2514
                    if not isinstance(line, bytes):
2450
2515
                        raise AssertionError(
2451
2516
                            'data must be utf8 was %s' % type(line))
2452
2517
                    lines.append(line)
2453
2518
                    self._cache_key(key, options, pos, size, parents)
2454
2519
                if len(orig_history):
2455
 
                    self._transport.append_bytes(path, ''.join(lines))
 
2520
                    self._transport.append_bytes(path, b''.join(lines))
2456
2521
                else:
2457
2522
                    self._init_index(path, lines)
2458
2523
            except:
2496
2561
        else:
2497
2562
            index = cache[version_id][5]
2498
2563
        cache[version_id] = (version_id,
2499
 
                                   options,
2500
 
                                   pos,
2501
 
                                   size,
2502
 
                                   parents,
2503
 
                                   index)
 
2564
                             options,
 
2565
                             pos,
 
2566
                             size,
 
2567
                             parents,
 
2568
                             index)
2504
2569
 
2505
2570
    def check_header(self, fp):
2506
2571
        line = fp.readline()
2507
 
        if line == '':
 
2572
        if line == b'':
2508
2573
            # An empty file can actually be treated as though the file doesn't
2509
2574
            # exist yet.
2510
2575
            raise errors.NoSuchFile(self)
2549
2614
        result = {}
2550
2615
        for key in keys:
2551
2616
            if key not in parent_map:
2552
 
                continue # Ghost
 
2617
                continue  # Ghost
2553
2618
            method = self.get_method(key)
 
2619
            if not isinstance(method, str):
 
2620
                raise TypeError(method)
2554
2621
            parents = parent_map[key]
2555
2622
            if method == 'fulltext':
2556
2623
                compression_parent = None
2557
2624
            else:
2558
2625
                compression_parent = parents[0]
2559
 
            noeol = 'no-eol' in self.get_options(key)
 
2626
            noeol = b'no-eol' in self.get_options(key)
2560
2627
            index_memo = self.get_position(key)
2561
2628
            result[key] = (index_memo, compression_parent,
2562
 
                                  parents, (method, noeol))
 
2629
                           parents, (method, noeol))
2563
2630
        return result
2564
2631
 
2565
2632
    def get_method(self, key):
2566
2633
        """Return compression method of specified key."""
2567
2634
        options = self.get_options(key)
2568
 
        if 'fulltext' in options:
 
2635
        if b'fulltext' in options:
2569
2636
            return 'fulltext'
2570
 
        elif 'line-delta' in options:
 
2637
        elif b'line-delta' in options:
2571
2638
            return 'line-delta'
2572
2639
        else:
2573
 
            raise errors.KnitIndexUnknownMethod(self, options)
 
2640
            raise KnitIndexUnknownMethod(self, options)
2574
2641
 
2575
2642
    def get_options(self, key):
2576
2643
        """Return a list representing options.
2608
2675
                                     for suffix in suffix_parents])
2609
2676
                parent_map[key] = parent_keys
2610
2677
                pending_keys.extend([p for p in parent_keys
2611
 
                                        if p not in parent_map])
 
2678
                                     if p not in parent_map])
2612
2679
        return parent_map, missing_keys
2613
2680
 
2614
2681
    def get_parent_map(self, keys):
2632
2699
                pass
2633
2700
            else:
2634
2701
                result[key] = tuple(prefix + (suffix,) for
2635
 
                    suffix in suffix_parents)
 
2702
                                    suffix in suffix_parents)
2636
2703
        return result
2637
2704
 
2638
2705
    def get_position(self, key):
2646
2713
        entry = self._kndx_cache[prefix][0][suffix]
2647
2714
        return key, entry[2], entry[3]
2648
2715
 
2649
 
    has_key = _mod_index._has_key_from_parent_map
 
2716
    __contains__ = _mod_index._has_key_from_parent_map
2650
2717
 
2651
2718
    def _init_index(self, path, extra_lines=[]):
2652
2719
        """Initialize an index."""
2653
 
        sio = StringIO()
 
2720
        sio = BytesIO()
2654
2721
        sio.write(self.HEADER)
2655
2722
        sio.writelines(extra_lines)
2656
2723
        sio.seek(0)
2657
2724
        self._transport.put_file_non_atomic(path, sio,
2658
 
                            create_parent_dir=True)
2659
 
                           # self._create_parent_dir)
2660
 
                           # mode=self._file_mode,
2661
 
                           # dir_mode=self._dir_mode)
 
2725
                                            create_parent_dir=True)
 
2726
        # self._create_parent_dir)
 
2727
        # mode=self._file_mode,
 
2728
        # dir_mode=self._dir_mode)
2662
2729
 
2663
2730
    def keys(self):
2664
2731
        """Get all the keys in the collection.
2668
2735
        result = set()
2669
2736
        # Identify all key prefixes.
2670
2737
        # XXX: A bit hacky, needs polish.
2671
 
        if type(self._mapper) is ConstantMapper:
 
2738
        if isinstance(self._mapper, ConstantMapper):
2672
2739
            prefixes = [()]
2673
2740
        else:
2674
2741
            relpaths = set()
2693
2760
                self._filename = prefix
2694
2761
                try:
2695
2762
                    path = self._mapper.map(prefix) + '.kndx'
2696
 
                    fp = self._transport.get(path)
2697
 
                    try:
 
2763
                    with self._transport.get(path) as fp:
2698
2764
                        # _load_data may raise NoSuchFile if the target knit is
2699
2765
                        # completely empty.
2700
2766
                        _load_data(self, fp)
2701
 
                    finally:
2702
 
                        fp.close()
2703
2767
                    self._kndx_cache[prefix] = (self._cache, self._history)
2704
2768
                    del self._cache
2705
2769
                    del self._filename
2706
2770
                    del self._history
2707
2771
                except NoSuchFile:
2708
2772
                    self._kndx_cache[prefix] = ({}, [])
2709
 
                    if type(self._mapper) is ConstantMapper:
 
2773
                    if isinstance(self._mapper, ConstantMapper):
2710
2774
                        # preserve behaviour for revisions.kndx etc.
2711
2775
                        self._init_index(path)
2712
2776
                    del self._cache
2732
2796
            '.' prefix.
2733
2797
        """
2734
2798
        if not keys:
2735
 
            return ''
 
2799
            return b''
2736
2800
        result_list = []
2737
2801
        prefix = keys[0][:-1]
2738
2802
        cache = self._kndx_cache[prefix][0]
2742
2806
                raise ValueError("mismatched prefixes for %r" % keys)
2743
2807
            if key[-1] in cache:
2744
2808
                # -- inlined lookup() --
2745
 
                result_list.append(str(cache[key[-1]][5]))
 
2809
                result_list.append(b'%d' % cache[key[-1]][5])
2746
2810
                # -- end lookup () --
2747
2811
            else:
2748
 
                result_list.append('.' + key[-1])
2749
 
        return ' '.join(result_list)
 
2812
                result_list.append(b'.' + key[-1])
 
2813
        return b' '.join(result_list)
2750
2814
 
2751
2815
    def _reset_cache(self):
2752
2816
        # Possibly this should be a LRU cache. A dictionary from key_prefix to
2783
2847
 
2784
2848
    def _split_key(self, key):
2785
2849
        """Split key into a prefix and suffix."""
 
2850
        # GZ 2018-07-03: This is intentionally either a sequence or bytes?
 
2851
        if isinstance(key, bytes):
 
2852
            return key[:-1], key[-1:]
2786
2853
        return key[:-1], key[-1]
2787
2854
 
2788
2855
 
2789
 
class _KeyRefs(object):
2790
 
 
2791
 
    def __init__(self, track_new_keys=False):
2792
 
        # dict mapping 'key' to 'set of keys referring to that key'
2793
 
        self.refs = {}
2794
 
        if track_new_keys:
2795
 
            # set remembering all new keys
2796
 
            self.new_keys = set()
2797
 
        else:
2798
 
            self.new_keys = None
2799
 
 
2800
 
    def clear(self):
2801
 
        if self.refs:
2802
 
            self.refs.clear()
2803
 
        if self.new_keys:
2804
 
            self.new_keys.clear()
2805
 
 
2806
 
    def add_references(self, key, refs):
2807
 
        # Record the new references
2808
 
        for referenced in refs:
2809
 
            try:
2810
 
                needed_by = self.refs[referenced]
2811
 
            except KeyError:
2812
 
                needed_by = self.refs[referenced] = set()
2813
 
            needed_by.add(key)
2814
 
        # Discard references satisfied by the new key
2815
 
        self.add_key(key)
2816
 
 
2817
 
    def get_new_keys(self):
2818
 
        return self.new_keys
2819
 
    
2820
 
    def get_unsatisfied_refs(self):
2821
 
        return self.refs.iterkeys()
2822
 
 
2823
 
    def _satisfy_refs_for_key(self, key):
2824
 
        try:
2825
 
            del self.refs[key]
2826
 
        except KeyError:
2827
 
            # No keys depended on this key.  That's ok.
2828
 
            pass
2829
 
 
2830
 
    def add_key(self, key):
2831
 
        # satisfy refs for key, and remember that we've seen this key.
2832
 
        self._satisfy_refs_for_key(key)
2833
 
        if self.new_keys is not None:
2834
 
            self.new_keys.add(key)
2835
 
 
2836
 
    def satisfy_refs_for_keys(self, keys):
2837
 
        for key in keys:
2838
 
            self._satisfy_refs_for_key(key)
2839
 
 
2840
 
    def get_referrers(self):
2841
 
        result = set()
2842
 
        for referrers in self.refs.itervalues():
2843
 
            result.update(referrers)
2844
 
        return result
2845
 
 
2846
 
 
2847
2856
class _KnitGraphIndex(object):
2848
2857
    """A KnitVersionedFiles index layered on GraphIndex."""
2849
2858
 
2850
2859
    def __init__(self, graph_index, is_locked, deltas=False, parents=True,
2851
 
        add_callback=None, track_external_parent_refs=False):
 
2860
                 add_callback=None, track_external_parent_refs=False):
2852
2861
        """Construct a KnitGraphIndex on a graph_index.
2853
2862
 
2854
 
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
 
2863
        :param graph_index: An implementation of breezy.index.GraphIndex.
2855
2864
        :param is_locked: A callback to check whether the object should answer
2856
2865
            queries.
2857
2866
        :param deltas: Allow delta-compressed records.
2874
2883
            # XXX: TODO: Delta tree and parent graph should be conceptually
2875
2884
            # separate.
2876
2885
            raise KnitCorrupt(self, "Cannot do delta compression without "
2877
 
                "parent tracking.")
 
2886
                              "parent tracking.")
2878
2887
        self.has_graph = parents
2879
2888
        self._is_locked = is_locked
2880
2889
        self._missing_compression_parents = set()
2887
2896
        return "%s(%r)" % (self.__class__.__name__, self._graph_index)
2888
2897
 
2889
2898
    def add_records(self, records, random_id=False,
2890
 
        missing_compression_parents=False):
 
2899
                    missing_compression_parents=False):
2891
2900
        """Add multiple records to the index.
2892
2901
 
2893
2902
        This function does not insert data into the Immutable GraphIndex
2918
2927
                if key_dependencies is not None:
2919
2928
                    key_dependencies.add_references(key, parents)
2920
2929
            index, pos, size = access_memo
2921
 
            if 'no-eol' in options:
2922
 
                value = 'N'
 
2930
            if b'no-eol' in options:
 
2931
                value = b'N'
2923
2932
            else:
2924
 
                value = ' '
2925
 
            value += "%d %d" % (pos, size)
 
2933
                value = b' '
 
2934
            value += b"%d %d" % (pos, size)
2926
2935
            if not self._deltas:
2927
 
                if 'line-delta' in options:
2928
 
                    raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
 
2936
                if b'line-delta' in options:
 
2937
                    raise KnitCorrupt(
 
2938
                        self, "attempt to add line-delta in non-delta knit")
2929
2939
            if self._parents:
2930
2940
                if self._deltas:
2931
 
                    if 'line-delta' in options:
 
2941
                    if b'line-delta' in options:
2932
2942
                        node_refs = (parents, (parents[0],))
2933
2943
                        if missing_compression_parents:
2934
2944
                            compression_parents.add(parents[0])
2939
2949
            else:
2940
2950
                if parents:
2941
2951
                    raise KnitCorrupt(self, "attempt to add node with parents "
2942
 
                        "in parentless index.")
 
2952
                                      "in parentless index.")
2943
2953
                node_refs = ()
2944
2954
            keys[key] = (value, node_refs)
2945
2955
        # check for dups
2950
2960
                # Sometimes these are passed as a list rather than a tuple
2951
2961
                passed = static_tuple.as_tuples(keys[key])
2952
2962
                passed_parents = passed[1][:1]
2953
 
                if (value[0] != keys[key][0][0] or
2954
 
                    parents != passed_parents):
 
2963
                if (value[0:1] != keys[key][0][0:1]
 
2964
                        or parents != passed_parents):
2955
2965
                    node_refs = static_tuple.as_tuples(node_refs)
2956
2966
                    raise KnitCorrupt(self, "inconsistent details in add_records"
2957
 
                        ": %s %s" % ((value, node_refs), passed))
 
2967
                                      ": %s %s" % ((value, node_refs), passed))
2958
2968
                del keys[key]
2959
2969
        result = []
2960
2970
        if self._parents:
2961
 
            for key, (value, node_refs) in keys.iteritems():
 
2971
            for key, (value, node_refs) in viewitems(keys):
2962
2972
                result.append((key, value, node_refs))
2963
2973
        else:
2964
 
            for key, (value, node_refs) in keys.iteritems():
 
2974
            for key, (value, node_refs) in viewitems(keys):
2965
2975
                result.append((key, value))
2966
2976
        self._add_callback(result)
2967
2977
        if missing_compression_parents:
3065
3075
                compression_parent_key = None
3066
3076
            else:
3067
3077
                compression_parent_key = self._compression_parent(entry)
3068
 
            noeol = (entry[2][0] == 'N')
 
3078
            noeol = (entry[2][0:1] == b'N')
3069
3079
            if compression_parent_key:
3070
3080
                method = 'line-delta'
3071
3081
            else:
3072
3082
                method = 'fulltext'
3073
3083
            result[key] = (self._node_to_position(entry),
3074
 
                                  compression_parent_key, parents,
3075
 
                                  (method, noeol))
 
3084
                           compression_parent_key, parents,
 
3085
                           (method, noeol))
3076
3086
        return result
3077
3087
 
3078
3088
    def _get_entries(self, keys, check_present=False):
3120
3130
        e.g. ['foo', 'bar']
3121
3131
        """
3122
3132
        node = self._get_node(key)
3123
 
        options = [self._get_method(node)]
3124
 
        if node[2][0] == 'N':
3125
 
            options.append('no-eol')
 
3133
        options = [self._get_method(node).encode('ascii')]
 
3134
        if node[2][0:1] == b'N':
 
3135
            options.append(b'no-eol')
3126
3136
        return options
3127
3137
 
3128
3138
    def find_ancestry(self, keys):
3156
3166
        node = self._get_node(key)
3157
3167
        return self._node_to_position(node)
3158
3168
 
3159
 
    has_key = _mod_index._has_key_from_parent_map
 
3169
    __contains__ = _mod_index._has_key_from_parent_map
3160
3170
 
3161
3171
    def keys(self):
3162
3172
        """Get all the keys in the collection.
3170
3180
 
3171
3181
    def _node_to_position(self, node):
3172
3182
        """Convert an index value to position details."""
3173
 
        bits = node[2][1:].split(' ')
 
3183
        bits = node[2][1:].split(b' ')
3174
3184
        return node[0], int(bits[0]), int(bits[1])
3175
3185
 
3176
3186
    def _sort_keys_by_io(self, keys, positions):
3221
3231
            opaque index memo. For _KnitKeyAccess the memo is (key, pos,
3222
3232
            length), where the key is the record key.
3223
3233
        """
3224
 
        if type(raw_data) is not str:
 
3234
        if not isinstance(raw_data, bytes):
3225
3235
            raise AssertionError(
3226
3236
                'data must be plain bytes was %s' % type(raw_data))
3227
3237
        result = []
3233
3243
            path = self._mapper.map(key)
3234
3244
            try:
3235
3245
                base = self._transport.append_bytes(path + '.knit',
3236
 
                    raw_data[offset:offset+size])
 
3246
                                                    raw_data[offset:offset + size])
3237
3247
            except errors.NoSuchFile:
3238
3248
                self._transport.mkdir(osutils.dirname(path))
3239
3249
                base = self._transport.append_bytes(path + '.knit',
3240
 
                    raw_data[offset:offset+size])
 
3250
                                                    raw_data[offset:offset + size])
3241
3251
            # if base == 0:
3242
3252
            # chmod.
3243
3253
            offset += size
3246
3256
 
3247
3257
    def flush(self):
3248
3258
        """Flush pending writes on this access object.
3249
 
        
 
3259
 
3250
3260
        For .knit files this is a no-op.
3251
3261
        """
3252
3262
        pass
3278
3288
                yield data
3279
3289
 
3280
3290
 
3281
 
class _DirectPackAccess(object):
3282
 
    """Access to data in one or more packs with less translation."""
3283
 
 
3284
 
    def __init__(self, index_to_packs, reload_func=None, flush_func=None):
3285
 
        """Create a _DirectPackAccess object.
3286
 
 
3287
 
        :param index_to_packs: A dict mapping index objects to the transport
3288
 
            and file names for obtaining data.
3289
 
        :param reload_func: A function to call if we determine that the pack
3290
 
            files have moved and we need to reload our caches. See
3291
 
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
3292
 
        """
3293
 
        self._container_writer = None
3294
 
        self._write_index = None
3295
 
        self._indices = index_to_packs
3296
 
        self._reload_func = reload_func
3297
 
        self._flush_func = flush_func
3298
 
 
3299
 
    def add_raw_records(self, key_sizes, raw_data):
3300
 
        """Add raw knit bytes to a storage area.
3301
 
 
3302
 
        The data is spooled to the container writer in one bytes-record per
3303
 
        raw data item.
3304
 
 
3305
 
        :param sizes: An iterable of tuples containing the key and size of each
3306
 
            raw data segment.
3307
 
        :param raw_data: A bytestring containing the data.
3308
 
        :return: A list of memos to retrieve the record later. Each memo is an
3309
 
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
3310
 
            length), where the index field is the write_index object supplied
3311
 
            to the PackAccess object.
3312
 
        """
3313
 
        if type(raw_data) is not str:
3314
 
            raise AssertionError(
3315
 
                'data must be plain bytes was %s' % type(raw_data))
3316
 
        result = []
3317
 
        offset = 0
3318
 
        for key, size in key_sizes:
3319
 
            p_offset, p_length = self._container_writer.add_bytes_record(
3320
 
                raw_data[offset:offset+size], [])
3321
 
            offset += size
3322
 
            result.append((self._write_index, p_offset, p_length))
3323
 
        return result
3324
 
 
3325
 
    def flush(self):
3326
 
        """Flush pending writes on this access object.
3327
 
 
3328
 
        This will flush any buffered writes to a NewPack.
3329
 
        """
3330
 
        if self._flush_func is not None:
3331
 
            self._flush_func()
3332
 
            
3333
 
    def get_raw_records(self, memos_for_retrieval):
3334
 
        """Get the raw bytes for a records.
3335
 
 
3336
 
        :param memos_for_retrieval: An iterable containing the (index, pos,
3337
 
            length) memo for retrieving the bytes. The Pack access method
3338
 
            looks up the pack to use for a given record in its index_to_pack
3339
 
            map.
3340
 
        :return: An iterator over the bytes of the records.
3341
 
        """
3342
 
        # first pass, group into same-index requests
3343
 
        request_lists = []
3344
 
        current_index = None
3345
 
        for (index, offset, length) in memos_for_retrieval:
3346
 
            if current_index == index:
3347
 
                current_list.append((offset, length))
3348
 
            else:
3349
 
                if current_index is not None:
3350
 
                    request_lists.append((current_index, current_list))
3351
 
                current_index = index
3352
 
                current_list = [(offset, length)]
3353
 
        # handle the last entry
3354
 
        if current_index is not None:
3355
 
            request_lists.append((current_index, current_list))
3356
 
        for index, offsets in request_lists:
3357
 
            try:
3358
 
                transport, path = self._indices[index]
3359
 
            except KeyError:
3360
 
                # A KeyError here indicates that someone has triggered an index
3361
 
                # reload, and this index has gone missing, we need to start
3362
 
                # over.
3363
 
                if self._reload_func is None:
3364
 
                    # If we don't have a _reload_func there is nothing that can
3365
 
                    # be done
3366
 
                    raise
3367
 
                raise errors.RetryWithNewPacks(index,
3368
 
                                               reload_occurred=True,
3369
 
                                               exc_info=sys.exc_info())
3370
 
            try:
3371
 
                reader = pack.make_readv_reader(transport, path, offsets)
3372
 
                for names, read_func in reader.iter_records():
3373
 
                    yield read_func(None)
3374
 
            except errors.NoSuchFile:
3375
 
                # A NoSuchFile error indicates that a pack file has gone
3376
 
                # missing on disk, we need to trigger a reload, and start over.
3377
 
                if self._reload_func is None:
3378
 
                    raise
3379
 
                raise errors.RetryWithNewPacks(transport.abspath(path),
3380
 
                                               reload_occurred=False,
3381
 
                                               exc_info=sys.exc_info())
3382
 
 
3383
 
    def set_writer(self, writer, index, transport_packname):
3384
 
        """Set a writer to use for adding data."""
3385
 
        if index is not None:
3386
 
            self._indices[index] = transport_packname
3387
 
        self._container_writer = writer
3388
 
        self._write_index = index
3389
 
 
3390
 
    def reload_or_raise(self, retry_exc):
3391
 
        """Try calling the reload function, or re-raise the original exception.
3392
 
 
3393
 
        This should be called after _DirectPackAccess raises a
3394
 
        RetryWithNewPacks exception. This function will handle the common logic
3395
 
        of determining when the error is fatal versus being temporary.
3396
 
        It will also make sure that the original exception is raised, rather
3397
 
        than the RetryWithNewPacks exception.
3398
 
 
3399
 
        If this function returns, then the calling function should retry
3400
 
        whatever operation was being performed. Otherwise an exception will
3401
 
        be raised.
3402
 
 
3403
 
        :param retry_exc: A RetryWithNewPacks exception.
3404
 
        """
3405
 
        is_error = False
3406
 
        if self._reload_func is None:
3407
 
            is_error = True
3408
 
        elif not self._reload_func():
3409
 
            # The reload claimed that nothing changed
3410
 
            if not retry_exc.reload_occurred:
3411
 
                # If there wasn't an earlier reload, then we really were
3412
 
                # expecting to find changes. We didn't find them, so this is a
3413
 
                # hard error
3414
 
                is_error = True
3415
 
        if is_error:
3416
 
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
3417
 
            raise exc_class, exc_value, exc_traceback
3418
 
 
3419
 
 
3420
 
# Deprecated, use PatienceSequenceMatcher instead
3421
 
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
3422
 
 
3423
 
 
3424
3291
def annotate_knit(knit, revision_id):
3425
3292
    """Annotate a knit with no cached annotations.
3426
3293
 
3469
3336
            passing to read_records_iter to start reading in the raw data from
3470
3337
            the pack file.
3471
3338
        """
3472
 
        pending = set([key])
 
3339
        pending = {key}
3473
3340
        records = []
3474
3341
        ann_keys = set()
3475
3342
        self._num_needed_children[key] = 1
3480
3347
            self._all_build_details.update(build_details)
3481
3348
            # new_nodes = self._vf._index._get_entries(this_iteration)
3482
3349
            pending = set()
3483
 
            for key, details in build_details.iteritems():
 
3350
            for key, details in viewitems(build_details):
3484
3351
                (index_memo, compression_parent, parent_keys,
3485
3352
                 record_details) = details
3486
3353
                self._parent_map[key] = parent_keys
3488
3355
                records.append((key, index_memo))
3489
3356
                # Do we actually need to check _annotated_lines?
3490
3357
                pending.update([p for p in parent_keys
3491
 
                                   if p not in self._all_build_details])
 
3358
                                if p not in self._all_build_details])
3492
3359
                if parent_keys:
3493
3360
                    for parent_key in parent_keys:
3494
3361
                        if parent_key in self._num_needed_children:
3501
3368
                    else:
3502
3369
                        self._num_compression_children[compression_parent] = 1
3503
3370
 
3504
 
            missing_versions = this_iteration.difference(build_details.keys())
 
3371
            missing_versions = this_iteration.difference(build_details)
3505
3372
            if missing_versions:
3506
3373
                for key in missing_versions:
3507
3374
                    if key in self._parent_map and key in self._text_cache:
3515
3382
                            else:
3516
3383
                                self._num_needed_children[parent_key] = 1
3517
3384
                        pending.update([p for p in parent_keys
3518
 
                                           if p not in self._all_build_details])
 
3385
                                        if p not in self._all_build_details])
3519
3386
                    else:
3520
3387
                        raise errors.RevisionNotPresent(key, self._vf)
3521
3388
        # Generally we will want to read the records in reverse order, because
3524
3391
        return records, ann_keys
3525
3392
 
3526
3393
    def _get_needed_texts(self, key, pb=None):
3527
 
        # if True or len(self._vf._fallback_vfs) > 0:
3528
 
        if len(self._vf._fallback_vfs) > 0:
 
3394
        # if True or len(self._vf._immediate_fallback_vfs) > 0:
 
3395
        if len(self._vf._immediate_fallback_vfs) > 0:
3529
3396
            # If we have fallbacks, go to the generic path
3530
3397
            for v in annotate.Annotator._get_needed_texts(self, key, pb=pb):
3531
3398
                yield v
3534
3401
            try:
3535
3402
                records, ann_keys = self._get_build_graph(key)
3536
3403
                for idx, (sub_key, text, num_lines) in enumerate(
3537
 
                                                self._extract_texts(records)):
 
3404
                        self._extract_texts(records)):
3538
3405
                    if pb is not None:
3539
 
                        pb.update('annotating', idx, len(records))
 
3406
                        pb.update(gettext('annotating'), idx, len(records))
3540
3407
                    yield sub_key, text, num_lines
3541
3408
                for sub_key in ann_keys:
3542
3409
                    text = self._text_cache[sub_key]
3543
 
                    num_lines = len(text) # bad assumption
 
3410
                    num_lines = len(text)  # bad assumption
3544
3411
                    yield sub_key, text, num_lines
3545
3412
                return
3546
 
            except errors.RetryWithNewPacks, e:
 
3413
            except errors.RetryWithNewPacks as e:
3547
3414
                self._vf._access.reload_or_raise(e)
3548
3415
                # The cached build_details are no longer valid
3549
3416
                self._all_build_details.clear()
3550
3417
 
3551
3418
    def _cache_delta_blocks(self, key, compression_parent, delta, lines):
3552
3419
        parent_lines = self._text_cache[compression_parent]
3553
 
        blocks = list(KnitContent.get_line_delta_blocks(delta, parent_lines, lines))
 
3420
        blocks = list(KnitContent.get_line_delta_blocks(
 
3421
            delta, parent_lines, lines))
3554
3422
        self._matching_blocks[(key, compression_parent)] = blocks
3555
3423
 
3556
3424
    def _expand_record(self, key, parent_keys, compression_parent, record,
3609
3477
            parent_annotations = self._annotations_cache[parent_key]
3610
3478
            return parent_annotations, blocks
3611
3479
        return annotate.Annotator._get_parent_annotations_and_matches(self,
3612
 
            key, text, parent_key)
 
3480
                                                                      key, text, parent_key)
3613
3481
 
3614
3482
    def _process_pending(self, key):
3615
3483
        """The content for 'key' was just processed.
3646
3514
                # Note that if there are multiple parents, we need to wait
3647
3515
                # for all of them.
3648
3516
                self._pending_annotation.setdefault(parent_key,
3649
 
                    []).append((key, parent_keys))
 
3517
                                                    []).append((key, parent_keys))
3650
3518
                return False
3651
3519
        return True
3652
3520
 
3707
3575
                    yield key, lines, len(lines)
3708
3576
                    to_process.extend(self._process_pending(key))
3709
3577
 
 
3578
 
3710
3579
try:
3711
 
    from bzrlib._knit_load_data_pyx import _load_data_c as _load_data
3712
 
except ImportError, e:
 
3580
    from ._knit_load_data_pyx import _load_data_c as _load_data
 
3581
except ImportError as e:
3713
3582
    osutils.failed_to_load_extension(e)
3714
 
    from bzrlib._knit_load_data_py import _load_data_py as _load_data
 
3583
    from ._knit_load_data_py import _load_data_py as _load_data