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

  • Committer: Jelmer Vernooij
  • Date: 2017-05-22 00:56:52 UTC
  • mfrom: (6621.2.26 py3_pokes)
  • Revision ID: jelmer@jelmer.uk-20170522005652-yjahcr9hwmjkno7n
Merge Python3 porting work ('py3 pokes')

Show diffs side-by-side

added added

removed removed

Lines of Context:
54
54
from __future__ import absolute_import
55
55
 
56
56
 
57
 
from cStringIO import StringIO
58
57
from itertools import izip
59
58
import operator
60
59
import os
61
60
 
62
 
from breezy.lazy_import import lazy_import
 
61
from .lazy_import import lazy_import
63
62
lazy_import(globals(), """
64
63
import gzip
65
64
 
80
79
from breezy.repofmt import pack_repo
81
80
from breezy.i18n import gettext
82
81
""")
83
 
from breezy import (
 
82
from . import (
84
83
    annotate,
85
84
    errors,
86
85
    osutils,
87
86
    )
88
 
from breezy.errors import (
 
87
from .errors import (
89
88
    NoSuchFile,
90
89
    InvalidRevisionId,
91
90
    KnitCorrupt,
93
92
    RevisionNotPresent,
94
93
    SHA1KnitCorrupt,
95
94
    )
96
 
from breezy.osutils import (
 
95
from .osutils import (
97
96
    contains_whitespace,
98
97
    sha_string,
99
98
    sha_strings,
100
99
    split_lines,
101
100
    )
102
 
from breezy.versionedfile import (
 
101
from .sixish import (
 
102
    BytesIO,
 
103
    )
 
104
from .versionedfile import (
103
105
    _KeyRefs,
104
106
    AbsentContentFactory,
105
107
    adapter_registry,
490
492
    def text(self):
491
493
        try:
492
494
            lines = [text for origin, text in self._lines]
493
 
        except ValueError, e:
 
495
        except ValueError as e:
494
496
            # most commonly (only?) caused by the internal form of the knit
495
497
            # missing annotation information because of a bug - see thread
496
498
            # around 20071015
685
687
        content = knit._get_content(key)
686
688
        # adjust for the fact that serialised annotations are only key suffixes
687
689
        # for this factory.
688
 
        if type(key) is tuple:
 
690
        if isinstance(key, tuple):
689
691
            prefix = key[:-1]
690
692
            origins = content.annotate()
691
693
            result = []
997
999
            lines = osutils.split_lines(line_bytes)
998
1000
 
999
1001
        for element in key[:-1]:
1000
 
            if type(element) is not str:
 
1002
            if not isinstance(element, str):
1001
1003
                raise TypeError("key contains non-strings: %r" % (key,))
1002
1004
        if key[-1] is None:
1003
1005
            key = key[:-1] + ('sha1:' + digest,)
1004
 
        elif type(key[-1]) is not str:
 
1006
        elif not isinstance(key[-1], str):
1005
1007
                raise TypeError("key contains non-strings: %r" % (key,))
1006
1008
        # Knit hunks are still last-element only
1007
1009
        version_id = key[-1]
1127
1129
                # boundaries.
1128
1130
                build_details = self._index.get_build_details([parent])
1129
1131
                parent_details = build_details[parent]
1130
 
            except (RevisionNotPresent, KeyError), e:
 
1132
            except (RevisionNotPresent, KeyError) as e:
1131
1133
                # Some basis is not locally present: always fulltext
1132
1134
                return False
1133
1135
            index_memo, compression_parent, _, _ = parent_details
1290
1292
                    (record_details, index_memo, next) = position_map[key]
1291
1293
                    raw_record_map[key] = data, record_details, next
1292
1294
                return raw_record_map
1293
 
            except errors.RetryWithNewPacks, e:
 
1295
            except errors.RetryWithNewPacks as e:
1294
1296
                self._access.reload_or_raise(e)
1295
1297
 
1296
1298
    @classmethod
1399
1401
                    remaining_keys.discard(content_factory.key)
1400
1402
                    yield content_factory
1401
1403
                return
1402
 
            except errors.RetryWithNewPacks, e:
 
1404
            except errors.RetryWithNewPacks as e:
1403
1405
                self._access.reload_or_raise(e)
1404
1406
 
1405
1407
    def _get_remaining_record_stream(self, keys, ordering,
1563
1565
        else:
1564
1566
            # self is not annotated, but we can strip annotations cheaply.
1565
1567
            annotated = ""
1566
 
            convertibles = set(["knit-annotated-ft-gz"])
 
1568
            convertibles = {"knit-annotated-ft-gz"}
1567
1569
            if self._max_delta_chain:
1568
1570
                delta_types.add("knit-annotated-delta-gz")
1569
1571
                convertibles.add("knit-annotated-delta-gz")
1610
1612
            elif ((record.storage_kind in knit_types)
1611
1613
                  and (compression_parent is None
1612
1614
                       or not self._immediate_fallback_vfs
1613
 
                       or self._index.has_key(compression_parent)
1614
 
                       or not self.has_key(compression_parent))):
 
1615
                       or compression_parent in self._index
 
1616
                       or compression_parent not in self)):
1615
1617
                # we can insert the knit record literally if either it has no
1616
1618
                # compression parent OR we already have its basis in this kvf
1617
1619
                # OR the basis is not present even in the fallbacks.  In the
1619
1621
                # will be well, or it won't turn up at all and we'll raise an
1620
1622
                # error at the end.
1621
1623
                #
1622
 
                # TODO: self.has_key is somewhat redundant with
1623
 
                # self._index.has_key; we really want something that directly
 
1624
                # TODO: self.__contains__ is somewhat redundant with
 
1625
                # self._index.__contains__; we really want something that directly
1624
1626
                # asks if it's only present in the fallbacks. -- mbp 20081119
1625
1627
                if record.storage_kind not in native_types:
1626
1628
                    try:
1659
1661
                    #
1660
1662
                    # They're required to be physically in this
1661
1663
                    # KnitVersionedFiles, not in a fallback.
1662
 
                    if not self._index.has_key(compression_parent):
 
1664
                    if compression_parent not in self._index:
1663
1665
                        pending = buffered_index_entries.setdefault(
1664
1666
                            compression_parent, [])
1665
1667
                        pending.append(index_entry)
1781
1783
                    for line in line_iterator:
1782
1784
                        yield line, key
1783
1785
                done = True
1784
 
            except errors.RetryWithNewPacks, e:
 
1786
            except errors.RetryWithNewPacks as e:
1785
1787
                self._access.reload_or_raise(e)
1786
1788
        # If there are still keys we've not yet found, we look in the fallback
1787
1789
        # vfs, and hope to find them there.  Note that if the keys are found
1870
1872
        :return: the header and the decompressor stream.
1871
1873
                 as (stream, header_record)
1872
1874
        """
1873
 
        df = gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
 
1875
        df = gzip.GzipFile(mode='rb', fileobj=BytesIO(raw_data))
1874
1876
        try:
1875
1877
            # Current serialise
1876
1878
            rec = self._check_header(key, df.readline())
1877
 
        except Exception, e:
 
1879
        except Exception as e:
1878
1880
            raise KnitCorrupt(self,
1879
1881
                              "While reading {%s} got %s(%s)"
1880
1882
                              % (key, e.__class__.__name__, str(e)))
1885
1887
        # 4168 calls in 2880 217 internal
1886
1888
        # 4168 calls to _parse_record_header in 2121
1887
1889
        # 4168 calls to readlines in 330
1888
 
        df = gzip.GzipFile(mode='rb', fileobj=StringIO(data))
 
1890
        df = gzip.GzipFile(mode='rb', fileobj=BytesIO(data))
1889
1891
        try:
1890
1892
            record_contents = df.readlines()
1891
 
        except Exception, e:
 
1893
        except Exception as e:
1892
1894
            raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1893
1895
                (data, e.__class__.__name__, str(e)))
1894
1896
        header = record_contents.pop(0)
1982
1984
            the 1000's lines and their \\n's. Using dense_lines if it is
1983
1985
            already known is a win because the string join to create bytes in
1984
1986
            this function spends less time resizing the final string.
1985
 
        :return: (len, a StringIO instance with the raw data ready to read.)
 
1987
        :return: (len, a BytesIO instance with the raw data ready to read.)
1986
1988
        """
1987
1989
        chunks = ["version %s %d %s\n" % (key[-1], len(lines), digest)]
1988
1990
        chunks.extend(dense_lines or lines)
1989
1991
        chunks.append("end %s\n" % key[-1])
1990
1992
        for chunk in chunks:
1991
 
            if type(chunk) is not str:
 
1993
            if not isinstance(chunk, str):
1992
1994
                raise AssertionError(
1993
1995
                    'data must be plain bytes was %s' % type(chunk))
1994
1996
        if lines and lines[-1][-1] != '\n':
2438
2440
                    line = "\n%s %s %s %s %s :" % (
2439
2441
                        key[-1], ','.join(options), pos, size,
2440
2442
                        self._dictionary_compress(parents))
2441
 
                    if type(line) is not str:
 
2443
                    if not isinstance(line, str):
2442
2444
                        raise AssertionError(
2443
2445
                            'data must be utf8 was %s' % type(line))
2444
2446
                    lines.append(line)
2638
2640
        entry = self._kndx_cache[prefix][0][suffix]
2639
2641
        return key, entry[2], entry[3]
2640
2642
 
2641
 
    has_key = _mod_index._has_key_from_parent_map
 
2643
    __contains__ = _mod_index._has_key_from_parent_map
2642
2644
 
2643
2645
    def _init_index(self, path, extra_lines=[]):
2644
2646
        """Initialize an index."""
2645
 
        sio = StringIO()
 
2647
        sio = BytesIO()
2646
2648
        sio.write(self.HEADER)
2647
2649
        sio.writelines(extra_lines)
2648
2650
        sio.seek(0)
2660
2662
        result = set()
2661
2663
        # Identify all key prefixes.
2662
2664
        # XXX: A bit hacky, needs polish.
2663
 
        if type(self._mapper) is ConstantMapper:
 
2665
        if isinstance(self._mapper, ConstantMapper):
2664
2666
            prefixes = [()]
2665
2667
        else:
2666
2668
            relpaths = set()
2698
2700
                    del self._history
2699
2701
                except NoSuchFile:
2700
2702
                    self._kndx_cache[prefix] = ({}, [])
2701
 
                    if type(self._mapper) is ConstantMapper:
 
2703
                    if isinstance(self._mapper, ConstantMapper):
2702
2704
                        # preserve behaviour for revisions.kndx etc.
2703
2705
                        self._init_index(path)
2704
2706
                    del self._cache
3090
3092
        node = self._get_node(key)
3091
3093
        return self._node_to_position(node)
3092
3094
 
3093
 
    has_key = _mod_index._has_key_from_parent_map
 
3095
    __contains__ = _mod_index._has_key_from_parent_map
3094
3096
 
3095
3097
    def keys(self):
3096
3098
        """Get all the keys in the collection.
3155
3157
            opaque index memo. For _KnitKeyAccess the memo is (key, pos,
3156
3158
            length), where the key is the record key.
3157
3159
        """
3158
 
        if type(raw_data) is not str:
 
3160
        if not isinstance(raw_data, str):
3159
3161
            raise AssertionError(
3160
3162
                'data must be plain bytes was %s' % type(raw_data))
3161
3163
        result = []
3260
3262
            passing to read_records_iter to start reading in the raw data from
3261
3263
            the pack file.
3262
3264
        """
3263
 
        pending = set([key])
 
3265
        pending = {key}
3264
3266
        records = []
3265
3267
        ann_keys = set()
3266
3268
        self._num_needed_children[key] = 1
3334
3336
                    num_lines = len(text) # bad assumption
3335
3337
                    yield sub_key, text, num_lines
3336
3338
                return
3337
 
            except errors.RetryWithNewPacks, e:
 
3339
            except errors.RetryWithNewPacks as e:
3338
3340
                self._vf._access.reload_or_raise(e)
3339
3341
                # The cached build_details are no longer valid
3340
3342
                self._all_build_details.clear()
3499
3501
                    to_process.extend(self._process_pending(key))
3500
3502
 
3501
3503
try:
3502
 
    from breezy._knit_load_data_pyx import _load_data_c as _load_data
3503
 
except ImportError, e:
 
3504
    from ._knit_load_data_pyx import _load_data_c as _load_data
 
3505
except ImportError as e:
3504
3506
    osutils.failed_to_load_extension(e)
3505
 
    from breezy._knit_load_data_py import _load_data_py as _load_data
 
3507
    from ._knit_load_data_py import _load_data_py as _load_data