|
| 1 | +import chardet |
| 2 | +from typing import Optional, Dict, Any |
| 3 | + |
| 4 | + |
| 5 | +SCRIPTENCODING_PREFIX = bytearray('scriptencoding', encoding='ascii') |
| 6 | +COMMENT_START_TOKEN = bytearray('"', encoding='ascii') |
| 7 | +LF = bytearray("\n", encoding='ascii') |
| 8 | + |
| 9 | + |
| 10 | +class DecodingStrategy(object): |
| 11 | + def decode(self, bytes_seq, debug_hint): |
| 12 | + # type: (bytes, Dict[str, str]) -> Optional[str] |
| 13 | + raise NotImplementedError |
| 14 | + |
| 15 | + |
| 16 | +class DecodingStrategyByChardet(DecodingStrategy): |
| 17 | + def decode(self, bytes_seq, debug_hint): |
| 18 | + # type: (bytes, Dict[str, Any]) -> Optional[str] |
| 19 | + encoding_hint = chardet.detect(bytearray(bytes_seq)) |
| 20 | + encoding = encoding_hint['encoding'] |
| 21 | + |
| 22 | + debug_hint['chardet_encoding'] = encoding_hint['encoding'] |
| 23 | + debug_hint['chardet_confidence'] = encoding_hint['confidence'] |
| 24 | + |
| 25 | + try: |
| 26 | + return bytes_seq.decode(encoding) |
| 27 | + |
| 28 | + except Exception as e: |
| 29 | + debug_hint['chardet_error'] = str(e) |
| 30 | + return None |
| 31 | + |
| 32 | + |
| 33 | +class ComposedDecodingStrategy(DecodingStrategy): |
| 34 | + def __init__(self, strategies): |
| 35 | + # type: ([DecodingStrategy]) -> None |
| 36 | + self.strategies = strategies |
| 37 | + |
| 38 | + |
| 39 | + def decode(self, bytes_seq, debug_hint): |
| 40 | + # type: (bytes, Dict[str, Any]) -> Optional[str] |
| 41 | + |
| 42 | + debug_hint['composed_strategies'] = [type(strategy).__name__ for strategy in self.strategies] |
| 43 | + |
| 44 | + for strategy in self.strategies: |
| 45 | + string_candidate = strategy.decode(bytes_seq, debug_hint) |
| 46 | + |
| 47 | + if string_candidate is None: |
| 48 | + continue |
| 49 | + |
| 50 | + debug_hint['selected_strategy'] = type(strategy).__name__ |
| 51 | + |
| 52 | + return string_candidate |
| 53 | + |
| 54 | + |
| 55 | +class DecodingStrategyForEmpty(DecodingStrategy): |
| 56 | + def decode(self, bytes_seq, debug_hint): |
| 57 | + # type: (bytes, Dict[str, Any]) -> Optional[str] |
| 58 | + if len(bytes_seq) <= 0: |
| 59 | + debug_hint['empty'] = 'true' |
| 60 | + return '' |
| 61 | + |
| 62 | + debug_hint['empty'] = 'false' |
| 63 | + return None |
| 64 | + |
| 65 | + |
| 66 | +class DecodingStrategyByScriptencoding(DecodingStrategy): |
| 67 | + def decode(self, bytes_seq, debug_hint): |
| 68 | + # type: (bytes, Dict[str, Any]) -> Optional[str] |
| 69 | + encoding_part = DecodingStrategyByScriptencoding.parse_script_encoding(bytes_seq, debug_hint) |
| 70 | + |
| 71 | + if encoding_part is None: |
| 72 | + debug_hint['scriptencoding'] = 'None' |
| 73 | + return None |
| 74 | + |
| 75 | + try: |
| 76 | + debug_hint['scriptencoding'] = encoding_part |
| 77 | + return bytes_seq.decode(encoding=encoding_part.decode(encoding='ascii')) |
| 78 | + |
| 79 | + except LookupError as e: |
| 80 | + debug_hint['scriptencoding_error'] = str(e) |
| 81 | + return None |
| 82 | + |
| 83 | + |
| 84 | + @classmethod |
| 85 | + def parse_script_encoding(cls, bytes_seq, debug_hint): |
| 86 | + # type: (bytes, Dict[str, Any]) -> Optional[bytes] |
| 87 | + try: |
| 88 | + start_index = bytes_seq.index(SCRIPTENCODING_PREFIX) |
| 89 | + encoding_part_start_index = start_index + len(SCRIPTENCODING_PREFIX) |
| 90 | + |
| 91 | + try: |
| 92 | + encoding_part_end_index_candidate_by_line_break = bytes_seq.index(LF, encoding_part_start_index) |
| 93 | + |
| 94 | + try: |
| 95 | + encoding_part_end_index_candidate_by_comment = bytes_seq.index( |
| 96 | + COMMENT_START_TOKEN, encoding_part_start_index) |
| 97 | + |
| 98 | + # Case for :scriptencoding foo "foo\n |
| 99 | + encoding_part_end_index = min( |
| 100 | + encoding_part_end_index_candidate_by_line_break, |
| 101 | + encoding_part_end_index_candidate_by_comment |
| 102 | + ) |
| 103 | + |
| 104 | + except ValueError: |
| 105 | + # Case for :scriptencoding foo\n |
| 106 | + encoding_part_end_index = encoding_part_end_index_candidate_by_line_break |
| 107 | + |
| 108 | + except ValueError: |
| 109 | + try: |
| 110 | + # Case for :scriptencoding foo "foo<EOF> |
| 111 | + encoding_part_end_index_candidate_by_comment = bytes_seq.index( |
| 112 | + COMMENT_START_TOKEN, encoding_part_start_index) |
| 113 | + encoding_part_end_index = encoding_part_end_index_candidate_by_comment |
| 114 | + |
| 115 | + except ValueError: |
| 116 | + # Case for :scriptencoding foo<EOF> |
| 117 | + encoding_part_end_index = len(bytes_seq) - 1 |
| 118 | + |
| 119 | + encoding_part_candidate = bytes_seq[encoding_part_start_index:encoding_part_end_index] |
| 120 | + return encoding_part_candidate.strip() |
| 121 | + |
| 122 | + except ValueError: |
| 123 | + debug_hint['scriptencoding_error'] = '`scriptencoding` is not found' |
| 124 | + return None |
| 125 | + |
| 126 | + |
| 127 | +class DecodingStrategyForUTF8(DecodingStrategy): |
| 128 | + def decode(self, bytes_seq, debug_hint): |
| 129 | + # type: (bytes, Dict[str, Any]) -> Optional[str] |
| 130 | + try: |
| 131 | + string = bytes_seq.decode('utf8') |
| 132 | + |
| 133 | + debug_hint['utf-8'] = 'success' |
| 134 | + return string |
| 135 | + |
| 136 | + except Exception as e: |
| 137 | + debug_hint['utf-8'] = 'failed: {}'.format(str(e)) |
| 138 | + |
| 139 | + return None |
| 140 | + |
| 141 | + |
| 142 | +default_decoding_strategy = ComposedDecodingStrategy([ |
| 143 | + DecodingStrategyForEmpty(), |
| 144 | + DecodingStrategyByScriptencoding(), |
| 145 | + DecodingStrategyForUTF8(), |
| 146 | + DecodingStrategyByChardet(), |
| 147 | +]) |
0 commit comments