Debian Codegraph @

strictyaml/ruamel/constructor.py

raw
1 # coding: utf-8
2
3 from __future__ import print_function, absolute_import, division
4
5 import datetime
6 import base64
7 import binascii
8 import re
9 import sys
10 import types
11 import warnings
12
13 # fmt: off
14 from strictyaml.ruamel.error import (MarkedYAMLError, MarkedYAMLFutureWarning,
15 MantissaNoDotYAML1_1Warning)
16 from strictyaml.ruamel.nodes import * # NOQA
17 from strictyaml.ruamel.nodes import (SequenceNode, MappingNode, ScalarNode)
18 from strictyaml.ruamel.compat import (utf8, builtins_module, to_str, PY2, PY3, # NOQA
19 text_type, nprint, nprintf, version_tnf)
20 from strictyaml.ruamel.compat import ordereddict, Hashable, MutableSequence # type: ignore
21 from strictyaml.ruamel.compat import MutableMapping # type: ignore
22
23 from strictyaml.ruamel.comments import * # NOQA
24 from strictyaml.ruamel.comments import (CommentedMap, CommentedOrderedMap, CommentedSet,
25 CommentedKeySeq, CommentedSeq, TaggedScalar,
26 CommentedKeyMap)
27 from strictyaml.ruamel.scalarstring import (SingleQuotedScalarString, DoubleQuotedScalarString,
28 LiteralScalarString, FoldedScalarString,
29 PlainScalarString, ScalarString,)
30 from strictyaml.ruamel.scalarint import ScalarInt, BinaryInt, OctalInt, HexInt, HexCapsInt
31 from strictyaml.ruamel.scalarfloat import ScalarFloat
32 from strictyaml.ruamel.scalarbool import ScalarBoolean
33 from strictyaml.ruamel.timestamp import TimeStamp
34 from strictyaml.ruamel.util import RegExp
35
36 if False: # MYPY
37 from typing import Any, Dict, List, Set, Generator, Union, Optional # NOQA
38
39
40 __all__ = ['BaseConstructor', 'SafeConstructor', 'Constructor',
41 'ConstructorError', 'RoundTripConstructor']
42 # fmt: on
43
44
45 class ConstructorError(MarkedYAMLError):
46 pass
47
48
49 class DuplicateKeyFutureWarning(MarkedYAMLFutureWarning):
50 pass
51
52
53 class DuplicateKeyError(MarkedYAMLFutureWarning):
54 pass
55
56
57 class BaseConstructor(object):
58
59 yaml_constructors = {} # type: Dict[Any, Any]
60 yaml_multi_constructors = {} # type: Dict[Any, Any]
61
62 def __init__(self, preserve_quotes=None, loader=None):
63 # type: (Optional[bool], Any) -> None
64 self.loader = loader
65 if (
66 self.loader is not None
67 and getattr(self.loader, "_constructor", None) is None
68 ):
69 self.loader._constructor = self
70 self.loader = loader
71 self.yaml_base_dict_type = dict
72 self.yaml_base_list_type = list
73 self.constructed_objects = {} # type: Dict[Any, Any]
74 self.recursive_objects = {} # type: Dict[Any, Any]
75 self.state_generators = [] # type: List[Any]
76 self.deep_construct = False
77 self._preserve_quotes = preserve_quotes
78 self.allow_duplicate_keys = version_tnf((0, 15, 1), (0, 16))
79
80 @property
81 def composer(self):
82 # type: () -> Any
83 if hasattr(self.loader, "typ"):
84 return self.loader.composer
85 try:
86 return self.loader._composer
87 except AttributeError:
88 sys.stdout.write("slt {}\n".format(type(self)))
89 sys.stdout.write("slc {}\n".format(self.loader._composer))
90 sys.stdout.write("{}\n".format(dir(self)))
91 raise
92
93 @property
94 def resolver(self):
95 # type: () -> Any
96 if hasattr(self.loader, "typ"):
97 return self.loader.resolver
98 return self.loader._resolver
99
100 def check_data(self):
101 # type: () -> Any
102 # If there are more documents available?
103 return self.composer.check_node()
104
105 def get_data(self):
106 # type: () -> Any
107 # Construct and return the next document.
108 if self.composer.check_node():
109 return self.construct_document(self.composer.get_node())
110
111 def get_single_data(self):
112 # type: () -> Any
113 # Ensure that the stream contains a single document and construct it.
114 node = self.composer.get_single_node()
115 if node is not None:
116 return self.construct_document(node)
117 return None
118
119 def construct_document(self, node):
120 # type: (Any) -> Any
121 data = self.construct_object(node)
122 while bool(self.state_generators):
123 state_generators = self.state_generators
124 self.state_generators = []
125 for generator in state_generators:
126 for _dummy in generator:
127 pass
128 self.constructed_objects = {}
129 self.recursive_objects = {}
130 self.deep_construct = False
131 return data
132
133 def construct_object(self, node, deep=False):
134 # type: (Any, bool) -> Any
135 """deep is True when creating an object/mapping recursively,
136 in that case want the underlying elements available during construction
137 """
138 if node in self.constructed_objects:
139 return self.constructed_objects[node]
140 if deep:
141 old_deep = self.deep_construct
142 self.deep_construct = True
143 if node in self.recursive_objects:
144 return self.recursive_objects[node]
145 # raise ConstructorError(
146 # None, None, 'found unconstructable recursive node', node.start_mark
147 # )
148 self.recursive_objects[node] = None
149 data = self.construct_non_recursive_object(node)
150
151 self.constructed_objects[node] = data
152 del self.recursive_objects[node]
153 if deep:
154 self.deep_construct = old_deep
155 return data
156
157 def construct_non_recursive_object(self, node, tag=None):
158 # type: (Any, Optional[str]) -> Any
159 constructor = None # type: Any
160 tag_suffix = None
161 if tag is None:
162 tag = node.tag
163 if tag in self.yaml_constructors:
164 constructor = self.yaml_constructors[tag]
165 else:
166 for tag_prefix in self.yaml_multi_constructors:
167 if tag.startswith(tag_prefix):
168 tag_suffix = tag[len(tag_prefix) :]
169 constructor = self.yaml_multi_constructors[tag_prefix]
170 break
171 else:
172 if None in self.yaml_multi_constructors:
173 tag_suffix = tag
174 constructor = self.yaml_multi_constructors[None]
175 elif None in self.yaml_constructors:
176 constructor = self.yaml_constructors[None]
177 elif isinstance(node, ScalarNode):
178 constructor = self.__class__.construct_scalar
179 elif isinstance(node, SequenceNode):
180 constructor = self.__class__.construct_sequence
181 elif isinstance(node, MappingNode):
182 constructor = self.__class__.construct_mapping
183 if tag_suffix is None:
184 data = constructor(self, node)
185 else:
186 data = constructor(self, tag_suffix, node)
187 if isinstance(data, types.GeneratorType):
188 generator = data
189 data = next(generator)
190 if self.deep_construct:
191 for _dummy in generator:
192 pass
193 else:
194 self.state_generators.append(generator)
195 return data
196
197 def construct_scalar(self, node):
198 # type: (Any) -> Any
199 if not isinstance(node, ScalarNode):
200 raise ConstructorError(
201 None,
202 None,
203 "expected a scalar node, but found %s" % node.id,
204 node.start_mark,
205 )
206 return node.value
207
208 def construct_sequence(self, node, deep=False):
209 # type: (Any, bool) -> Any
210 """deep is True when creating an object/mapping recursively,
211 in that case want the underlying elements available during construction
212 """
213 if not isinstance(node, SequenceNode):
214 raise ConstructorError(
215 None,
216 None,
217 "expected a sequence node, but found %s" % node.id,
218 node.start_mark,
219 )
220 return [self.construct_object(child, deep=deep) for child in node.value]
221
222 def construct_mapping(self, node, deep=False):
223 # type: (Any, bool) -> Any
224 """deep is True when creating an object/mapping recursively,
225 in that case want the underlying elements available during construction
226 """
227 if not isinstance(node, MappingNode):
228 raise ConstructorError(
229 None,
230 None,
231 "expected a mapping node, but found %s" % node.id,
232 node.start_mark,
233 )
234 total_mapping = self.yaml_base_dict_type()
235 if getattr(node, "merge", None) is not None:
236 todo = [(node.merge, False), (node.value, False)]
237 else:
238 todo = [(node.value, True)]
239 for values, check in todo:
240 mapping = self.yaml_base_dict_type() # type: Dict[Any, Any]
241 for key_node, value_node in values:
242 # keys can be list -> deep
243 key = self.construct_object(key_node, deep=True)
244 # lists are not hashable, but tuples are
245 if not isinstance(key, Hashable):
246 if isinstance(key, list):
247 key = tuple(key)
248 if PY2:
249 try:
250 hash(key)
251 except TypeError as exc:
252 raise ConstructorError(
253 "while constructing a mapping",
254 node.start_mark,
255 "found unacceptable key (%s)" % exc,
256 key_node.start_mark,
257 )
258 else:
259 if not isinstance(key, Hashable):
260 raise ConstructorError(
261 "while constructing a mapping",
262 node.start_mark,
263 "found unhashable key",
264 key_node.start_mark,
265 )
266
267 value = self.construct_object(value_node, deep=deep)
268 if check:
269 if self.check_mapping_key(node, key_node, mapping, key, value):
270 mapping[key] = value
271 else:
272 mapping[key] = value
273 total_mapping.update(mapping)
274 return total_mapping
275
276 def check_mapping_key(self, node, key_node, mapping, key, value):
277 # type: (Any, Any, Any, Any, Any) -> bool
278 """return True if key is unique"""
279 if key in mapping:
280 if not self.allow_duplicate_keys:
281 mk = mapping.get(key)
282 if PY2:
283 if isinstance(key, unicode):
284 key = key.encode("utf-8")
285 if isinstance(value, unicode):
286 value = value.encode("utf-8")
287 if isinstance(mk, unicode):
288 mk = mk.encode("utf-8")
289 args = [
290 "while constructing a mapping",
291 node.start_mark,
292 'found duplicate key "{}" with value "{}" '
293 '(original value: "{}")'.format(key, value, mk),
294 key_node.start_mark,
295 """
296 To suppress this check see:
297 http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
298 """,
299 """\
300 Duplicate keys will become an error in future releases, and are errors
301 by default when using the new API.
302 """,
303 ]
304 if self.allow_duplicate_keys is None:
305 warnings.warn(DuplicateKeyFutureWarning(*args))
306 else:
307 raise DuplicateKeyError(*args)
308 return False
309 return True
310
311 def check_set_key(self, node, key_node, setting, key):
312 # type: (Any, Any, Any, Any, Any) -> None
313 if key in setting:
314 if not self.allow_duplicate_keys:
315 if PY2:
316 if isinstance(key, unicode):
317 key = key.encode("utf-8")
318 args = [
319 "while constructing a set",
320 node.start_mark,
321 'found duplicate key "{}"'.format(key),
322 key_node.start_mark,
323 """
324 To suppress this check see:
325 http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
326 """,
327 """\
328 Duplicate keys will become an error in future releases, and are errors
329 by default when using the new API.
330 """,
331 ]
332 if self.allow_duplicate_keys is None:
333 warnings.warn(DuplicateKeyFutureWarning(*args))
334 else:
335 raise DuplicateKeyError(*args)
336
337 def construct_pairs(self, node, deep=False):
338 # type: (Any, bool) -> Any
339 if not isinstance(node, MappingNode):
340 raise ConstructorError(
341 None,
342 None,
343 "expected a mapping node, but found %s" % node.id,
344 node.start_mark,
345 )
346 pairs = []
347 for key_node, value_node in node.value:
348 key = self.construct_object(key_node, deep=deep)
349 value = self.construct_object(value_node, deep=deep)
350 pairs.append((key, value))
351 return pairs
352
353 @classmethod
354 def add_constructor(cls, tag, constructor):
355 # type: (Any, Any) -> None
356 if "yaml_constructors" not in cls.__dict__:
357 cls.yaml_constructors = cls.yaml_constructors.copy()
358 cls.yaml_constructors[tag] = constructor
359
360 @classmethod
361 def add_multi_constructor(cls, tag_prefix, multi_constructor):
362 # type: (Any, Any) -> None
363 if "yaml_multi_constructors" not in cls.__dict__:
364 cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy()
365 cls.yaml_multi_constructors[tag_prefix] = multi_constructor
366
367
368 class SafeConstructor(BaseConstructor):
369 def construct_scalar(self, node):
370 # type: (Any) -> Any
371 if isinstance(node, MappingNode):
372 for key_node, value_node in node.value:
373 if key_node.tag == u"tag:yaml.org,2002:value":
374 return self.construct_scalar(value_node)
375 return BaseConstructor.construct_scalar(self, node)
376
377 def flatten_mapping(self, node):
378 # type: (Any) -> Any
379 """
380 This implements the merge key feature http://yaml.org/type/merge.html
381 by inserting keys from the merge dict/list of dicts if not yet
382 available in this node
383 """
384 merge = [] # type: List[Any]
385 index = 0
386 while index < len(node.value):
387 key_node, value_node = node.value[index]
388 if key_node.tag == u"tag:yaml.org,2002:merge":
389 if merge: # double << key
390 if self.allow_duplicate_keys:
391 del node.value[index]
392 index += 1
393 continue
394 args = [
395 "while constructing a mapping",
396 node.start_mark,
397 'found duplicate key "{}"'.format(key_node.value),
398 key_node.start_mark,
399 """
400 To suppress this check see:
401 http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
402 """,
403 """\
404 Duplicate keys will become an error in future releases, and are errors
405 by default when using the new API.
406 """,
407 ]
408 if self.allow_duplicate_keys is None:
409 warnings.warn(DuplicateKeyFutureWarning(*args))
410 else:
411 raise DuplicateKeyError(*args)
412 del node.value[index]
413 if isinstance(value_node, MappingNode):
414 self.flatten_mapping(value_node)
415 merge.extend(value_node.value)
416 elif isinstance(value_node, SequenceNode):
417 submerge = []
418 for subnode in value_node.value:
419 if not isinstance(subnode, MappingNode):
420 raise ConstructorError(
421 "while constructing a mapping",
422 node.start_mark,
423 "expected a mapping for merging, but found %s"
424 % subnode.id,
425 subnode.start_mark,
426 )
427 self.flatten_mapping(subnode)
428 submerge.append(subnode.value)
429 submerge.reverse()
430 for value in submerge:
431 merge.extend(value)
432 else:
433 raise ConstructorError(
434 "while constructing a mapping",
435 node.start_mark,
436 "expected a mapping or list of mappings for merging, "
437 "but found %s" % value_node.id,
438 value_node.start_mark,
439 )
440 elif key_node.tag == u"tag:yaml.org,2002:value":
441 key_node.tag = u"tag:yaml.org,2002:str"
442 index += 1
443 else:
444 index += 1
445 if bool(merge):
446 node.merge = (
447 merge # separate merge keys to be able to update without duplicate
448 )
449 node.value = merge + node.value
450
451 def construct_mapping(self, node, deep=False):
452 # type: (Any, bool) -> Any
453 """deep is True when creating an object/mapping recursively,
454 in that case want the underlying elements available during construction
455 """
456 if isinstance(node, MappingNode):
457 self.flatten_mapping(node)
458 return BaseConstructor.construct_mapping(self, node, deep=deep)
459
460 def construct_yaml_null(self, node):
461 # type: (Any) -> Any
462 self.construct_scalar(node)
463 return None
464
465 # YAML 1.2 spec doesn't mention yes/no etc any more, 1.1 does
466 bool_values = {
467 u"yes": True,
468 u"no": False,
469 u"y": True,
470 u"n": False,
471 u"true": True,
472 u"false": False,
473 u"on": True,
474 u"off": False,
475 }
476
477 def construct_yaml_bool(self, node):
478 # type: (Any) -> bool
479 value = self.construct_scalar(node)
480 return self.bool_values[value.lower()]
481
482 def construct_yaml_int(self, node):
483 # type: (Any) -> int
484 value_s = to_str(self.construct_scalar(node))
485 value_s = value_s.replace("_", "")
486 sign = +1
487 if value_s[0] == "-":
488 sign = -1
489 if value_s[0] in "+-":
490 value_s = value_s[1:]
491 if value_s == "0":
492 return 0
493 elif value_s.startswith("0b"):
494 return sign * int(value_s[2:], 2)
495 elif value_s.startswith("0x"):
496 return sign * int(value_s[2:], 16)
497 elif value_s.startswith("0o"):
498 return sign * int(value_s[2:], 8)
499 elif self.resolver.processing_version == (1, 1) and value_s[0] == "0":
500 return sign * int(value_s, 8)
501 elif self.resolver.processing_version == (1, 1) and ":" in value_s:
502 digits = [int(part) for part in value_s.split(":")]
503 digits.reverse()
504 base = 1
505 value = 0
506 for digit in digits:
507 value += digit * base
508 base *= 60
509 return sign * value
510 else:
511 return sign * int(value_s)
512
513 inf_value = 1e300
514 while inf_value != inf_value * inf_value:
515 inf_value *= inf_value
516 nan_value = -inf_value / inf_value # Trying to make a quiet NaN (like C99).
517
518 def construct_yaml_float(self, node):
519 # type: (Any) -> float
520 value_so = to_str(self.construct_scalar(node))
521 value_s = value_so.replace("_", "").lower()
522 sign = +1
523 if value_s[0] == "-":
524 sign = -1
525 if value_s[0] in "+-":
526 value_s = value_s[1:]
527 if value_s == ".inf":
528 return sign * self.inf_value
529 elif value_s == ".nan":
530 return self.nan_value
531 elif self.resolver.processing_version != (1, 2) and ":" in value_s:
532 digits = [float(part) for part in value_s.split(":")]
533 digits.reverse()
534 base = 1
535 value = 0.0
536 for digit in digits:
537 value += digit * base
538 base *= 60
539 return sign * value
540 else:
541 if self.resolver.processing_version != (1, 2) and "e" in value_s:
542 # value_s is lower case independent of input
543 mantissa, exponent = value_s.split("e")
544 if "." not in mantissa:
545 warnings.warn(MantissaNoDotYAML1_1Warning(node, value_so))
546 return sign * float(value_s)
547
548 if PY3:
549
550 def construct_yaml_binary(self, node):
551 # type: (Any) -> Any
552 try:
553 value = self.construct_scalar(node).encode("ascii")
554 except UnicodeEncodeError as exc:
555 raise ConstructorError(
556 None,
557 None,
558 "failed to convert base64 data into ascii: %s" % exc,
559 node.start_mark,
560 )
561 try:
562 if hasattr(base64, "decodebytes"):
563 return base64.decodebytes(value)
564 else:
565 return base64.decodestring(value)
566 except binascii.Error as exc:
567 raise ConstructorError(
568 None,
569 None,
570 "failed to decode base64 data: %s" % exc,
571 node.start_mark,
572 )
573
574 else:
575
576 def construct_yaml_binary(self, node):
577 # type: (Any) -> Any
578 value = self.construct_scalar(node)
579 try:
580 return to_str(value).decode("base64")
581 except (binascii.Error, UnicodeEncodeError) as exc:
582 raise ConstructorError(
583 None,
584 None,
585 "failed to decode base64 data: %s" % exc,
586 node.start_mark,
587 )
588
589 timestamp_regexp = RegExp(
590 u"""^(?P<year>[0-9][0-9][0-9][0-9])
591 -(?P<month>[0-9][0-9]?)
592 -(?P<day>[0-9][0-9]?)
593 (?:((?P<t>[Tt])|[ \\t]+) # explictly not retaining extra spaces
594 (?P<hour>[0-9][0-9]?)
595 :(?P<minute>[0-9][0-9])
596 :(?P<second>[0-9][0-9])
597 (?:\\.(?P<fraction>[0-9]*))?
598 (?:[ \\t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
599 (?::(?P<tz_minute>[0-9][0-9]))?))?)?$""",
600 re.X,
601 )
602
603 def construct_yaml_timestamp(self, node, values=None):
604 # type: (Any, Any) -> Any
605 if values is None:
606 try:
607 match = self.timestamp_regexp.match(node.value)
608 except TypeError:
609 match = None
610 if match is None:
611 raise ConstructorError(
612 None,
613 None,
614 'failed to construct timestamp from "{}"'.format(node.value),
615 node.start_mark,
616 )
617 values = match.groupdict()
618 year = int(values["year"])
619 month = int(values["month"])
620 day = int(values["day"])
621 if not values["hour"]:
622 return datetime.date(year, month, day)
623 hour = int(values["hour"])
624 minute = int(values["minute"])
625 second = int(values["second"])
626 fraction = 0
627 if values["fraction"]:
628 fraction_s = values["fraction"][:6]
629 while len(fraction_s) < 6:
630 fraction_s += "0"
631 fraction = int(fraction_s)
632 if len(values["fraction"]) > 6 and int(values["fraction"][6]) > 4:
633 fraction += 1
634 delta = None
635 if values["tz_sign"]:
636 tz_hour = int(values["tz_hour"])
637 minutes = values["tz_minute"]
638 tz_minute = int(minutes) if minutes else 0
639 delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
640 if values["tz_sign"] == "-":
641 delta = -delta
642 # should do something else instead (or hook this up to the preceding if statement
643 # in reverse
644 # if delta is None:
645 # return datetime.datetime(year, month, day, hour, minute, second, fraction)
646 # return datetime.datetime(year, month, day, hour, minute, second, fraction,
647 # datetime.timezone.utc)
648 # the above is not good enough though, should provide tzinfo. In Python3 that is easily
649 # doable drop that kind of support for Python2 as it has not native tzinfo
650 data = datetime.datetime(year, month, day, hour, minute, second, fraction)
651 if delta:
652 data -= delta
653 return data
654
655 def construct_yaml_omap(self, node):
656 # type: (Any) -> Any
657 # Note: we do now check for duplicate keys
658 omap = ordereddict()
659 yield omap
660 if not isinstance(node, SequenceNode):
661 raise ConstructorError(
662 "while constructing an ordered map",
663 node.start_mark,
664 "expected a sequence, but found %s" % node.id,
665 node.start_mark,
666 )
667 for subnode in node.value:
668 if not isinstance(subnode, MappingNode):
669 raise ConstructorError(
670 "while constructing an ordered map",
671 node.start_mark,
672 "expected a mapping of length 1, but found %s" % subnode.id,
673 subnode.start_mark,
674 )
675 if len(subnode.value) != 1:
676 raise ConstructorError(
677 "while constructing an ordered map",
678 node.start_mark,
679 "expected a single mapping item, but found %d items"
680 % len(subnode.value),
681 subnode.start_mark,
682 )
683 key_node, value_node = subnode.value[0]
684 key = self.construct_object(key_node)
685 assert key not in omap
686 value = self.construct_object(value_node)
687 omap[key] = value
688
689 def construct_yaml_pairs(self, node):
690 # type: (Any) -> Any
691 # Note: the same code as `construct_yaml_omap`.
692 pairs = [] # type: List[Any]
693 yield pairs
694 if not isinstance(node, SequenceNode):
695 raise ConstructorError(
696 "while constructing pairs",
697 node.start_mark,
698 "expected a sequence, but found %s" % node.id,
699 node.start_mark,
700 )
701 for subnode in node.value:
702 if not isinstance(subnode, MappingNode):
703 raise ConstructorError(
704 "while constructing pairs",
705 node.start_mark,
706 "expected a mapping of length 1, but found %s" % subnode.id,
707 subnode.start_mark,
708 )
709 if len(subnode.value) != 1:
710 raise ConstructorError(
711 "while constructing pairs",
712 node.start_mark,
713 "expected a single mapping item, but found %d items"
714 % len(subnode.value),
715 subnode.start_mark,
716 )
717 key_node, value_node = subnode.value[0]
718 key = self.construct_object(key_node)
719 value = self.construct_object(value_node)
720 pairs.append((key, value))
721
722 def construct_yaml_set(self, node):
723 # type: (Any) -> Any
724 data = set() # type: Set[Any]
725 yield data
726 value = self.construct_mapping(node)
727 data.update(value)
728
729 def construct_yaml_str(self, node):
730 # type: (Any) -> Any
731 value = self.construct_scalar(node)
732 if PY3:
733 return value
734 try:
735 return value.encode("ascii")
736 except UnicodeEncodeError:
737 return value
738
739 def construct_yaml_seq(self, node):
740 # type: (Any) -> Any
741 data = self.yaml_base_list_type() # type: List[Any]
742 yield data
743 data.extend(self.construct_sequence(node))
744
745 def construct_yaml_map(self, node):
746 # type: (Any) -> Any
747 data = self.yaml_base_dict_type() # type: Dict[Any, Any]
748 yield data
749 value = self.construct_mapping(node)
750 data.update(value)
751
752 def construct_yaml_object(self, node, cls):
753 # type: (Any, Any) -> Any
754 data = cls.__new__(cls)
755 yield data
756 if hasattr(data, "__setstate__"):
757 state = self.construct_mapping(node, deep=True)
758 data.__setstate__(state)
759 else:
760 state = self.construct_mapping(node)
761 data.__dict__.update(state)
762
763 def construct_undefined(self, node):
764 # type: (Any) -> None
765 raise ConstructorError(
766 None,
767 None,
768 "could not determine a constructor for the tag %r" % utf8(node.tag),
769 node.start_mark,
770 )
771
772
773 SafeConstructor.add_constructor(
774 u"tag:yaml.org,2002:null", SafeConstructor.construct_yaml_null
775 )
776
777 SafeConstructor.add_constructor(
778 u"tag:yaml.org,2002:bool", SafeConstructor.construct_yaml_bool
779 )
780
781 SafeConstructor.add_constructor(
782 u"tag:yaml.org,2002:int", SafeConstructor.construct_yaml_int
783 )
784
785 SafeConstructor.add_constructor(
786 u"tag:yaml.org,2002:float", SafeConstructor.construct_yaml_float
787 )
788
789 SafeConstructor.add_constructor(
790 u"tag:yaml.org,2002:binary", SafeConstructor.construct_yaml_binary
791 )
792
793 SafeConstructor.add_constructor(
794 u"tag:yaml.org,2002:timestamp", SafeConstructor.construct_yaml_timestamp
795 )
796
797 SafeConstructor.add_constructor(
798 u"tag:yaml.org,2002:omap", SafeConstructor.construct_yaml_omap
799 )
800
801 SafeConstructor.add_constructor(
802 u"tag:yaml.org,2002:pairs", SafeConstructor.construct_yaml_pairs
803 )
804
805 SafeConstructor.add_constructor(
806 u"tag:yaml.org,2002:set", SafeConstructor.construct_yaml_set
807 )
808
809 SafeConstructor.add_constructor(
810 u"tag:yaml.org,2002:str", SafeConstructor.construct_yaml_str
811 )
812
813 SafeConstructor.add_constructor(
814 u"tag:yaml.org,2002:seq", SafeConstructor.construct_yaml_seq
815 )
816
817 SafeConstructor.add_constructor(
818 u"tag:yaml.org,2002:map", SafeConstructor.construct_yaml_map
819 )
820
821 SafeConstructor.add_constructor(None, SafeConstructor.construct_undefined)
822
823 if PY2:
824
825 class classobj:
826 pass
827
828
829 class Constructor(SafeConstructor):
830 def construct_python_str(self, node):
831 # type: (Any) -> Any
832 return utf8(self.construct_scalar(node))
833
834 def construct_python_unicode(self, node):
835 # type: (Any) -> Any
836 return self.construct_scalar(node)
837
838 if PY3:
839
840 def construct_python_bytes(self, node):
841 # type: (Any) -> Any
842 try:
843 value = self.construct_scalar(node).encode("ascii")
844 except UnicodeEncodeError as exc:
845 raise ConstructorError(
846 None,
847 None,
848 "failed to convert base64 data into ascii: %s" % exc,
849 node.start_mark,
850 )
851 try:
852 if hasattr(base64, "decodebytes"):
853 return base64.decodebytes(value)
854 else:
855 return base64.decodestring(value)
856 except binascii.Error as exc:
857 raise ConstructorError(
858 None,
859 None,
860 "failed to decode base64 data: %s" % exc,
861 node.start_mark,
862 )
863
864 def construct_python_long(self, node):
865 # type: (Any) -> int
866 val = self.construct_yaml_int(node)
867 if PY3:
868 return val
869 return int(val)
870
871 def construct_python_complex(self, node):
872 # type: (Any) -> Any
873 return complex(self.construct_scalar(node))
874
875 def construct_python_tuple(self, node):
876 # type: (Any) -> Any
877 return tuple(self.construct_sequence(node))
878
879 def find_python_module(self, name, mark):
880 # type: (Any, Any) -> Any
881 if not name:
882 raise ConstructorError(
883 "while constructing a Python module",
884 mark,
885 "expected non-empty name appended to the tag",
886 mark,
887 )
888 try:
889 __import__(name)
890 except ImportError as exc:
891 raise ConstructorError(
892 "while constructing a Python module",
893 mark,
894 "cannot find module %r (%s)" % (utf8(name), exc),
895 mark,
896 )
897 return sys.modules[name]
898
899 def find_python_name(self, name, mark):
900 # type: (Any, Any) -> Any
901 if not name:
902 raise ConstructorError(
903 "while constructing a Python object",
904 mark,
905 "expected non-empty name appended to the tag",
906 mark,
907 )
908 if u"." in name:
909 lname = name.split(".")
910 lmodule_name = lname
911 lobject_name = [] # type: List[Any]
912 while len(lmodule_name) > 1:
913 lobject_name.insert(0, lmodule_name.pop())
914 module_name = ".".join(lmodule_name)
915 try:
916 __import__(module_name)
917 # object_name = '.'.join(object_name)
918 break
919 except ImportError:
920 continue
921 else:
922 module_name = builtins_module
923 lobject_name = [name]
924 try:
925 __import__(module_name)
926 except ImportError as exc:
927 raise ConstructorError(
928 "while constructing a Python object",
929 mark,
930 "cannot find module %r (%s)" % (utf8(module_name), exc),
931 mark,
932 )
933 module = sys.modules[module_name]
934 object_name = ".".join(lobject_name)
935 obj = module
936 while lobject_name:
937 if not hasattr(obj, lobject_name[0]):
938
939 raise ConstructorError(
940 "while constructing a Python object",
941 mark,
942 "cannot find %r in the module %r"
943 % (utf8(object_name), module.__name__),
944 mark,
945 )
946 obj = getattr(obj, lobject_name.pop(0))
947 return obj
948
949 def construct_python_name(self, suffix, node):
950 # type: (Any, Any) -> Any
951 value = self.construct_scalar(node)
952 if value:
953 raise ConstructorError(
954 "while constructing a Python name",
955 node.start_mark,
956 "expected the empty value, but found %r" % utf8(value),
957 node.start_mark,
958 )
959 return self.find_python_name(suffix, node.start_mark)
960
961 def construct_python_module(self, suffix, node):
962 # type: (Any, Any) -> Any
963 value = self.construct_scalar(node)
964 if value:
965 raise ConstructorError(
966 "while constructing a Python module",
967 node.start_mark,
968 "expected the empty value, but found %r" % utf8(value),
969 node.start_mark,
970 )
971 return self.find_python_module(suffix, node.start_mark)
972
973 def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False):
974 # type: (Any, Any, Any, Any, bool) -> Any
975 if not args:
976 args = []
977 if not kwds:
978 kwds = {}
979 cls = self.find_python_name(suffix, node.start_mark)
980 if PY3:
981 if newobj and isinstance(cls, type):
982 return cls.__new__(cls, *args, **kwds)
983 else:
984 return cls(*args, **kwds)
985 else:
986 if newobj and isinstance(cls, type(classobj)) and not args and not kwds:
987 instance = classobj()
988 instance.__class__ = cls
989 return instance
990 elif newobj and isinstance(cls, type):
991 return cls.__new__(cls, *args, **kwds)
992 else:
993 return cls(*args, **kwds)
994
995 def set_python_instance_state(self, instance, state):
996 # type: (Any, Any) -> None
997 if hasattr(instance, "__setstate__"):
998 instance.__setstate__(state)
999 else:
1000 slotstate = {} # type: Dict[Any, Any]
1001 if isinstance(state, tuple) and len(state) == 2:
1002 state, slotstate = state
1003 if hasattr(instance, "__dict__"):
1004 instance.__dict__.update(state)
1005 elif state:
1006 slotstate.update(state)
1007 for key, value in slotstate.items():
1008 setattr(instance, key, value)
1009
1010 def construct_python_object(self, suffix, node):
1011 # type: (Any, Any) -> Any
1012 # Format:
1013 # !!python/object:module.name { ... state ... }
1014 instance = self.make_python_instance(suffix, node, newobj=True)
1015 self.recursive_objects[node] = instance
1016 yield instance
1017 deep = hasattr(instance, "__setstate__")
1018 state = self.construct_mapping(node, deep=deep)
1019 self.set_python_instance_state(instance, state)
1020
1021 def construct_python_object_apply(self, suffix, node, newobj=False):
1022 # type: (Any, Any, bool) -> Any
1023 # Format:
1024 # !!python/object/apply # (or !!python/object/new)
1025 # args: [ ... arguments ... ]
1026 # kwds: { ... keywords ... }
1027 # state: ... state ...
1028 # listitems: [ ... listitems ... ]
1029 # dictitems: { ... dictitems ... }
1030 # or short format:
1031 # !!python/object/apply [ ... arguments ... ]
1032 # The difference between !!python/object/apply and !!python/object/new
1033 # is how an object is created, check make_python_instance for details.
1034 if isinstance(node, SequenceNode):
1035 args = self.construct_sequence(node, deep=True)
1036 kwds = {} # type: Dict[Any, Any]
1037 state = {} # type: Dict[Any, Any]
1038 listitems = [] # type: List[Any]
1039 dictitems = {} # type: Dict[Any, Any]
1040 else:
1041 value = self.construct_mapping(node, deep=True)
1042 args = value.get("args", [])
1043 kwds = value.get("kwds", {})
1044 state = value.get("state", {})
1045 listitems = value.get("listitems", [])
1046 dictitems = value.get("dictitems", {})
1047 instance = self.make_python_instance(suffix, node, args, kwds, newobj)
1048 if bool(state):
1049 self.set_python_instance_state(instance, state)
1050 if bool(listitems):
1051 instance.extend(listitems)
1052 if bool(dictitems):
1053 for key in dictitems:
1054 instance[key] = dictitems[key]
1055 return instance
1056
1057 def construct_python_object_new(self, suffix, node):
1058 # type: (Any, Any) -> Any
1059 return self.construct_python_object_apply(suffix, node, newobj=True)
1060
1061
1062 Constructor.add_constructor(
1063 u"tag:yaml.org,2002:python/none", Constructor.construct_yaml_null
1064 )
1065
1066 Constructor.add_constructor(
1067 u"tag:yaml.org,2002:python/bool", Constructor.construct_yaml_bool
1068 )
1069
1070 Constructor.add_constructor(
1071 u"tag:yaml.org,2002:python/str", Constructor.construct_python_str
1072 )
1073
1074 Constructor.add_constructor(
1075 u"tag:yaml.org,2002:python/unicode", Constructor.construct_python_unicode
1076 )
1077
1078 if PY3:
1079 Constructor.add_constructor(
1080 u"tag:yaml.org,2002:python/bytes", Constructor.construct_python_bytes
1081 )
1082
1083 Constructor.add_constructor(
1084 u"tag:yaml.org,2002:python/int", Constructor.construct_yaml_int
1085 )
1086
1087 Constructor.add_constructor(
1088 u"tag:yaml.org,2002:python/long", Constructor.construct_python_long
1089 )
1090
1091 Constructor.add_constructor(
1092 u"tag:yaml.org,2002:python/float", Constructor.construct_yaml_float
1093 )
1094
1095 Constructor.add_constructor(
1096 u"tag:yaml.org,2002:python/complex", Constructor.construct_python_complex
1097 )
1098
1099 Constructor.add_constructor(
1100 u"tag:yaml.org,2002:python/list", Constructor.construct_yaml_seq
1101 )
1102
1103 Constructor.add_constructor(
1104 u"tag:yaml.org,2002:python/tuple", Constructor.construct_python_tuple
1105 )
1106
1107 Constructor.add_constructor(
1108 u"tag:yaml.org,2002:python/dict", Constructor.construct_yaml_map
1109 )
1110
1111 Constructor.add_multi_constructor(
1112 u"tag:yaml.org,2002:python/name:", Constructor.construct_python_name
1113 )
1114
1115 Constructor.add_multi_constructor(
1116 u"tag:yaml.org,2002:python/module:", Constructor.construct_python_module
1117 )
1118
1119 Constructor.add_multi_constructor(
1120 u"tag:yaml.org,2002:python/object:", Constructor.construct_python_object
1121 )
1122
1123 Constructor.add_multi_constructor(
1124 u"tag:yaml.org,2002:python/object/apply:", Constructor.construct_python_object_apply
1125 )
1126
1127 Constructor.add_multi_constructor(
1128 u"tag:yaml.org,2002:python/object/new:", Constructor.construct_python_object_new
1129 )
1130
1131
1132 class RoundTripConstructor(SafeConstructor):
1133 """need to store the comments on the node itself,
1134 as well as on the items
1135 """
1136
1137 def construct_scalar(self, node):
1138 # type: (Any) -> Any
1139 if not isinstance(node, ScalarNode):
1140 raise ConstructorError(
1141 None,
1142 None,
1143 "expected a scalar node, but found %s" % node.id,
1144 node.start_mark,
1145 )
1146
1147 if node.style == "|" and isinstance(node.value, text_type):
1148 lss = LiteralScalarString(node.value, anchor=node.anchor)
1149 if node.comment and node.comment[1]:
1150 lss.comment = node.comment[1][0] # type: ignore
1151 return lss
1152 if node.style == ">" and isinstance(node.value, text_type):
1153 fold_positions = [] # type: List[int]
1154 idx = -1
1155 while True:
1156 idx = node.value.find("\a", idx + 1)
1157 if idx < 0:
1158 break
1159 fold_positions.append(idx - len(fold_positions))
1160 fss = FoldedScalarString(node.value.replace("\a", ""), anchor=node.anchor)
1161 if node.comment and node.comment[1]:
1162 fss.comment = node.comment[1][0] # type: ignore
1163 if fold_positions:
1164 fss.fold_pos = fold_positions # type: ignore
1165 return fss
1166 elif bool(self._preserve_quotes) and isinstance(node.value, text_type):
1167 if node.style == "'":
1168 return SingleQuotedScalarString(node.value, anchor=node.anchor)
1169 if node.style == '"':
1170 return DoubleQuotedScalarString(node.value, anchor=node.anchor)
1171 if node.anchor:
1172 return PlainScalarString(node.value, anchor=node.anchor)
1173 return node.value
1174
1175 def construct_yaml_int(self, node):
1176 # type: (Any) -> Any
1177 width = None # type: Any
1178 value_su = to_str(self.construct_scalar(node))
1179 try:
1180 sx = value_su.rstrip("_")
1181 underscore = [len(sx) - sx.rindex("_") - 1, False, False] # type: Any
1182 except ValueError:
1183 underscore = None
1184 except IndexError:
1185 underscore = None
1186 value_s = value_su.replace("_", "")
1187 sign = +1
1188 if value_s[0] == "-":
1189 sign = -1
1190 if value_s[0] in "+-":
1191 value_s = value_s[1:]
1192 if value_s == "0":
1193 return 0
1194 elif value_s.startswith("0b"):
1195 if self.resolver.processing_version > (1, 1) and value_s[2] == "0":
1196 width = len(value_s[2:])
1197 if underscore is not None:
1198 underscore[1] = value_su[2] == "_"
1199 underscore[2] = len(value_su[2:]) > 1 and value_su[-1] == "_"
1200 return BinaryInt(
1201 sign * int(value_s[2:], 2),
1202 width=width,
1203 underscore=underscore,
1204 anchor=node.anchor,
1205 )
1206 elif value_s.startswith("0x"):
1207 # default to lower-case if no a-fA-F in string
1208 if self.resolver.processing_version > (1, 1) and value_s[2] == "0":
1209 width = len(value_s[2:])
1210 hex_fun = HexInt # type: Any
1211 for ch in value_s[2:]:
1212 if ch in "ABCDEF": # first non-digit is capital
1213 hex_fun = HexCapsInt
1214 break
1215 if ch in "abcdef":
1216 break
1217 if underscore is not None:
1218 underscore[1] = value_su[2] == "_"
1219 underscore[2] = len(value_su[2:]) > 1 and value_su[-1] == "_"
1220 return hex_fun(
1221 sign * int(value_s[2:], 16),
1222 width=width,
1223 underscore=underscore,
1224 anchor=node.anchor,
1225 )
1226 elif value_s.startswith("0o"):
1227 if self.resolver.processing_version > (1, 1) and value_s[2] == "0":
1228 width = len(value_s[2:])
1229 if underscore is not None:
1230 underscore[1] = value_su[2] == "_"
1231 underscore[2] = len(value_su[2:]) > 1 and value_su[-1] == "_"
1232 return OctalInt(
1233 sign * int(value_s[2:], 8),
1234 width=width,
1235 underscore=underscore,
1236 anchor=node.anchor,
1237 )
1238 elif self.resolver.processing_version != (1, 2) and value_s[0] == "0":
1239 return sign * int(value_s, 8)
1240 elif self.resolver.processing_version != (1, 2) and ":" in value_s:
1241 digits = [int(part) for part in value_s.split(":")]
1242 digits.reverse()
1243 base = 1
1244 value = 0
1245 for digit in digits:
1246 value += digit * base
1247 base *= 60
1248 return sign * value
1249 elif self.resolver.processing_version > (1, 1) and value_s[0] == "0":
1250 # not an octal, an integer with leading zero(s)
1251 if underscore is not None:
1252 # cannot have a leading underscore
1253 underscore[2] = len(value_su) > 1 and value_su[-1] == "_"
1254 return ScalarInt(
1255 sign * int(value_s), width=len(value_s), underscore=underscore
1256 )
1257 elif underscore:
1258 # cannot have a leading underscore
1259 underscore[2] = len(value_su) > 1 and value_su[-1] == "_"
1260 return ScalarInt(
1261 sign * int(value_s),
1262 width=None,
1263 underscore=underscore,
1264 anchor=node.anchor,
1265 )
1266 elif node.anchor:
1267 return ScalarInt(sign * int(value_s), width=None, anchor=node.anchor)
1268 else:
1269 return sign * int(value_s)
1270
1271 def construct_yaml_float(self, node):
1272 # type: (Any) -> Any
1273 def leading_zeros(v):
1274 # type: (Any) -> int
1275 lead0 = 0
1276 idx = 0
1277 while idx < len(v) and v[idx] in "0.":
1278 if v[idx] == "0":
1279 lead0 += 1
1280 idx += 1
1281 return lead0
1282
1283 # underscore = None
1284 m_sign = False # type: Any
1285 value_so = to_str(self.construct_scalar(node))
1286 value_s = value_so.replace("_", "").lower()
1287 sign = +1
1288 if value_s[0] == "-":
1289 sign = -1
1290 if value_s[0] in "+-":
1291 m_sign = value_s[0]
1292 value_s = value_s[1:]
1293 if value_s == ".inf":
1294 return sign * self.inf_value
1295 if value_s == ".nan":
1296 return self.nan_value
1297 if self.resolver.processing_version != (1, 2) and ":" in value_s:
1298 digits = [float(part) for part in value_s.split(":")]
1299 digits.reverse()
1300 base = 1
1301 value = 0.0
1302 for digit in digits:
1303 value += digit * base
1304 base *= 60
1305 return sign * value
1306 if "e" in value_s:
1307 try:
1308 mantissa, exponent = value_so.split("e")
1309 exp = "e"
1310 except ValueError:
1311 mantissa, exponent = value_so.split("E")
1312 exp = "E"
1313 if self.resolver.processing_version != (1, 2):
1314 # value_s is lower case independent of input
1315 if "." not in mantissa:
1316 warnings.warn(MantissaNoDotYAML1_1Warning(node, value_so))
1317 lead0 = leading_zeros(mantissa)
1318 width = len(mantissa)
1319 prec = mantissa.find(".")
1320 if m_sign:
1321 width -= 1
1322 e_width = len(exponent)
1323 e_sign = exponent[0] in "+-"
1324 # nprint('sf', width, prec, m_sign, exp, e_width, e_sign)
1325 return ScalarFloat(
1326 sign * float(value_s),
1327 width=width,
1328 prec=prec,
1329 m_sign=m_sign,
1330 m_lead0=lead0,
1331 exp=exp,
1332 e_width=e_width,
1333 e_sign=e_sign,
1334 anchor=node.anchor,
1335 )
1336 width = len(value_so)
1337 prec = value_so.index(
1338 "."
1339 ) # you can use index, this would not be float without dot
1340 lead0 = leading_zeros(value_so)
1341 return ScalarFloat(
1342 sign * float(value_s),
1343 width=width,
1344 prec=prec,
1345 m_sign=m_sign,
1346 m_lead0=lead0,
1347 anchor=node.anchor,
1348 )
1349
1350 def construct_yaml_str(self, node):
1351 # type: (Any) -> Any
1352 value = self.construct_scalar(node)
1353 if isinstance(value, ScalarString):
1354 return value
1355 if PY3:
1356 return value
1357 try:
1358 return value.encode("ascii")
1359 except AttributeError:
1360 # in case you replace the node dynamically e.g. with a dict
1361 return value
1362 except UnicodeEncodeError:
1363 return value
1364
1365 def construct_rt_sequence(self, node, seqtyp, deep=False):
1366 # type: (Any, Any, bool) -> Any
1367 if not isinstance(node, SequenceNode):
1368 raise ConstructorError(
1369 None,
1370 None,
1371 "expected a sequence node, but found %s" % node.id,
1372 node.start_mark,
1373 )
1374 ret_val = []
1375 if node.comment:
1376 seqtyp._yaml_add_comment(node.comment[:2])
1377 if len(node.comment) > 2:
1378 seqtyp.yaml_end_comment_extend(node.comment[2], clear=True)
1379 if node.anchor:
1380 from strictyaml.ruamel.serializer import templated_id
1381
1382 if not templated_id(node.anchor):
1383 seqtyp.yaml_set_anchor(node.anchor)
1384 for idx, child in enumerate(node.value):
1385 if child.comment:
1386 seqtyp._yaml_add_comment(child.comment, key=idx)
1387 child.comment = None # if moved to sequence remove from child
1388 ret_val.append(self.construct_object(child, deep=deep))
1389 seqtyp._yaml_set_idx_line_col(
1390 idx, [child.start_mark.line, child.start_mark.column]
1391 )
1392 return ret_val
1393
1394 def flatten_mapping(self, node):
1395 # type: (Any) -> Any
1396 """
1397 This implements the merge key feature http://yaml.org/type/merge.html
1398 by inserting keys from the merge dict/list of dicts if not yet
1399 available in this node
1400 """
1401
1402 def constructed(value_node):
1403 # type: (Any) -> Any
1404 # If the contents of a merge are defined within the
1405 # merge marker, then they won't have been constructed
1406 # yet. But if they were already constructed, we need to use
1407 # the existing object.
1408 if value_node in self.constructed_objects:
1409 value = self.constructed_objects[value_node]
1410 else:
1411 value = self.construct_object(value_node, deep=False)
1412 return value
1413
1414 # merge = []
1415 merge_map_list = [] # type: List[Any]
1416 index = 0
1417 while index < len(node.value):
1418 key_node, value_node = node.value[index]
1419 if key_node.tag == u"tag:yaml.org,2002:merge":
1420 if merge_map_list: # double << key
1421 if self.allow_duplicate_keys:
1422 del node.value[index]
1423 index += 1
1424 continue
1425 args = [
1426 "while constructing a mapping",
1427 node.start_mark,
1428 'found duplicate key "{}"'.format(key_node.value),
1429 key_node.start_mark,
1430 """
1431 To suppress this check see:
1432 http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
1433 """,
1434 """\
1435 Duplicate keys will become an error in future releases, and are errors
1436 by default when using the new API.
1437 """,
1438 ]
1439 if self.allow_duplicate_keys is None:
1440 warnings.warn(DuplicateKeyFutureWarning(*args))
1441 else:
1442 raise DuplicateKeyError(*args)
1443 del node.value[index]
1444 if isinstance(value_node, MappingNode):
1445 merge_map_list.append((index, constructed(value_node)))
1446 # self.flatten_mapping(value_node)
1447 # merge.extend(value_node.value)
1448 elif isinstance(value_node, SequenceNode):
1449 # submerge = []
1450 for subnode in value_node.value:
1451 if not isinstance(subnode, MappingNode):
1452 raise ConstructorError(
1453 "while constructing a mapping",
1454 node.start_mark,
1455 "expected a mapping for merging, but found %s"
1456 % subnode.id,
1457 subnode.start_mark,
1458 )
1459 merge_map_list.append((index, constructed(subnode)))
1460 # self.flatten_mapping(subnode)
1461 # submerge.append(subnode.value)
1462 # submerge.reverse()
1463 # for value in submerge:
1464 # merge.extend(value)
1465 else:
1466 raise ConstructorError(
1467 "while constructing a mapping",
1468 node.start_mark,
1469 "expected a mapping or list of mappings for merging, "
1470 "but found %s" % value_node.id,
1471 value_node.start_mark,
1472 )
1473 elif key_node.tag == u"tag:yaml.org,2002:value":
1474 key_node.tag = u"tag:yaml.org,2002:str"
1475 index += 1
1476 else:
1477 index += 1
1478 return merge_map_list
1479 # if merge:
1480 # node.value = merge + node.value
1481
1482 def _sentinel(self):
1483 # type: () -> None
1484 pass
1485
1486 def construct_mapping(self, node, maptyp, deep=False): # type: ignore
1487 # type: (Any, Any, bool) -> Any
1488 if not isinstance(node, MappingNode):
1489 raise ConstructorError(
1490 None,
1491 None,
1492 "expected a mapping node, but found %s" % node.id,
1493 node.start_mark,
1494 )
1495 merge_map = self.flatten_mapping(node)
1496 # mapping = {}
1497 if node.comment:
1498 maptyp._yaml_add_comment(node.comment[:2])
1499 if len(node.comment) > 2:
1500 maptyp.yaml_end_comment_extend(node.comment[2], clear=True)
1501 if node.anchor:
1502 from strictyaml.ruamel.serializer import templated_id
1503
1504 if not templated_id(node.anchor):
1505 maptyp.yaml_set_anchor(node.anchor)
1506 last_key, last_value = None, self._sentinel
1507 for key_node, value_node in node.value:
1508 # keys can be list -> deep
1509 key = self.construct_object(key_node, deep=True)
1510 # lists are not hashable, but tuples are
1511 if not isinstance(key, Hashable):
1512 if isinstance(key, MutableSequence):
1513 key_s = CommentedKeySeq(key)
1514 if key_node.flow_style is True:
1515 key_s.fa.set_flow_style()
1516 elif key_node.flow_style is False:
1517 key_s.fa.set_block_style()
1518 key = key_s
1519 elif isinstance(key, MutableMapping):
1520 key_m = CommentedKeyMap(key)
1521 if key_node.flow_style is True:
1522 key_m.fa.set_flow_style()
1523 elif key_node.flow_style is False:
1524 key_m.fa.set_block_style()
1525 key = key_m
1526 if PY2:
1527 try:
1528 hash(key)
1529 except TypeError as exc:
1530 raise ConstructorError(
1531 "while constructing a mapping",
1532 node.start_mark,
1533 "found unacceptable key (%s)" % exc,
1534 key_node.start_mark,
1535 )
1536 else:
1537 if not isinstance(key, Hashable):
1538 raise ConstructorError(
1539 "while constructing a mapping",
1540 node.start_mark,
1541 "found unhashable key",
1542 key_node.start_mark,
1543 )
1544 value = self.construct_object(value_node, deep=deep)
1545 if self.check_mapping_key(node, key_node, maptyp, key, value):
1546 if (
1547 key_node.comment
1548 and len(key_node.comment) > 4
1549 and key_node.comment[4]
1550 ):
1551 if last_value is None:
1552 key_node.comment[0] = key_node.comment.pop(4)
1553 maptyp._yaml_add_comment(key_node.comment, value=last_key)
1554 else:
1555 key_node.comment[2] = key_node.comment.pop(4)
1556 maptyp._yaml_add_comment(key_node.comment, key=key)
1557 key_node.comment = None
1558 if key_node.comment:
1559 maptyp._yaml_add_comment(key_node.comment, key=key)
1560 if value_node.comment:
1561 maptyp._yaml_add_comment(value_node.comment, value=key)
1562 maptyp._yaml_set_kv_line_col(
1563 key,
1564 [
1565 key_node.start_mark.line,
1566 key_node.start_mark.column,
1567 value_node.start_mark.line,
1568 value_node.start_mark.column,
1569 ],
1570 )
1571 maptyp[key] = value
1572 last_key, last_value = key, value # could use indexing
1573 # do this last, or <<: before a key will prevent insertion in instances
1574 # of collections.OrderedDict (as they have no __contains__
1575 if merge_map:
1576 maptyp.add_yaml_merge(merge_map)
1577
1578 def construct_setting(self, node, typ, deep=False):
1579 # type: (Any, Any, bool) -> Any
1580 if not isinstance(node, MappingNode):
1581 raise ConstructorError(
1582 None,
1583 None,
1584 "expected a mapping node, but found %s" % node.id,
1585 node.start_mark,
1586 )
1587 if node.comment:
1588 typ._yaml_add_comment(node.comment[:2])
1589 if len(node.comment) > 2:
1590 typ.yaml_end_comment_extend(node.comment[2], clear=True)
1591 if node.anchor:
1592 from strictyaml.ruamel.serializer import templated_id
1593
1594 if not templated_id(node.anchor):
1595 typ.yaml_set_anchor(node.anchor)
1596 for key_node, value_node in node.value:
1597 # keys can be list -> deep
1598 key = self.construct_object(key_node, deep=True)
1599 # lists are not hashable, but tuples are
1600 if not isinstance(key, Hashable):
1601 if isinstance(key, list):
1602 key = tuple(key)
1603 if PY2:
1604 try:
1605 hash(key)
1606 except TypeError as exc:
1607 raise ConstructorError(
1608 "while constructing a mapping",
1609 node.start_mark,
1610 "found unacceptable key (%s)" % exc,
1611 key_node.start_mark,
1612 )
1613 else:
1614 if not isinstance(key, Hashable):
1615 raise ConstructorError(
1616 "while constructing a mapping",
1617 node.start_mark,
1618 "found unhashable key",
1619 key_node.start_mark,
1620 )
1621 # construct but should be null
1622 value = self.construct_object(value_node, deep=deep) # NOQA
1623 self.check_set_key(node, key_node, typ, key)
1624 if key_node.comment:
1625 typ._yaml_add_comment(key_node.comment, key=key)
1626 if value_node.comment:
1627 typ._yaml_add_comment(value_node.comment, value=key)
1628 typ.add(key)
1629
1630 def construct_yaml_seq(self, node):
1631 # type: (Any) -> Any
1632 data = CommentedSeq()
1633 data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
1634 if node.comment:
1635 data._yaml_add_comment(node.comment)
1636 yield data
1637 data.extend(self.construct_rt_sequence(node, data))
1638 self.set_collection_style(data, node)
1639
1640 def construct_yaml_map(self, node):
1641 # type: (Any) -> Any
1642 data = CommentedMap()
1643 data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
1644 yield data
1645 self.construct_mapping(node, data, deep=True)
1646 self.set_collection_style(data, node)
1647
1648 def set_collection_style(self, data, node):
1649 # type: (Any, Any) -> None
1650 if len(data) == 0:
1651 return
1652 if node.flow_style is True:
1653 data.fa.set_flow_style()
1654 elif node.flow_style is False:
1655 data.fa.set_block_style()
1656
1657 def construct_yaml_object(self, node, cls):
1658 # type: (Any, Any) -> Any
1659 data = cls.__new__(cls)
1660 yield data
1661 if hasattr(data, "__setstate__"):
1662 state = SafeConstructor.construct_mapping(self, node, deep=True)
1663 data.__setstate__(state)
1664 else:
1665 state = SafeConstructor.construct_mapping(self, node)
1666 data.__dict__.update(state)
1667
1668 def construct_yaml_omap(self, node):
1669 # type: (Any) -> Any
1670 # Note: we do now check for duplicate keys
1671 omap = CommentedOrderedMap()
1672 omap._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
1673 if node.flow_style is True:
1674 omap.fa.set_flow_style()
1675 elif node.flow_style is False:
1676 omap.fa.set_block_style()
1677 yield omap
1678 if node.comment:
1679 omap._yaml_add_comment(node.comment[:2])
1680 if len(node.comment) > 2:
1681 omap.yaml_end_comment_extend(node.comment[2], clear=True)
1682 if not isinstance(node, SequenceNode):
1683 raise ConstructorError(
1684 "while constructing an ordered map",
1685 node.start_mark,
1686 "expected a sequence, but found %s" % node.id,
1687 node.start_mark,
1688 )
1689 for subnode in node.value:
1690 if not isinstance(subnode, MappingNode):
1691 raise ConstructorError(
1692 "while constructing an ordered map",
1693 node.start_mark,
1694 "expected a mapping of length 1, but found %s" % subnode.id,
1695 subnode.start_mark,
1696 )
1697 if len(subnode.value) != 1:
1698 raise ConstructorError(
1699 "while constructing an ordered map",
1700 node.start_mark,
1701 "expected a single mapping item, but found %d items"
1702 % len(subnode.value),
1703 subnode.start_mark,
1704 )
1705 key_node, value_node = subnode.value[0]
1706 key = self.construct_object(key_node)
1707 assert key not in omap
1708 value = self.construct_object(value_node)
1709 if key_node.comment:
1710 omap._yaml_add_comment(key_node.comment, key=key)
1711 if subnode.comment:
1712 omap._yaml_add_comment(subnode.comment, key=key)
1713 if value_node.comment:
1714 omap._yaml_add_comment(value_node.comment, value=key)
1715 omap[key] = value
1716
1717 def construct_yaml_set(self, node):
1718 # type: (Any) -> Any
1719 data = CommentedSet()
1720 data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
1721 yield data
1722 self.construct_setting(node, data)
1723
1724 def construct_undefined(self, node):
1725 # type: (Any) -> Any
1726 try:
1727 if isinstance(node, MappingNode):
1728 data = CommentedMap()
1729 data._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
1730 if node.flow_style is True:
1731 data.fa.set_flow_style()
1732 elif node.flow_style is False:
1733 data.fa.set_block_style()
1734 data.yaml_set_tag(node.tag)
1735 yield data
1736 if node.anchor:
1737 data.yaml_set_anchor(node.anchor)
1738 self.construct_mapping(node, data)
1739 return
1740 elif isinstance(node, ScalarNode):
1741 data2 = TaggedScalar()
1742 data2.value = self.construct_scalar(node)
1743 data2.style = node.style
1744 data2.yaml_set_tag(node.tag)
1745 yield data2
1746 if node.anchor:
1747 data2.yaml_set_anchor(node.anchor, always_dump=True)
1748 return
1749 elif isinstance(node, SequenceNode):
1750 data3 = CommentedSeq()
1751 data3._yaml_set_line_col(node.start_mark.line, node.start_mark.column)
1752 if node.flow_style is True:
1753 data3.fa.set_flow_style()
1754 elif node.flow_style is False:
1755 data3.fa.set_block_style()
1756 data3.yaml_set_tag(node.tag)
1757 yield data3
1758 if node.anchor:
1759 data3.yaml_set_anchor(node.anchor)
1760 data3.extend(self.construct_sequence(node))
1761 return
1762 except: # NOQA
1763 pass
1764 raise ConstructorError(
1765 None,
1766 None,
1767 "could not determine a constructor for the tag %r" % utf8(node.tag),
1768 node.start_mark,
1769 )
1770
1771 def construct_yaml_timestamp(self, node, values=None):
1772 # type: (Any, Any) -> Any
1773 try:
1774 match = self.timestamp_regexp.match(node.value)
1775 except TypeError:
1776 match = None
1777 if match is None:
1778 raise ConstructorError(
1779 None,
1780 None,
1781 'failed to construct timestamp from "{}"'.format(node.value),
1782 node.start_mark,
1783 )
1784 values = match.groupdict()
1785 if not values["hour"]:
1786 return SafeConstructor.construct_yaml_timestamp(self, node, values)
1787 for part in ["t", "tz_sign", "tz_hour", "tz_minute"]:
1788 if values[part]:
1789 break
1790 else:
1791 return SafeConstructor.construct_yaml_timestamp(self, node, values)
1792 year = int(values["year"])
1793 month = int(values["month"])
1794 day = int(values["day"])
1795 hour = int(values["hour"])
1796 minute = int(values["minute"])
1797 second = int(values["second"])
1798 fraction = 0
1799 if values["fraction"]:
1800 fraction_s = values["fraction"][:6]
1801 while len(fraction_s) < 6:
1802 fraction_s += "0"
1803 fraction = int(fraction_s)
1804 if len(values["fraction"]) > 6 and int(values["fraction"][6]) > 4:
1805 fraction += 1
1806 delta = None
1807 if values["tz_sign"]:
1808 tz_hour = int(values["tz_hour"])
1809 minutes = values["tz_minute"]
1810 tz_minute = int(minutes) if minutes else 0
1811 delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
1812 if values["tz_sign"] == "-":
1813 delta = -delta
1814 # shold check for NOne and solve issue 366 should be tzinfo=delta)
1815 if delta:
1816 dt = datetime.datetime(year, month, day, hour, minute)
1817 dt -= delta
1818 data = TimeStamp(
1819 dt.year, dt.month, dt.day, dt.hour, dt.minute, second, fraction
1820 )
1821 data._yaml["delta"] = delta
1822 tz = values["tz_sign"] + values["tz_hour"]
1823 if values["tz_minute"]:
1824 tz += ":" + values["tz_minute"]
1825 data._yaml["tz"] = tz
1826 else:
1827 data = TimeStamp(year, month, day, hour, minute, second, fraction)
1828 if values["tz"]: # no delta
1829 data._yaml["tz"] = values["tz"]
1830
1831 if values["t"]:
1832 data._yaml["t"] = True
1833 return data
1834
1835 def construct_yaml_bool(self, node):
1836 # type: (Any) -> Any
1837 b = SafeConstructor.construct_yaml_bool(self, node)
1838 if node.anchor:
1839 return ScalarBoolean(b, anchor=node.anchor)
1840 return b
1841
1842
1843 RoundTripConstructor.add_constructor(
1844 u"tag:yaml.org,2002:null", RoundTripConstructor.construct_yaml_null
1845 )
1846
1847 RoundTripConstructor.add_constructor(
1848 u"tag:yaml.org,2002:bool", RoundTripConstructor.construct_yaml_bool
1849 )
1850
1851 RoundTripConstructor.add_constructor(
1852 u"tag:yaml.org,2002:int", RoundTripConstructor.construct_yaml_int
1853 )
1854
1855 RoundTripConstructor.add_constructor(
1856 u"tag:yaml.org,2002:float", RoundTripConstructor.construct_yaml_float
1857 )
1858
1859 RoundTripConstructor.add_constructor(
1860 u"tag:yaml.org,2002:binary", RoundTripConstructor.construct_yaml_binary
1861 )
1862
1863 RoundTripConstructor.add_constructor(
1864 u"tag:yaml.org,2002:timestamp", RoundTripConstructor.construct_yaml_timestamp
1865 )
1866
1867 RoundTripConstructor.add_constructor(
1868 u"tag:yaml.org,2002:omap", RoundTripConstructor.construct_yaml_omap
1869 )
1870
1871 RoundTripConstructor.add_constructor(
1872 u"tag:yaml.org,2002:pairs", RoundTripConstructor.construct_yaml_pairs
1873 )
1874
1875 RoundTripConstructor.add_constructor(
1876 u"tag:yaml.org,2002:set", RoundTripConstructor.construct_yaml_set
1877 )
1878
1879 RoundTripConstructor.add_constructor(
1880 u"tag:yaml.org,2002:str", RoundTripConstructor.construct_yaml_str
1881 )
1882
1883 RoundTripConstructor.add_constructor(
1884 u"tag:yaml.org,2002:seq", RoundTripConstructor.construct_yaml_seq
1885 )
1886
1887 RoundTripConstructor.add_constructor(
1888 u"tag:yaml.org,2002:map", RoundTripConstructor.construct_yaml_map
1889 )
1890
1891 RoundTripConstructor.add_constructor(None, RoundTripConstructor.construct_undefined)