Debian Codegraph @

strictyaml/representation.py

raw
1 from strictyaml.ruamel.comments import CommentedSeq, CommentedMap
2 from strictyaml.exceptions import raise_type_error, YAMLSerializationError
3 from strictyaml.yamllocation import YAMLChunk
4 from strictyaml.dumper import StrictYAMLDumper
5 from strictyaml.ruamel import dump, scalarstring
6 from copy import copy
7 import decimal
8 import sys
9
10
11 if sys.version_info[0] == 3:
12 unicode = str
13
14 if sys.version_info[:2] < (3, 7):
15 from collections import OrderedDict as OrderedDictBase
16
17 class OrderedDict(OrderedDictBase):
18 def __repr__(self):
19 return (
20 "{"
21 + ", ".join("{}: {}".format(repr(k), repr(v)) for k, v in self.items())
22 + "}"
23 )
24
25 else:
26 OrderedDict = dict
27
28
29 class YAMLIterator(object):
30 def __init__(self, yaml_object):
31 self._yaml_object = yaml_object
32 self._index = 0
33
34 def __iter__(self):
35 return self
36
37 def next(self):
38 return self.__next__()
39
40 def __next__(self):
41 if self._index >= len(self._yaml_object):
42 raise StopIteration
43 else:
44 self._index = self._index + 1
45 return self._yaml_object[self._index - 1]
46
47
48 class YAML(object):
49 """
50 A YAML object represents a block of YAML which can be:
51
52 * Used to extract parsed data from the YAML (.data).
53 * Used to render to a string of YAML, with comments (.as_yaml()).
54 * Revalidated with a stricter schema (.revalidate(schema)).
55 """
56
57 def __init__(self, value, validator=None):
58 if isinstance(value, YAMLChunk):
59 self._chunk = value
60 self._validator = validator
61 if value.is_scalar():
62 self._value = validator.validate(value)
63 if isinstance(self._value, YAML):
64 self._value = self._value._value
65 self._text = value.contents
66 else:
67 self._value = (
68 value.strictparsed()._value
69 if isinstance(value.strictparsed(), YAML)
70 else value.strictparsed()
71 )
72 self._text = None
73 elif isinstance(value, YAML):
74 self._chunk = value._chunk
75 self._validator = validator if validator is not None else value.validator
76 self._value = value._value
77 self._text = value._text
78 else:
79 self._chunk = YAMLChunk(value)
80 self._validator = validator
81 self._value = value
82 self._text = unicode(value)
83 self._selected_validator = None
84 assert not isinstance(self._value, YAML)
85
86 def __int__(self):
87 # TODO: Raise more sensible exception if not int
88 return int(self._value)
89
90 def __str__(self):
91 if not self.is_scalar():
92 raise TypeError(
93 "Cannot cast mapping/sequence '{0}' to string".format(repr(self._value))
94 )
95 elif type(self._value) in (unicode, str, int, float, decimal.Decimal):
96 return unicode(self._value)
97 else:
98 raise_type_error(
99 repr(self), "str", "str(yamlobj.data) or str(yamlobj.text)"
100 )
101
102 def __unicode__(self):
103 return self.__str__()
104
105 def revalidate(self, schema):
106 if self.is_scalar():
107 self._value = schema(self._chunk)._value
108 else:
109 result = schema(self._chunk)
110 self._selected_validator = result._selected_validator
111 self._validator = schema
112
113 @property
114 def data(self):
115 """
116 Returns raw data representation of the document or document segment.
117
118 Mappings are rendered as ordered dicts, sequences as lists and scalar values
119 as whatever the validator returns (int, string, etc.).
120
121 If no validators are used, scalar values are always returned as strings.
122 """
123 if isinstance(self._value, CommentedMap):
124 mapping = OrderedDict()
125 for key, value in self._value.items():
126 """
127 #if isinstance(key, YAML):
128 #mapping[key.data] = value.data if isinstance(value, YAML) else value
129 """
130 mapping[key.data] = value.data
131 return mapping
132 elif isinstance(self._value, CommentedSeq):
133 return [item.data for item in self._value]
134 else:
135 if isinstance(self._value, scalarstring.ScalarString):
136 return str(self._value)
137 return self._value
138
139 def as_marked_up(self):
140 """
141 Returns strictyaml.ruamel CommentedSeq/CommentedMap objects
142 with comments. This can be fed directly into a strictyaml.ruamel
143 dumper.
144 """
145 return self._chunk.contents
146
147 @property
148 def start_line(self):
149 """
150 Return line number that the element starts on (including preceding comments).
151 """
152 return self._chunk.start_line()
153
154 @property
155 def end_line(self):
156 """
157 Return line number that the element ends on (including trailing comments).
158 """
159 return self._chunk.end_line()
160
161 def lines(self):
162 """
163 Return a string of the lines which make up the selected line
164 including preceding and trailing comments.
165 """
166 return self._chunk.lines()
167
168 def lines_before(self, how_many):
169 return self._chunk.lines_before(how_many)
170
171 def lines_after(self, how_many):
172 return self._chunk.lines_after(how_many)
173
174 def __float__(self):
175 return float(self._value)
176
177 def __repr__(self):
178 return "YAML({0})".format(self.data)
179
180 def __bool__(self):
181 if isinstance(self._value, bool):
182 return self._value
183 else:
184 raise_type_error(
185 repr(self), "bool", "bool(yamlobj.data) or bool(yamlobj.text)"
186 )
187
188 def _strictindex(self, index):
189 if isinstance(index, YAML):
190 index = index.data
191 if self.is_mapping():
192 key_validator = (
193 self._selected_validator.key_validator
194 if self._selected_validator is not None
195 else self._validator.key_validator
196 )
197 return key_validator(YAMLChunk(index)).data
198 else:
199 return index
200
201 def __nonzero__(self):
202 return self.__bool__()
203
204 def __getitem__(self, index):
205 return self._value[self._strictindex(index)]
206
207 def __setitem__(self, index, value):
208 strictindex = self._strictindex(index)
209
210 # Generate nice error messages - first, copy our whole node's data
211 # and use ``to_yaml()`` to determine if the resulting data would
212 # validate our schema. Must replace whole current node to support
213 # complex types, e.g. ``EmptyList() | Seq(Str())``.
214 if isinstance(value, YAML):
215 yaml_value = self._chunk.fork(strictindex, value)
216 new_value = self._validator(yaml_value)
217 else:
218 old_data = self.data
219 if isinstance(old_data, dict):
220 old_data[index] = value
221 elif isinstance(old_data, list):
222 if len(old_data) <= index:
223 raise YAMLSerializationError(
224 "cannot extend list via __setitem__. "
225 "Instead, replace whole list on parent "
226 "node."
227 )
228 old_data[index] = value
229 else:
230 raise NotImplementedError(repr(old_data))
231 yaml_value = YAMLChunk(self._validator.to_yaml(old_data))
232 yaml_value_repr = self._validator(yaml_value)
233
234 # Now that the new content is properly validated, create a valid
235 # chunk with the new information.
236 forked_chunk = self._chunk.fork(strictindex, yaml_value_repr[strictindex])
237 new_value = self._validator(forked_chunk)
238
239 # Now, overwrite our chunk and value with the new information.
240 old_chunk = self._chunk # Needed for reference to pre-fork ruamel
241 self._chunk = new_value._chunk
242 self._value = new_value._value
243 self._text = new_value._text
244 self._selected_validator = new_value._selected_validator
245 # Update any parent ruamel links to point to our new chunk.
246 self._chunk.pointer.set(old_chunk, "_ruamelparsed", new_value._chunk.contents)
247 self._chunk.pointer.set(old_chunk, "_strictparsed", self, strictdoc=True)
248 # forked chunk made a deep copy of the original document, but we just
249 # updated pointers in the original document. So, restore our chunk to
250 # pointing at the original document.
251 self._chunk._ruamelparsed = old_chunk._ruamelparsed
252 self._chunk._strictparsed = old_chunk._strictparsed
253
254 def __delitem__(self, index):
255 strictindex = self._strictindex(index)
256 del self._value[strictindex]
257 del self._chunk.contents[self._chunk.ruamelindex(strictindex)]
258
259 def __hash__(self):
260 return hash(self._value)
261
262 def __len__(self):
263 return len(self._value)
264
265 def as_yaml(self):
266 """
267 Render the YAML node and subnodes as string.
268 """
269 dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True)
270 return dumped if sys.version_info[0] == 3 else dumped.decode("utf8")
271
272 def items(self):
273 if not isinstance(self._value, CommentedMap):
274 raise TypeError("{0} not a mapping, cannot use .items()".format(repr(self)))
275 return [(key, self._value[key]) for key, value in self._value.items()]
276
277 def keys(self):
278 if not isinstance(self._value, CommentedMap):
279 raise TypeError("{0} not a mapping, cannot use .keys()".format(repr(self)))
280 return [key for key, _ in self._value.items()]
281
282 def values(self):
283 if not isinstance(self._value, CommentedMap):
284 raise TypeError(
285 "{0} not a mapping, cannot use .values()".format(repr(self))
286 )
287 return [self._value[key] for key, value in self._value.items()]
288
289 def get(self, index, default=None):
290 if not isinstance(self._value, CommentedMap):
291 raise TypeError("{0} not a mapping, cannot use .get()".format(repr(self)))
292 return self._value[index] if index in self._value.keys() else default
293
294 def __contains__(self, item):
295 if isinstance(self._value, CommentedSeq):
296 return item in self._value
297 elif isinstance(self._value, CommentedMap):
298 return item in self.keys()
299 else:
300 return item in self._value
301
302 def __iter__(self):
303 if self.is_sequence():
304 return YAMLIterator(self)
305 elif self.is_mapping():
306 return YAMLIterator(self.keys())
307 else:
308 raise TypeError("{0} is a scalar value, cannot iterate.".format(repr(self)))
309
310 @property
311 def validator(self):
312 return self._validator
313
314 @property
315 def text(self):
316 """
317 Return string value of scalar, whatever value it was parsed as.
318 """
319 if isinstance(self._value, CommentedMap):
320 raise TypeError("{0} is a mapping, has no text value.".format(repr(self)))
321 if isinstance(self._value, CommentedSeq):
322 raise TypeError("{0} is a sequence, has no text value.".format(repr(self)))
323 return self._text
324
325 def copy(self):
326 return copy(self)
327
328 def __gt__(self, val):
329 if isinstance(self._value, CommentedMap) or isinstance(
330 self._value, CommentedSeq
331 ):
332 raise TypeError("{0} not an orderable type.".format(repr(self._value)))
333 return self._value > val
334
335 def __lt__(self, val):
336 if isinstance(self._value, CommentedMap) or isinstance(
337 self._value, CommentedSeq
338 ):
339 raise TypeError("{0} not an orderable type.".format(repr(self._value)))
340 return self._value < val
341
342 @property
343 def value(self):
344 return self._value
345
346 def is_mapping(self):
347 return isinstance(self._value, CommentedMap)
348
349 def is_sequence(self):
350 return isinstance(self._value, CommentedSeq)
351
352 def is_scalar(self):
353 return not self.is_mapping() and not self.is_sequence()
354
355 @property
356 def scalar(self):
357 if isinstance(self._value, (CommentedMap, CommentedSeq)):
358 raise TypeError("{0} has no scalar value.".format(repr(self)))
359 return self._value
360
361 def whole_document(self):
362 return self._chunk.whole_document
363
364 def __eq__(self, value):
365 return self.data == value
366
367 def __ne__(self, value):
368 return self.data != value