Debian Codegraph @

strictyaml/ruamel/compat.py

raw
1 # coding: utf-8
2
3 from __future__ import print_function
4
5 # partially from package six by Benjamin Peterson
6
7 import sys
8 import os
9 import types
10 import traceback
11 from abc import abstractmethod
12
13
14 # fmt: off
15 if False: # MYPY
16 from typing import Any, Dict, Optional, List, Union, BinaryIO, IO, Text, Tuple # NOQA
17 from typing import Optional # NOQA
18 # fmt: on
19
20 _DEFAULT_YAML_VERSION = (1, 2)
21
22 try:
23 from ruamel.ordereddict import ordereddict
24 except: # NOQA
25 try:
26 from collections import OrderedDict
27 except ImportError:
28 from ordereddict import OrderedDict # type: ignore
29 # to get the right name import ... as ordereddict doesn't do that
30
31 class ordereddict(OrderedDict): # type: ignore
32 if not hasattr(OrderedDict, "insert"):
33
34 def insert(self, pos, key, value):
35 # type: (int, Any, Any) -> None
36 if pos >= len(self):
37 self[key] = value
38 return
39 od = ordereddict()
40 od.update(self)
41 for k in od:
42 del self[k]
43 for index, old_key in enumerate(od):
44 if pos == index:
45 self[key] = value
46 self[old_key] = od[old_key]
47
48
49 PY2 = sys.version_info[0] == 2
50 PY3 = sys.version_info[0] == 3
51
52
53 if PY3:
54
55 def utf8(s):
56 # type: (str) -> str
57 return s
58
59 def to_str(s):
60 # type: (str) -> str
61 return s
62
63 def to_unicode(s):
64 # type: (str) -> str
65 return s
66
67
68 else:
69 if False:
70 unicode = str
71
72 def utf8(s):
73 # type: (unicode) -> str
74 return s.encode("utf-8")
75
76 def to_str(s):
77 # type: (str) -> str
78 return str(s)
79
80 def to_unicode(s):
81 # type: (str) -> unicode
82 return unicode(s) # NOQA
83
84
85 if PY3:
86 string_types = str
87 integer_types = int
88 class_types = type
89 text_type = str
90 binary_type = bytes
91
92 MAXSIZE = sys.maxsize
93 unichr = chr
94 import io
95
96 StringIO = io.StringIO
97 BytesIO = io.BytesIO
98 # have unlimited precision
99 no_limit_int = int
100 from collections.abc import (
101 Hashable,
102 MutableSequence,
103 MutableMapping,
104 Mapping,
105 ) # NOQA
106
107 else:
108 string_types = basestring # NOQA
109 integer_types = (int, long) # NOQA
110 class_types = (type, types.ClassType)
111 text_type = unicode # NOQA
112 binary_type = str
113
114 # to allow importing
115 unichr = unichr
116 from StringIO import StringIO as _StringIO
117
118 StringIO = _StringIO
119 import cStringIO
120
121 BytesIO = cStringIO.StringIO
122 # have unlimited precision
123 no_limit_int = long # NOQA not available on Python 3
124 from collections import Hashable, MutableSequence, MutableMapping, Mapping # NOQA
125
126 if False: # MYPY
127 # StreamType = Union[BinaryIO, IO[str], IO[unicode], StringIO]
128 # StreamType = Union[BinaryIO, IO[str], StringIO] # type: ignore
129 StreamType = Any
130
131 StreamTextType = StreamType # Union[Text, StreamType]
132 VersionType = Union[List[int], str, Tuple[int, int]]
133
134 if PY3:
135 builtins_module = "builtins"
136 else:
137 builtins_module = "__builtin__"
138
139 UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2
140
141
142 def with_metaclass(meta, *bases):
143 # type: (Any, Any) -> Any
144 """Create a base class with a metaclass."""
145 return meta("NewBase", bases, {})
146
147
148 DBG_TOKEN = 1
149 DBG_EVENT = 2
150 DBG_NODE = 4
151
152
153 _debug = None # type: Optional[int]
154 if "RUAMELDEBUG" in os.environ:
155 _debugx = os.environ.get("RUAMELDEBUG")
156 if _debugx is None:
157 _debug = 0
158 else:
159 _debug = int(_debugx)
160
161
162 if bool(_debug):
163
164 class ObjectCounter(object):
165 def __init__(self):
166 # type: () -> None
167 self.map = {} # type: Dict[Any, Any]
168
169 def __call__(self, k):
170 # type: (Any) -> None
171 self.map[k] = self.map.get(k, 0) + 1
172
173 def dump(self):
174 # type: () -> None
175 for k in sorted(self.map):
176 sys.stdout.write("{} -> {}".format(k, self.map[k]))
177
178 object_counter = ObjectCounter()
179
180
181 # used from yaml util when testing
182 def dbg(val=None):
183 # type: (Any) -> Any
184 global _debug
185 if _debug is None:
186 # set to true or false
187 _debugx = os.environ.get("YAMLDEBUG")
188 if _debugx is None:
189 _debug = 0
190 else:
191 _debug = int(_debugx)
192 if val is None:
193 return _debug
194 return _debug & val
195
196
197 class Nprint(object):
198 def __init__(self, file_name=None):
199 # type: (Any) -> None
200 self._max_print = None # type: Any
201 self._count = None # type: Any
202 self._file_name = file_name
203
204 def __call__(self, *args, **kw):
205 # type: (Any, Any) -> None
206 if not bool(_debug):
207 return
208 out = sys.stdout if self._file_name is None else open(self._file_name, "a")
209 dbgprint = print # to fool checking for print statements by dv utility
210 kw1 = kw.copy()
211 kw1["file"] = out
212 dbgprint(*args, **kw1)
213 out.flush()
214 if self._max_print is not None:
215 if self._count is None:
216 self._count = self._max_print
217 self._count -= 1
218 if self._count == 0:
219 dbgprint("forced exit\n")
220 traceback.print_stack()
221 out.flush()
222 sys.exit(0)
223 if self._file_name:
224 out.close()
225
226 def set_max_print(self, i):
227 # type: (int) -> None
228 self._max_print = i
229 self._count = None
230
231
232 nprint = Nprint()
233 nprintf = Nprint("/var/tmp/strictyaml.ruamel.log")
234
235 # char checkers following production rules
236
237
238 def check_namespace_char(ch):
239 # type: (Any) -> bool
240 if u"\x21" <= ch <= u"\x7E": # ! to ~
241 return True
242 if u"\xA0" <= ch <= u"\uD7FF":
243 return True
244 if (u"\uE000" <= ch <= u"\uFFFD") and ch != u"\uFEFF": # excl. byte order mark
245 return True
246 if u"\U00010000" <= ch <= u"\U0010FFFF":
247 return True
248 return False
249
250
251 def check_anchorname_char(ch):
252 # type: (Any) -> bool
253 if ch in u",[]{}":
254 return False
255 return check_namespace_char(ch)
256
257
258 def version_tnf(t1, t2=None):
259 # type: (Any, Any) -> Any
260 """
261 return True if strictyaml.ruamel version_info < t1, None if t2 is specified and bigger else False
262 """
263 from strictyaml.ruamel import version_info # NOQA
264
265 if version_info < t1:
266 return True
267 if t2 is not None and version_info < t2:
268 return None
269 return False
270
271
272 class MutableSliceableSequence(MutableSequence): # type: ignore
273 __slots__ = ()
274
275 def __getitem__(self, index):
276 # type: (Any) -> Any
277 if not isinstance(index, slice):
278 return self.__getsingleitem__(index)
279 return type(self)([self[i] for i in range(*index.indices(len(self)))]) # type: ignore
280
281 def __setitem__(self, index, value):
282 # type: (Any, Any) -> None
283 if not isinstance(index, slice):
284 return self.__setsingleitem__(index, value)
285 assert iter(value)
286 # nprint(index.start, index.stop, index.step, index.indices(len(self)))
287 if index.step is None:
288 del self[index.start : index.stop]
289 for elem in reversed(value):
290 self.insert(0 if index.start is None else index.start, elem)
291 else:
292 range_parms = index.indices(len(self))
293 nr_assigned_items = (range_parms[1] - range_parms[0] - 1) // range_parms[
294 2
295 ] + 1
296 # need to test before changing, in case TypeError is caught
297 if nr_assigned_items < len(value):
298 raise TypeError(
299 "too many elements in value {} < {}".format(
300 nr_assigned_items, len(value)
301 )
302 )
303 elif nr_assigned_items > len(value):
304 raise TypeError(
305 "not enough elements in value {} > {}".format(
306 nr_assigned_items, len(value)
307 )
308 )
309 for idx, i in enumerate(range(*range_parms)):
310 self[i] = value[idx]
311
312 def __delitem__(self, index):
313 # type: (Any) -> None
314 if not isinstance(index, slice):
315 return self.__delsingleitem__(index)
316 # nprint(index.start, index.stop, index.step, index.indices(len(self)))
317 for i in reversed(range(*index.indices(len(self)))):
318 del self[i]
319
320 @abstractmethod
321 def __getsingleitem__(self, index):
322 # type: (Any) -> Any
323 raise IndexError
324
325 @abstractmethod
326 def __setsingleitem__(self, index, value):
327 # type: (Any, Any) -> None
328 raise IndexError
329
330 @abstractmethod
331 def __delsingleitem__(self, index):
332 # type: (Any) -> None
333 raise IndexError