| 1 |
# coding: utf-8 |
| 2 |
|
| 3 |
from __future__ import print_function, absolute_import, division |
| 4 |
|
| 5 |
|
| 6 |
from strictyaml.ruamel.error import * # NOQA |
| 7 |
from strictyaml.ruamel.nodes import * # NOQA |
| 8 |
from strictyaml.ruamel.compat import text_type, binary_type, to_unicode, PY2, PY3 |
| 9 |
from strictyaml.ruamel.compat import ordereddict # type: ignore |
| 10 |
from strictyaml.ruamel.compat import nprint, nprintf # NOQA |
| 11 |
from strictyaml.ruamel.scalarstring import ( |
| 12 |
LiteralScalarString, |
| 13 |
FoldedScalarString, |
| 14 |
SingleQuotedScalarString, |
| 15 |
DoubleQuotedScalarString, |
| 16 |
PlainScalarString, |
| 17 |
) |
| 18 |
from strictyaml.ruamel.comments import ( |
| 19 |
CommentedMap, |
| 20 |
CommentedOrderedMap, |
| 21 |
CommentedSeq, |
| 22 |
CommentedKeySeq, |
| 23 |
CommentedKeyMap, |
| 24 |
CommentedSet, |
| 25 |
comment_attrib, |
| 26 |
merge_attrib, |
| 27 |
TaggedScalar, |
| 28 |
) |
| 29 |
from strictyaml.ruamel.scalarint import ( |
| 30 |
ScalarInt, |
| 31 |
BinaryInt, |
| 32 |
OctalInt, |
| 33 |
HexInt, |
| 34 |
HexCapsInt, |
| 35 |
) |
| 36 |
from strictyaml.ruamel.scalarfloat import ScalarFloat |
| 37 |
from strictyaml.ruamel.scalarbool import ScalarBoolean |
| 38 |
from strictyaml.ruamel.timestamp import TimeStamp |
| 39 |
|
| 40 |
import datetime |
| 41 |
import sys |
| 42 |
import types |
| 43 |
|
| 44 |
if PY3: |
| 45 |
import copyreg |
| 46 |
import base64 |
| 47 |
else: |
| 48 |
import copy_reg as copyreg # type: ignore |
| 49 |
|
| 50 |
if False: # MYPY |
| 51 |
from typing import Dict, List, Any, Union, Text, Optional # NOQA |
| 52 |
|
| 53 |
# fmt: off |
| 54 |
__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer', |
| 55 |
'RepresenterError', 'RoundTripRepresenter'] |
| 56 |
# fmt: on |
| 57 |
|
| 58 |
|
| 59 |
class RepresenterError(YAMLError): |
| 60 |
pass |
| 61 |
|
| 62 |
|
| 63 |
if PY2: |
| 64 |
|
| 65 |
def get_classobj_bases(cls): |
| 66 |
# type: (Any) -> Any |
| 67 |
bases = [cls] |
| 68 |
for base in cls.__bases__: |
| 69 |
bases.extend(get_classobj_bases(base)) |
| 70 |
return bases |
| 71 |
|
| 72 |
|
| 73 |
class BaseRepresenter(object): |
| 74 |
|
| 75 |
yaml_representers = {} # type: Dict[Any, Any] |
| 76 |
yaml_multi_representers = {} # type: Dict[Any, Any] |
| 77 |
|
| 78 |
def __init__(self, default_style=None, default_flow_style=None, dumper=None): |
| 79 |
# type: (Any, Any, Any, Any) -> None |
| 80 |
self.dumper = dumper |
| 81 |
if self.dumper is not None: |
| 82 |
self.dumper._representer = self |
| 83 |
self.default_style = default_style |
| 84 |
self.default_flow_style = default_flow_style |
| 85 |
self.represented_objects = {} # type: Dict[Any, Any] |
| 86 |
self.object_keeper = [] # type: List[Any] |
| 87 |
self.alias_key = None # type: Optional[int] |
| 88 |
self.sort_base_mapping_type_on_output = True |
| 89 |
|
| 90 |
@property |
| 91 |
def serializer(self): |
| 92 |
# type: () -> Any |
| 93 |
try: |
| 94 |
if hasattr(self.dumper, "typ"): |
| 95 |
return self.dumper.serializer |
| 96 |
return self.dumper._serializer |
| 97 |
except AttributeError: |
| 98 |
return self # cyaml |
| 99 |
|
| 100 |
def represent(self, data): |
| 101 |
# type: (Any) -> None |
| 102 |
node = self.represent_data(data) |
| 103 |
self.serializer.serialize(node) |
| 104 |
self.represented_objects = {} |
| 105 |
self.object_keeper = [] |
| 106 |
self.alias_key = None |
| 107 |
|
| 108 |
def represent_data(self, data): |
| 109 |
# type: (Any) -> Any |
| 110 |
if self.ignore_aliases(data): |
| 111 |
self.alias_key = None |
| 112 |
else: |
| 113 |
self.alias_key = id(data) |
| 114 |
if self.alias_key is not None: |
| 115 |
if self.alias_key in self.represented_objects: |
| 116 |
node = self.represented_objects[self.alias_key] |
| 117 |
# if node is None: |
| 118 |
# raise RepresenterError( |
| 119 |
# "recursive objects are not allowed: %r" % data) |
| 120 |
return node |
| 121 |
# self.represented_objects[alias_key] = None |
| 122 |
self.object_keeper.append(data) |
| 123 |
data_types = type(data).__mro__ |
| 124 |
if PY2: |
| 125 |
# if type(data) is types.InstanceType: |
| 126 |
if isinstance(data, types.InstanceType): |
| 127 |
data_types = get_classobj_bases(data.__class__) + list(data_types) |
| 128 |
if data_types[0] in self.yaml_representers: |
| 129 |
node = self.yaml_representers[data_types[0]](self, data) |
| 130 |
else: |
| 131 |
for data_type in data_types: |
| 132 |
if data_type in self.yaml_multi_representers: |
| 133 |
node = self.yaml_multi_representers[data_type](self, data) |
| 134 |
break |
| 135 |
else: |
| 136 |
if None in self.yaml_multi_representers: |
| 137 |
node = self.yaml_multi_representers[None](self, data) |
| 138 |
elif None in self.yaml_representers: |
| 139 |
node = self.yaml_representers[None](self, data) |
| 140 |
else: |
| 141 |
node = ScalarNode(None, text_type(data)) |
| 142 |
# if alias_key is not None: |
| 143 |
# self.represented_objects[alias_key] = node |
| 144 |
return node |
| 145 |
|
| 146 |
def represent_key(self, data): |
| 147 |
# type: (Any) -> Any |
| 148 |
""" |
| 149 |
David Fraser: Extract a method to represent keys in mappings, so that |
| 150 |
a subclass can choose not to quote them (for example) |
| 151 |
used in represent_mapping |
| 152 |
https://bitbucket.org/davidfraser/pyyaml/commits/d81df6eb95f20cac4a79eed95ae553b5c6f77b8c |
| 153 |
""" |
| 154 |
return self.represent_data(data) |
| 155 |
|
| 156 |
@classmethod |
| 157 |
def add_representer(cls, data_type, representer): |
| 158 |
# type: (Any, Any) -> None |
| 159 |
if "yaml_representers" not in cls.__dict__: |
| 160 |
cls.yaml_representers = cls.yaml_representers.copy() |
| 161 |
cls.yaml_representers[data_type] = representer |
| 162 |
|
| 163 |
@classmethod |
| 164 |
def add_multi_representer(cls, data_type, representer): |
| 165 |
# type: (Any, Any) -> None |
| 166 |
if "yaml_multi_representers" not in cls.__dict__: |
| 167 |
cls.yaml_multi_representers = cls.yaml_multi_representers.copy() |
| 168 |
cls.yaml_multi_representers[data_type] = representer |
| 169 |
|
| 170 |
def represent_scalar(self, tag, value, style=None, anchor=None): |
| 171 |
# type: (Any, Any, Any, Any) -> Any |
| 172 |
if style is None: |
| 173 |
style = self.default_style |
| 174 |
comment = None |
| 175 |
if style and style[0] in "|>": |
| 176 |
comment = getattr(value, "comment", None) |
| 177 |
if comment: |
| 178 |
comment = [None, [comment]] |
| 179 |
node = ScalarNode(tag, value, style=style, comment=comment, anchor=anchor) |
| 180 |
if self.alias_key is not None: |
| 181 |
self.represented_objects[self.alias_key] = node |
| 182 |
return node |
| 183 |
|
| 184 |
def represent_sequence(self, tag, sequence, flow_style=None): |
| 185 |
# type: (Any, Any, Any) -> Any |
| 186 |
value = [] # type: List[Any] |
| 187 |
node = SequenceNode(tag, value, flow_style=flow_style) |
| 188 |
if self.alias_key is not None: |
| 189 |
self.represented_objects[self.alias_key] = node |
| 190 |
best_style = True |
| 191 |
for item in sequence: |
| 192 |
node_item = self.represent_data(item) |
| 193 |
if not (isinstance(node_item, ScalarNode) and not node_item.style): |
| 194 |
best_style = False |
| 195 |
value.append(node_item) |
| 196 |
if flow_style is None: |
| 197 |
if self.default_flow_style is not None: |
| 198 |
node.flow_style = self.default_flow_style |
| 199 |
else: |
| 200 |
node.flow_style = best_style |
| 201 |
return node |
| 202 |
|
| 203 |
def represent_omap(self, tag, omap, flow_style=None): |
| 204 |
# type: (Any, Any, Any) -> Any |
| 205 |
value = [] # type: List[Any] |
| 206 |
node = SequenceNode(tag, value, flow_style=flow_style) |
| 207 |
if self.alias_key is not None: |
| 208 |
self.represented_objects[self.alias_key] = node |
| 209 |
best_style = True |
| 210 |
for item_key in omap: |
| 211 |
item_val = omap[item_key] |
| 212 |
node_item = self.represent_data({item_key: item_val}) |
| 213 |
# if not (isinstance(node_item, ScalarNode) \ |
| 214 |
# and not node_item.style): |
| 215 |
# best_style = False |
| 216 |
value.append(node_item) |
| 217 |
if flow_style is None: |
| 218 |
if self.default_flow_style is not None: |
| 219 |
node.flow_style = self.default_flow_style |
| 220 |
else: |
| 221 |
node.flow_style = best_style |
| 222 |
return node |
| 223 |
|
| 224 |
def represent_mapping(self, tag, mapping, flow_style=None): |
| 225 |
# type: (Any, Any, Any) -> Any |
| 226 |
value = [] # type: List[Any] |
| 227 |
node = MappingNode(tag, value, flow_style=flow_style) |
| 228 |
if self.alias_key is not None: |
| 229 |
self.represented_objects[self.alias_key] = node |
| 230 |
best_style = True |
| 231 |
if hasattr(mapping, "items"): |
| 232 |
mapping = list(mapping.items()) |
| 233 |
if self.sort_base_mapping_type_on_output: |
| 234 |
try: |
| 235 |
mapping = sorted(mapping) |
| 236 |
except TypeError: |
| 237 |
pass |
| 238 |
for item_key, item_value in mapping: |
| 239 |
node_key = self.represent_key(item_key) |
| 240 |
node_value = self.represent_data(item_value) |
| 241 |
if not (isinstance(node_key, ScalarNode) and not node_key.style): |
| 242 |
best_style = False |
| 243 |
if not (isinstance(node_value, ScalarNode) and not node_value.style): |
| 244 |
best_style = False |
| 245 |
value.append((node_key, node_value)) |
| 246 |
if flow_style is None: |
| 247 |
if self.default_flow_style is not None: |
| 248 |
node.flow_style = self.default_flow_style |
| 249 |
else: |
| 250 |
node.flow_style = best_style |
| 251 |
return node |
| 252 |
|
| 253 |
def ignore_aliases(self, data): |
| 254 |
# type: (Any) -> bool |
| 255 |
return False |
| 256 |
|
| 257 |
|
| 258 |
class SafeRepresenter(BaseRepresenter): |
| 259 |
def ignore_aliases(self, data): |
| 260 |
# type: (Any) -> bool |
| 261 |
# https://docs.python.org/3/reference/expressions.html#parenthesized-forms : |
| 262 |
# "i.e. two occurrences of the empty tuple may or may not yield the same object" |
| 263 |
# so "data is ()" should not be used |
| 264 |
if data is None or (isinstance(data, tuple) and data == ()): |
| 265 |
return True |
| 266 |
if isinstance(data, (binary_type, text_type, bool, int, float)): |
| 267 |
return True |
| 268 |
return False |
| 269 |
|
| 270 |
def represent_none(self, data): |
| 271 |
# type: (Any) -> Any |
| 272 |
return self.represent_scalar(u"tag:yaml.org,2002:null", u"null") |
| 273 |
|
| 274 |
if PY3: |
| 275 |
|
| 276 |
def represent_str(self, data): |
| 277 |
# type: (Any) -> Any |
| 278 |
return self.represent_scalar(u"tag:yaml.org,2002:str", data) |
| 279 |
|
| 280 |
def represent_binary(self, data): |
| 281 |
# type: (Any) -> Any |
| 282 |
if hasattr(base64, "encodebytes"): |
| 283 |
data = base64.encodebytes(data).decode("ascii") |
| 284 |
else: |
| 285 |
data = base64.encodestring(data).decode("ascii") |
| 286 |
return self.represent_scalar(u"tag:yaml.org,2002:binary", data, style="|") |
| 287 |
|
| 288 |
else: |
| 289 |
|
| 290 |
def represent_str(self, data): |
| 291 |
# type: (Any) -> Any |
| 292 |
tag = None |
| 293 |
style = None |
| 294 |
try: |
| 295 |
data = unicode(data, "ascii") |
| 296 |
tag = u"tag:yaml.org,2002:str" |
| 297 |
except UnicodeDecodeError: |
| 298 |
try: |
| 299 |
data = unicode(data, "utf-8") |
| 300 |
tag = u"tag:yaml.org,2002:str" |
| 301 |
except UnicodeDecodeError: |
| 302 |
data = data.encode("base64") |
| 303 |
tag = u"tag:yaml.org,2002:binary" |
| 304 |
style = "|" |
| 305 |
return self.represent_scalar(tag, data, style=style) |
| 306 |
|
| 307 |
def represent_unicode(self, data): |
| 308 |
# type: (Any) -> Any |
| 309 |
return self.represent_scalar(u"tag:yaml.org,2002:str", data) |
| 310 |
|
| 311 |
def represent_bool(self, data, anchor=None): |
| 312 |
# type: (Any, Optional[Any]) -> Any |
| 313 |
try: |
| 314 |
value = self.dumper.boolean_representation[bool(data)] |
| 315 |
except AttributeError: |
| 316 |
if data: |
| 317 |
value = u"true" |
| 318 |
else: |
| 319 |
value = u"false" |
| 320 |
return self.represent_scalar(u"tag:yaml.org,2002:bool", value, anchor=anchor) |
| 321 |
|
| 322 |
def represent_int(self, data): |
| 323 |
# type: (Any) -> Any |
| 324 |
return self.represent_scalar(u"tag:yaml.org,2002:int", text_type(data)) |
| 325 |
|
| 326 |
if PY2: |
| 327 |
|
| 328 |
def represent_long(self, data): |
| 329 |
# type: (Any) -> Any |
| 330 |
return self.represent_scalar(u"tag:yaml.org,2002:int", text_type(data)) |
| 331 |
|
| 332 |
inf_value = 1e300 |
| 333 |
while repr(inf_value) != repr(inf_value * inf_value): |
| 334 |
inf_value *= inf_value |
| 335 |
|
| 336 |
def represent_float(self, data): |
| 337 |
# type: (Any) -> Any |
| 338 |
if data != data or (data == 0.0 and data == 1.0): |
| 339 |
value = u".nan" |
| 340 |
elif data == self.inf_value: |
| 341 |
value = u".inf" |
| 342 |
elif data == -self.inf_value: |
| 343 |
value = u"-.inf" |
| 344 |
else: |
| 345 |
value = to_unicode(repr(data)).lower() |
| 346 |
if getattr(self.serializer, "use_version", None) == (1, 1): |
| 347 |
if u"." not in value and u"e" in value: |
| 348 |
# Note that in some cases `repr(data)` represents a float number |
| 349 |
# without the decimal parts. For instance: |
| 350 |
# >>> repr(1e17) |
| 351 |
# '1e17' |
| 352 |
# Unfortunately, this is not a valid float representation according |
| 353 |
# to the definition of the `!!float` tag in YAML 1.1. We fix |
| 354 |
# this by adding '.0' before the 'e' symbol. |
| 355 |
value = value.replace(u"e", u".0e", 1) |
| 356 |
return self.represent_scalar(u"tag:yaml.org,2002:float", value) |
| 357 |
|
| 358 |
def represent_list(self, data): |
| 359 |
# type: (Any) -> Any |
| 360 |
# pairs = (len(data) > 0 and isinstance(data, list)) |
| 361 |
# if pairs: |
| 362 |
# for item in data: |
| 363 |
# if not isinstance(item, tuple) or len(item) != 2: |
| 364 |
# pairs = False |
| 365 |
# break |
| 366 |
# if not pairs: |
| 367 |
return self.represent_sequence(u"tag:yaml.org,2002:seq", data) |
| 368 |
|
| 369 |
# value = [] |
| 370 |
# for item_key, item_value in data: |
| 371 |
# value.append(self.represent_mapping(u'tag:yaml.org,2002:map', |
| 372 |
# [(item_key, item_value)])) |
| 373 |
# return SequenceNode(u'tag:yaml.org,2002:pairs', value) |
| 374 |
|
| 375 |
def represent_dict(self, data): |
| 376 |
# type: (Any) -> Any |
| 377 |
return self.represent_mapping(u"tag:yaml.org,2002:map", data) |
| 378 |
|
| 379 |
def represent_ordereddict(self, data): |
| 380 |
# type: (Any) -> Any |
| 381 |
return self.represent_omap(u"tag:yaml.org,2002:omap", data) |
| 382 |
|
| 383 |
def represent_set(self, data): |
| 384 |
# type: (Any) -> Any |
| 385 |
value = {} # type: Dict[Any, None] |
| 386 |
for key in data: |
| 387 |
value[key] = None |
| 388 |
return self.represent_mapping(u"tag:yaml.org,2002:set", value) |
| 389 |
|
| 390 |
def represent_date(self, data): |
| 391 |
# type: (Any) -> Any |
| 392 |
value = to_unicode(data.isoformat()) |
| 393 |
return self.represent_scalar(u"tag:yaml.org,2002:timestamp", value) |
| 394 |
|
| 395 |
def represent_datetime(self, data): |
| 396 |
# type: (Any) -> Any |
| 397 |
value = to_unicode(data.isoformat(" ")) |
| 398 |
return self.represent_scalar(u"tag:yaml.org,2002:timestamp", value) |
| 399 |
|
| 400 |
def represent_yaml_object(self, tag, data, cls, flow_style=None): |
| 401 |
# type: (Any, Any, Any, Any) -> Any |
| 402 |
if hasattr(data, "__getstate__"): |
| 403 |
state = data.__getstate__() |
| 404 |
else: |
| 405 |
state = data.__dict__.copy() |
| 406 |
return self.represent_mapping(tag, state, flow_style=flow_style) |
| 407 |
|
| 408 |
def represent_undefined(self, data): |
| 409 |
# type: (Any) -> None |
| 410 |
raise RepresenterError("cannot represent an object: %s" % (data,)) |
| 411 |
|
| 412 |
|
| 413 |
SafeRepresenter.add_representer(type(None), SafeRepresenter.represent_none) |
| 414 |
|
| 415 |
SafeRepresenter.add_representer(str, SafeRepresenter.represent_str) |
| 416 |
|
| 417 |
if PY2: |
| 418 |
SafeRepresenter.add_representer(unicode, SafeRepresenter.represent_unicode) |
| 419 |
else: |
| 420 |
SafeRepresenter.add_representer(bytes, SafeRepresenter.represent_binary) |
| 421 |
|
| 422 |
SafeRepresenter.add_representer(bool, SafeRepresenter.represent_bool) |
| 423 |
|
| 424 |
SafeRepresenter.add_representer(int, SafeRepresenter.represent_int) |
| 425 |
|
| 426 |
if PY2: |
| 427 |
SafeRepresenter.add_representer(long, SafeRepresenter.represent_long) |
| 428 |
|
| 429 |
SafeRepresenter.add_representer(float, SafeRepresenter.represent_float) |
| 430 |
|
| 431 |
SafeRepresenter.add_representer(list, SafeRepresenter.represent_list) |
| 432 |
|
| 433 |
SafeRepresenter.add_representer(tuple, SafeRepresenter.represent_list) |
| 434 |
|
| 435 |
SafeRepresenter.add_representer(dict, SafeRepresenter.represent_dict) |
| 436 |
|
| 437 |
SafeRepresenter.add_representer(set, SafeRepresenter.represent_set) |
| 438 |
|
| 439 |
SafeRepresenter.add_representer(ordereddict, SafeRepresenter.represent_ordereddict) |
| 440 |
|
| 441 |
if sys.version_info >= (2, 7): |
| 442 |
import collections |
| 443 |
|
| 444 |
SafeRepresenter.add_representer( |
| 445 |
collections.OrderedDict, SafeRepresenter.represent_ordereddict |
| 446 |
) |
| 447 |
|
| 448 |
SafeRepresenter.add_representer(datetime.date, SafeRepresenter.represent_date) |
| 449 |
|
| 450 |
SafeRepresenter.add_representer(datetime.datetime, SafeRepresenter.represent_datetime) |
| 451 |
|
| 452 |
SafeRepresenter.add_representer(None, SafeRepresenter.represent_undefined) |
| 453 |
|
| 454 |
|
| 455 |
class Representer(SafeRepresenter): |
| 456 |
if PY2: |
| 457 |
|
| 458 |
def represent_str(self, data): |
| 459 |
# type: (Any) -> Any |
| 460 |
tag = None |
| 461 |
style = None |
| 462 |
try: |
| 463 |
data = unicode(data, "ascii") |
| 464 |
tag = u"tag:yaml.org,2002:str" |
| 465 |
except UnicodeDecodeError: |
| 466 |
try: |
| 467 |
data = unicode(data, "utf-8") |
| 468 |
tag = u"tag:yaml.org,2002:python/str" |
| 469 |
except UnicodeDecodeError: |
| 470 |
data = data.encode("base64") |
| 471 |
tag = u"tag:yaml.org,2002:binary" |
| 472 |
style = "|" |
| 473 |
return self.represent_scalar(tag, data, style=style) |
| 474 |
|
| 475 |
def represent_unicode(self, data): |
| 476 |
# type: (Any) -> Any |
| 477 |
tag = None |
| 478 |
try: |
| 479 |
data.encode("ascii") |
| 480 |
tag = u"tag:yaml.org,2002:python/unicode" |
| 481 |
except UnicodeEncodeError: |
| 482 |
tag = u"tag:yaml.org,2002:str" |
| 483 |
return self.represent_scalar(tag, data) |
| 484 |
|
| 485 |
def represent_long(self, data): |
| 486 |
# type: (Any) -> Any |
| 487 |
tag = u"tag:yaml.org,2002:int" |
| 488 |
if int(data) is not data: |
| 489 |
tag = u"tag:yaml.org,2002:python/long" |
| 490 |
return self.represent_scalar(tag, to_unicode(data)) |
| 491 |
|
| 492 |
def represent_complex(self, data): |
| 493 |
# type: (Any) -> Any |
| 494 |
if data.imag == 0.0: |
| 495 |
data = u"%r" % data.real |
| 496 |
elif data.real == 0.0: |
| 497 |
data = u"%rj" % data.imag |
| 498 |
elif data.imag > 0: |
| 499 |
data = u"%r+%rj" % (data.real, data.imag) |
| 500 |
else: |
| 501 |
data = u"%r%rj" % (data.real, data.imag) |
| 502 |
return self.represent_scalar(u"tag:yaml.org,2002:python/complex", data) |
| 503 |
|
| 504 |
def represent_tuple(self, data): |
| 505 |
# type: (Any) -> Any |
| 506 |
return self.represent_sequence(u"tag:yaml.org,2002:python/tuple", data) |
| 507 |
|
| 508 |
def represent_name(self, data): |
| 509 |
# type: (Any) -> Any |
| 510 |
try: |
| 511 |
name = u"%s.%s" % (data.__module__, data.__qualname__) |
| 512 |
except AttributeError: |
| 513 |
# probably PY2 |
| 514 |
name = u"%s.%s" % (data.__module__, data.__name__) |
| 515 |
return self.represent_scalar(u"tag:yaml.org,2002:python/name:" + name, "") |
| 516 |
|
| 517 |
def represent_module(self, data): |
| 518 |
# type: (Any) -> Any |
| 519 |
return self.represent_scalar( |
| 520 |
u"tag:yaml.org,2002:python/module:" + data.__name__, "" |
| 521 |
) |
| 522 |
|
| 523 |
if PY2: |
| 524 |
|
| 525 |
def represent_instance(self, data): |
| 526 |
# type: (Any) -> Any |
| 527 |
# For instances of classic classes, we use __getinitargs__ and |
| 528 |
# __getstate__ to serialize the data. |
| 529 |
|
| 530 |
# If data.__getinitargs__ exists, the object must be reconstructed |
| 531 |
# by calling cls(**args), where args is a tuple returned by |
| 532 |
# __getinitargs__. Otherwise, the cls.__init__ method should never |
| 533 |
# be called and the class instance is created by instantiating a |
| 534 |
# trivial class and assigning to the instance's __class__ variable. |
| 535 |
|
| 536 |
# If data.__getstate__ exists, it returns the state of the object. |
| 537 |
# Otherwise, the state of the object is data.__dict__. |
| 538 |
|
| 539 |
# We produce either a !!python/object or !!python/object/new node. |
| 540 |
# If data.__getinitargs__ does not exist and state is a dictionary, |
| 541 |
# we produce a !!python/object node . Otherwise we produce a |
| 542 |
# !!python/object/new node. |
| 543 |
|
| 544 |
cls = data.__class__ |
| 545 |
class_name = u"%s.%s" % (cls.__module__, cls.__name__) |
| 546 |
args = None |
| 547 |
state = None |
| 548 |
if hasattr(data, "__getinitargs__"): |
| 549 |
args = list(data.__getinitargs__()) |
| 550 |
if hasattr(data, "__getstate__"): |
| 551 |
state = data.__getstate__() |
| 552 |
else: |
| 553 |
state = data.__dict__ |
| 554 |
if args is None and isinstance(state, dict): |
| 555 |
return self.represent_mapping( |
| 556 |
u"tag:yaml.org,2002:python/object:" + class_name, state |
| 557 |
) |
| 558 |
if isinstance(state, dict) and not state: |
| 559 |
return self.represent_sequence( |
| 560 |
u"tag:yaml.org,2002:python/object/new:" + class_name, args |
| 561 |
) |
| 562 |
value = {} |
| 563 |
if bool(args): |
| 564 |
value["args"] = args |
| 565 |
value["state"] = state # type: ignore |
| 566 |
return self.represent_mapping( |
| 567 |
u"tag:yaml.org,2002:python/object/new:" + class_name, value |
| 568 |
) |
| 569 |
|
| 570 |
def represent_object(self, data): |
| 571 |
# type: (Any) -> Any |
| 572 |
# We use __reduce__ API to save the data. data.__reduce__ returns |
| 573 |
# a tuple of length 2-5: |
| 574 |
# (function, args, state, listitems, dictitems) |
| 575 |
|
| 576 |
# For reconstructing, we calls function(*args), then set its state, |
| 577 |
# listitems, and dictitems if they are not None. |
| 578 |
|
| 579 |
# A special case is when function.__name__ == '__newobj__'. In this |
| 580 |
# case we create the object with args[0].__new__(*args). |
| 581 |
|
| 582 |
# Another special case is when __reduce__ returns a string - we don't |
| 583 |
# support it. |
| 584 |
|
| 585 |
# We produce a !!python/object, !!python/object/new or |
| 586 |
# !!python/object/apply node. |
| 587 |
|
| 588 |
cls = type(data) |
| 589 |
if cls in copyreg.dispatch_table: |
| 590 |
reduce = copyreg.dispatch_table[cls](data) |
| 591 |
elif hasattr(data, "__reduce_ex__"): |
| 592 |
reduce = data.__reduce_ex__(2) |
| 593 |
elif hasattr(data, "__reduce__"): |
| 594 |
reduce = data.__reduce__() |
| 595 |
else: |
| 596 |
raise RepresenterError("cannot represent object: %r" % (data,)) |
| 597 |
reduce = (list(reduce) + [None] * 5)[:5] |
| 598 |
function, args, state, listitems, dictitems = reduce |
| 599 |
args = list(args) |
| 600 |
if state is None: |
| 601 |
state = {} |
| 602 |
if listitems is not None: |
| 603 |
listitems = list(listitems) |
| 604 |
if dictitems is not None: |
| 605 |
dictitems = dict(dictitems) |
| 606 |
if function.__name__ == "__newobj__": |
| 607 |
function = args[0] |
| 608 |
args = args[1:] |
| 609 |
tag = u"tag:yaml.org,2002:python/object/new:" |
| 610 |
newobj = True |
| 611 |
else: |
| 612 |
tag = u"tag:yaml.org,2002:python/object/apply:" |
| 613 |
newobj = False |
| 614 |
try: |
| 615 |
function_name = u"%s.%s" % (function.__module__, function.__qualname__) |
| 616 |
except AttributeError: |
| 617 |
# probably PY2 |
| 618 |
function_name = u"%s.%s" % (function.__module__, function.__name__) |
| 619 |
if ( |
| 620 |
not args |
| 621 |
and not listitems |
| 622 |
and not dictitems |
| 623 |
and isinstance(state, dict) |
| 624 |
and newobj |
| 625 |
): |
| 626 |
return self.represent_mapping( |
| 627 |
u"tag:yaml.org,2002:python/object:" + function_name, state |
| 628 |
) |
| 629 |
if not listitems and not dictitems and isinstance(state, dict) and not state: |
| 630 |
return self.represent_sequence(tag + function_name, args) |
| 631 |
value = {} |
| 632 |
if args: |
| 633 |
value["args"] = args |
| 634 |
if state or not isinstance(state, dict): |
| 635 |
value["state"] = state |
| 636 |
if listitems: |
| 637 |
value["listitems"] = listitems |
| 638 |
if dictitems: |
| 639 |
value["dictitems"] = dictitems |
| 640 |
return self.represent_mapping(tag + function_name, value) |
| 641 |
|
| 642 |
|
| 643 |
if PY2: |
| 644 |
Representer.add_representer(str, Representer.represent_str) |
| 645 |
|
| 646 |
Representer.add_representer(unicode, Representer.represent_unicode) |
| 647 |
|
| 648 |
Representer.add_representer(long, Representer.represent_long) |
| 649 |
|
| 650 |
Representer.add_representer(complex, Representer.represent_complex) |
| 651 |
|
| 652 |
Representer.add_representer(tuple, Representer.represent_tuple) |
| 653 |
|
| 654 |
Representer.add_representer(type, Representer.represent_name) |
| 655 |
|
| 656 |
if PY2: |
| 657 |
Representer.add_representer(types.ClassType, Representer.represent_name) |
| 658 |
|
| 659 |
Representer.add_representer(types.FunctionType, Representer.represent_name) |
| 660 |
|
| 661 |
Representer.add_representer(types.BuiltinFunctionType, Representer.represent_name) |
| 662 |
|
| 663 |
Representer.add_representer(types.ModuleType, Representer.represent_module) |
| 664 |
|
| 665 |
if PY2: |
| 666 |
Representer.add_multi_representer( |
| 667 |
types.InstanceType, Representer.represent_instance |
| 668 |
) |
| 669 |
|
| 670 |
Representer.add_multi_representer(object, Representer.represent_object) |
| 671 |
|
| 672 |
Representer.add_multi_representer(type, Representer.represent_name) |
| 673 |
|
| 674 |
|
| 675 |
class RoundTripRepresenter(SafeRepresenter): |
| 676 |
# need to add type here and write out the .comment |
| 677 |
# in serializer and emitter |
| 678 |
|
| 679 |
def __init__(self, default_style=None, default_flow_style=None, dumper=None): |
| 680 |
# type: (Any, Any, Any) -> None |
| 681 |
if not hasattr(dumper, "typ") and default_flow_style is None: |
| 682 |
default_flow_style = False |
| 683 |
SafeRepresenter.__init__( |
| 684 |
self, |
| 685 |
default_style=default_style, |
| 686 |
default_flow_style=default_flow_style, |
| 687 |
dumper=dumper, |
| 688 |
) |
| 689 |
|
| 690 |
def ignore_aliases(self, data): |
| 691 |
# type: (Any) -> bool |
| 692 |
try: |
| 693 |
if data.anchor is not None and data.anchor.value is not None: |
| 694 |
return False |
| 695 |
except AttributeError: |
| 696 |
pass |
| 697 |
return SafeRepresenter.ignore_aliases(self, data) |
| 698 |
|
| 699 |
def represent_none(self, data): |
| 700 |
# type: (Any) -> Any |
| 701 |
if ( |
| 702 |
len(self.represented_objects) == 0 |
| 703 |
and not self.serializer.use_explicit_start |
| 704 |
): |
| 705 |
# this will be open ended (although it is not yet) |
| 706 |
return self.represent_scalar(u"tag:yaml.org,2002:null", u"null") |
| 707 |
return self.represent_scalar(u"tag:yaml.org,2002:null", "") |
| 708 |
|
| 709 |
def represent_literal_scalarstring(self, data): |
| 710 |
# type: (Any) -> Any |
| 711 |
tag = None |
| 712 |
style = "|" |
| 713 |
anchor = data.yaml_anchor(any=True) |
| 714 |
if PY2 and not isinstance(data, unicode): |
| 715 |
data = unicode(data, "ascii") |
| 716 |
tag = u"tag:yaml.org,2002:str" |
| 717 |
return self.represent_scalar(tag, data, style=style, anchor=anchor) |
| 718 |
|
| 719 |
represent_preserved_scalarstring = represent_literal_scalarstring |
| 720 |
|
| 721 |
def represent_folded_scalarstring(self, data): |
| 722 |
# type: (Any) -> Any |
| 723 |
tag = None |
| 724 |
style = ">" |
| 725 |
anchor = data.yaml_anchor(any=True) |
| 726 |
for fold_pos in reversed(getattr(data, "fold_pos", [])): |
| 727 |
if ( |
| 728 |
data[fold_pos] == " " |
| 729 |
and (fold_pos > 0 and not data[fold_pos - 1].isspace()) |
| 730 |
and (fold_pos < len(data) and not data[fold_pos + 1].isspace()) |
| 731 |
): |
| 732 |
data = data[:fold_pos] + "\a" + data[fold_pos:] |
| 733 |
if PY2 and not isinstance(data, unicode): |
| 734 |
data = unicode(data, "ascii") |
| 735 |
tag = u"tag:yaml.org,2002:str" |
| 736 |
return self.represent_scalar(tag, data, style=style, anchor=anchor) |
| 737 |
|
| 738 |
def represent_single_quoted_scalarstring(self, data): |
| 739 |
# type: (Any) -> Any |
| 740 |
tag = None |
| 741 |
style = "'" |
| 742 |
anchor = data.yaml_anchor(any=True) |
| 743 |
if PY2 and not isinstance(data, unicode): |
| 744 |
data = unicode(data, "ascii") |
| 745 |
tag = u"tag:yaml.org,2002:str" |
| 746 |
return self.represent_scalar(tag, data, style=style, anchor=anchor) |
| 747 |
|
| 748 |
def represent_double_quoted_scalarstring(self, data): |
| 749 |
# type: (Any) -> Any |
| 750 |
tag = None |
| 751 |
style = '"' |
| 752 |
anchor = data.yaml_anchor(any=True) |
| 753 |
if PY2 and not isinstance(data, unicode): |
| 754 |
data = unicode(data, "ascii") |
| 755 |
tag = u"tag:yaml.org,2002:str" |
| 756 |
return self.represent_scalar(tag, data, style=style, anchor=anchor) |
| 757 |
|
| 758 |
def represent_plain_scalarstring(self, data): |
| 759 |
# type: (Any) -> Any |
| 760 |
tag = None |
| 761 |
style = "" |
| 762 |
anchor = data.yaml_anchor(any=True) |
| 763 |
if PY2 and not isinstance(data, unicode): |
| 764 |
data = unicode(data, "ascii") |
| 765 |
tag = u"tag:yaml.org,2002:str" |
| 766 |
return self.represent_scalar(tag, data, style=style, anchor=anchor) |
| 767 |
|
| 768 |
def insert_underscore(self, prefix, s, underscore, anchor=None): |
| 769 |
# type: (Any, Any, Any, Any) -> Any |
| 770 |
if underscore is None: |
| 771 |
return self.represent_scalar( |
| 772 |
u"tag:yaml.org,2002:int", prefix + s, anchor=anchor |
| 773 |
) |
| 774 |
if underscore[0]: |
| 775 |
sl = list(s) |
| 776 |
pos = len(s) - underscore[0] |
| 777 |
while pos > 0: |
| 778 |
sl.insert(pos, "_") |
| 779 |
pos -= underscore[0] |
| 780 |
s = "".join(sl) |
| 781 |
if underscore[1]: |
| 782 |
s = "_" + s |
| 783 |
if underscore[2]: |
| 784 |
s += "_" |
| 785 |
return self.represent_scalar( |
| 786 |
u"tag:yaml.org,2002:int", prefix + s, anchor=anchor |
| 787 |
) |
| 788 |
|
| 789 |
def represent_scalar_int(self, data): |
| 790 |
# type: (Any) -> Any |
| 791 |
if data._width is not None: |
| 792 |
s = "{:0{}d}".format(data, data._width) |
| 793 |
else: |
| 794 |
s = format(data, "d") |
| 795 |
anchor = data.yaml_anchor(any=True) |
| 796 |
return self.insert_underscore("", s, data._underscore, anchor=anchor) |
| 797 |
|
| 798 |
def represent_binary_int(self, data): |
| 799 |
# type: (Any) -> Any |
| 800 |
if data._width is not None: |
| 801 |
# cannot use '{:#0{}b}', that strips the zeros |
| 802 |
s = "{:0{}b}".format(data, data._width) |
| 803 |
else: |
| 804 |
s = format(data, "b") |
| 805 |
anchor = data.yaml_anchor(any=True) |
| 806 |
return self.insert_underscore("0b", s, data._underscore, anchor=anchor) |
| 807 |
|
| 808 |
def represent_octal_int(self, data): |
| 809 |
# type: (Any) -> Any |
| 810 |
if data._width is not None: |
| 811 |
# cannot use '{:#0{}o}', that strips the zeros |
| 812 |
s = "{:0{}o}".format(data, data._width) |
| 813 |
else: |
| 814 |
s = format(data, "o") |
| 815 |
anchor = data.yaml_anchor(any=True) |
| 816 |
return self.insert_underscore("0o", s, data._underscore, anchor=anchor) |
| 817 |
|
| 818 |
def represent_hex_int(self, data): |
| 819 |
# type: (Any) -> Any |
| 820 |
if data._width is not None: |
| 821 |
# cannot use '{:#0{}x}', that strips the zeros |
| 822 |
s = "{:0{}x}".format(data, data._width) |
| 823 |
else: |
| 824 |
s = format(data, "x") |
| 825 |
anchor = data.yaml_anchor(any=True) |
| 826 |
return self.insert_underscore("0x", s, data._underscore, anchor=anchor) |
| 827 |
|
| 828 |
def represent_hex_caps_int(self, data): |
| 829 |
# type: (Any) -> Any |
| 830 |
if data._width is not None: |
| 831 |
# cannot use '{:#0{}X}', that strips the zeros |
| 832 |
s = "{:0{}X}".format(data, data._width) |
| 833 |
else: |
| 834 |
s = format(data, "X") |
| 835 |
anchor = data.yaml_anchor(any=True) |
| 836 |
return self.insert_underscore("0x", s, data._underscore, anchor=anchor) |
| 837 |
|
| 838 |
def represent_scalar_float(self, data): |
| 839 |
# type: (Any) -> Any |
| 840 |
""" this is way more complicated """ |
| 841 |
value = None |
| 842 |
anchor = data.yaml_anchor(any=True) |
| 843 |
if data != data or (data == 0.0 and data == 1.0): |
| 844 |
value = u".nan" |
| 845 |
elif data == self.inf_value: |
| 846 |
value = u".inf" |
| 847 |
elif data == -self.inf_value: |
| 848 |
value = u"-.inf" |
| 849 |
if value: |
| 850 |
return self.represent_scalar( |
| 851 |
u"tag:yaml.org,2002:float", value, anchor=anchor |
| 852 |
) |
| 853 |
if data._exp is None and data._prec > 0 and data._prec == data._width - 1: |
| 854 |
# no exponent, but trailing dot |
| 855 |
value = u"{}{:d}.".format( |
| 856 |
data._m_sign if data._m_sign else "", abs(int(data)) |
| 857 |
) |
| 858 |
elif data._exp is None: |
| 859 |
# no exponent, "normal" dot |
| 860 |
prec = data._prec |
| 861 |
ms = data._m_sign if data._m_sign else "" |
| 862 |
# -1 for the dot |
| 863 |
value = u"{}{:0{}.{}f}".format( |
| 864 |
ms, abs(data), data._width - len(ms), data._width - prec - 1 |
| 865 |
) |
| 866 |
if prec == 0 or (prec == 1 and ms != ""): |
| 867 |
value = value.replace(u"0.", u".") |
| 868 |
while len(value) < data._width: |
| 869 |
value += u"0" |
| 870 |
else: |
| 871 |
# exponent |
| 872 |
m, es = u"{:{}.{}e}".format( |
| 873 |
# data, data._width, data._width - data._prec + (1 if data._m_sign else 0) |
| 874 |
data, |
| 875 |
data._width, |
| 876 |
data._width + (1 if data._m_sign else 0), |
| 877 |
).split("e") |
| 878 |
w = data._width if data._prec > 0 else (data._width + 1) |
| 879 |
if data < 0: |
| 880 |
w += 1 |
| 881 |
m = m[:w] |
| 882 |
e = int(es) |
| 883 |
m1, m2 = m.split(".") # always second? |
| 884 |
while len(m1) + len(m2) < data._width - (1 if data._prec >= 0 else 0): |
| 885 |
m2 += u"0" |
| 886 |
if data._m_sign and data > 0: |
| 887 |
m1 = "+" + m1 |
| 888 |
esgn = u"+" if data._e_sign else "" |
| 889 |
if data._prec < 0: # mantissa without dot |
| 890 |
if m2 != u"0": |
| 891 |
e -= len(m2) |
| 892 |
else: |
| 893 |
m2 = "" |
| 894 |
while (len(m1) + len(m2) - (1 if data._m_sign else 0)) < data._width: |
| 895 |
m2 += u"0" |
| 896 |
e -= 1 |
| 897 |
value = ( |
| 898 |
m1 + m2 + data._exp + u"{:{}0{}d}".format(e, esgn, data._e_width) |
| 899 |
) |
| 900 |
elif data._prec == 0: # mantissa with trailing dot |
| 901 |
e -= len(m2) |
| 902 |
value = ( |
| 903 |
m1 |
| 904 |
+ m2 |
| 905 |
+ u"." |
| 906 |
+ data._exp |
| 907 |
+ u"{:{}0{}d}".format(e, esgn, data._e_width) |
| 908 |
) |
| 909 |
else: |
| 910 |
if data._m_lead0 > 0: |
| 911 |
m2 = u"0" * (data._m_lead0 - 1) + m1 + m2 |
| 912 |
m1 = u"0" |
| 913 |
m2 = m2[: -data._m_lead0] # these should be zeros |
| 914 |
e += data._m_lead0 |
| 915 |
while len(m1) < data._prec: |
| 916 |
m1 += m2[0] |
| 917 |
m2 = m2[1:] |
| 918 |
e -= 1 |
| 919 |
value = ( |
| 920 |
m1 |
| 921 |
+ u"." |
| 922 |
+ m2 |
| 923 |
+ data._exp |
| 924 |
+ u"{:{}0{}d}".format(e, esgn, data._e_width) |
| 925 |
) |
| 926 |
|
| 927 |
if value is None: |
| 928 |
value = to_unicode(repr(data)).lower() |
| 929 |
return self.represent_scalar(u"tag:yaml.org,2002:float", value, anchor=anchor) |
| 930 |
|
| 931 |
def represent_sequence(self, tag, sequence, flow_style=None): |
| 932 |
# type: (Any, Any, Any) -> Any |
| 933 |
value = [] # type: List[Any] |
| 934 |
# if the flow_style is None, the flow style tacked on to the object |
| 935 |
# explicitly will be taken. If that is None as well the default flow |
| 936 |
# style rules |
| 937 |
try: |
| 938 |
flow_style = sequence.fa.flow_style(flow_style) |
| 939 |
except AttributeError: |
| 940 |
flow_style = flow_style |
| 941 |
try: |
| 942 |
anchor = sequence.yaml_anchor() |
| 943 |
except AttributeError: |
| 944 |
anchor = None |
| 945 |
node = SequenceNode(tag, value, flow_style=flow_style, anchor=anchor) |
| 946 |
if self.alias_key is not None: |
| 947 |
self.represented_objects[self.alias_key] = node |
| 948 |
best_style = True |
| 949 |
try: |
| 950 |
comment = getattr(sequence, comment_attrib) |
| 951 |
node.comment = comment.comment |
| 952 |
# reset any comment already printed information |
| 953 |
if node.comment and node.comment[1]: |
| 954 |
for ct in node.comment[1]: |
| 955 |
ct.reset() |
| 956 |
item_comments = comment.items |
| 957 |
for v in item_comments.values(): |
| 958 |
if v and v[1]: |
| 959 |
for ct in v[1]: |
| 960 |
ct.reset() |
| 961 |
item_comments = comment.items |
| 962 |
node.comment = comment.comment |
| 963 |
try: |
| 964 |
node.comment.append(comment.end) |
| 965 |
except AttributeError: |
| 966 |
pass |
| 967 |
except AttributeError: |
| 968 |
item_comments = {} |
| 969 |
for idx, item in enumerate(sequence): |
| 970 |
node_item = self.represent_data(item) |
| 971 |
self.merge_comments(node_item, item_comments.get(idx)) |
| 972 |
if not (isinstance(node_item, ScalarNode) and not node_item.style): |
| 973 |
best_style = False |
| 974 |
value.append(node_item) |
| 975 |
if flow_style is None: |
| 976 |
if len(sequence) != 0 and self.default_flow_style is not None: |
| 977 |
node.flow_style = self.default_flow_style |
| 978 |
else: |
| 979 |
node.flow_style = best_style |
| 980 |
return node |
| 981 |
|
| 982 |
def merge_comments(self, node, comments): |
| 983 |
# type: (Any, Any) -> Any |
| 984 |
if comments is None: |
| 985 |
assert hasattr(node, "comment") |
| 986 |
return node |
| 987 |
if getattr(node, "comment", None) is not None: |
| 988 |
for idx, val in enumerate(comments): |
| 989 |
if idx >= len(node.comment): |
| 990 |
continue |
| 991 |
nc = node.comment[idx] |
| 992 |
if nc is not None: |
| 993 |
assert val is None or val == nc |
| 994 |
comments[idx] = nc |
| 995 |
node.comment = comments |
| 996 |
return node |
| 997 |
|
| 998 |
def represent_key(self, data): |
| 999 |
# type: (Any) -> Any |
| 1000 |
if isinstance(data, CommentedKeySeq): |
| 1001 |
self.alias_key = None |
| 1002 |
return self.represent_sequence( |
| 1003 |
u"tag:yaml.org,2002:seq", data, flow_style=True |
| 1004 |
) |
| 1005 |
if isinstance(data, CommentedKeyMap): |
| 1006 |
self.alias_key = None |
| 1007 |
return self.represent_mapping( |
| 1008 |
u"tag:yaml.org,2002:map", data, flow_style=True |
| 1009 |
) |
| 1010 |
return SafeRepresenter.represent_key(self, data) |
| 1011 |
|
| 1012 |
def represent_mapping(self, tag, mapping, flow_style=None): |
| 1013 |
# type: (Any, Any, Any) -> Any |
| 1014 |
value = [] # type: List[Any] |
| 1015 |
try: |
| 1016 |
flow_style = mapping.fa.flow_style(flow_style) |
| 1017 |
except AttributeError: |
| 1018 |
flow_style = flow_style |
| 1019 |
try: |
| 1020 |
anchor = mapping.yaml_anchor() |
| 1021 |
except AttributeError: |
| 1022 |
anchor = None |
| 1023 |
node = MappingNode(tag, value, flow_style=flow_style, anchor=anchor) |
| 1024 |
if self.alias_key is not None: |
| 1025 |
self.represented_objects[self.alias_key] = node |
| 1026 |
best_style = True |
| 1027 |
# no sorting! !! |
| 1028 |
try: |
| 1029 |
comment = getattr(mapping, comment_attrib) |
| 1030 |
node.comment = comment.comment |
| 1031 |
if node.comment and node.comment[1]: |
| 1032 |
for ct in node.comment[1]: |
| 1033 |
ct.reset() |
| 1034 |
item_comments = comment.items |
| 1035 |
for v in item_comments.values(): |
| 1036 |
if v and v[1]: |
| 1037 |
for ct in v[1]: |
| 1038 |
ct.reset() |
| 1039 |
try: |
| 1040 |
node.comment.append(comment.end) |
| 1041 |
except AttributeError: |
| 1042 |
pass |
| 1043 |
except AttributeError: |
| 1044 |
item_comments = {} |
| 1045 |
merge_list = [m[1] for m in getattr(mapping, merge_attrib, [])] |
| 1046 |
try: |
| 1047 |
merge_pos = getattr(mapping, merge_attrib, [[0]])[0][0] |
| 1048 |
except IndexError: |
| 1049 |
merge_pos = 0 |
| 1050 |
item_count = 0 |
| 1051 |
if bool(merge_list): |
| 1052 |
items = mapping.non_merged_items() |
| 1053 |
else: |
| 1054 |
items = mapping.items() |
| 1055 |
for item_key, item_value in items: |
| 1056 |
item_count += 1 |
| 1057 |
node_key = self.represent_key(item_key) |
| 1058 |
node_value = self.represent_data(item_value) |
| 1059 |
item_comment = item_comments.get(item_key) |
| 1060 |
if item_comment: |
| 1061 |
assert getattr(node_key, "comment", None) is None |
| 1062 |
node_key.comment = item_comment[:2] |
| 1063 |
nvc = getattr(node_value, "comment", None) |
| 1064 |
if nvc is not None: # end comment already there |
| 1065 |
nvc[0] = item_comment[2] |
| 1066 |
nvc[1] = item_comment[3] |
| 1067 |
else: |
| 1068 |
node_value.comment = item_comment[2:] |
| 1069 |
if not (isinstance(node_key, ScalarNode) and not node_key.style): |
| 1070 |
best_style = False |
| 1071 |
if not (isinstance(node_value, ScalarNode) and not node_value.style): |
| 1072 |
best_style = False |
| 1073 |
value.append((node_key, node_value)) |
| 1074 |
if flow_style is None: |
| 1075 |
if ( |
| 1076 |
(item_count != 0) or bool(merge_list) |
| 1077 |
) and self.default_flow_style is not None: |
| 1078 |
node.flow_style = self.default_flow_style |
| 1079 |
else: |
| 1080 |
node.flow_style = best_style |
| 1081 |
if bool(merge_list): |
| 1082 |
# because of the call to represent_data here, the anchors |
| 1083 |
# are marked as being used and thereby created |
| 1084 |
if len(merge_list) == 1: |
| 1085 |
arg = self.represent_data(merge_list[0]) |
| 1086 |
else: |
| 1087 |
arg = self.represent_data(merge_list) |
| 1088 |
arg.flow_style = True |
| 1089 |
value.insert(merge_pos, (ScalarNode(u"tag:yaml.org,2002:merge", "<<"), arg)) |
| 1090 |
return node |
| 1091 |
|
| 1092 |
def represent_omap(self, tag, omap, flow_style=None): |
| 1093 |
# type: (Any, Any, Any) -> Any |
| 1094 |
value = [] # type: List[Any] |
| 1095 |
try: |
| 1096 |
flow_style = omap.fa.flow_style(flow_style) |
| 1097 |
except AttributeError: |
| 1098 |
flow_style = flow_style |
| 1099 |
try: |
| 1100 |
anchor = omap.yaml_anchor() |
| 1101 |
except AttributeError: |
| 1102 |
anchor = None |
| 1103 |
node = SequenceNode(tag, value, flow_style=flow_style, anchor=anchor) |
| 1104 |
if self.alias_key is not None: |
| 1105 |
self.represented_objects[self.alias_key] = node |
| 1106 |
best_style = True |
| 1107 |
try: |
| 1108 |
comment = getattr(omap, comment_attrib) |
| 1109 |
node.comment = comment.comment |
| 1110 |
if node.comment and node.comment[1]: |
| 1111 |
for ct in node.comment[1]: |
| 1112 |
ct.reset() |
| 1113 |
item_comments = comment.items |
| 1114 |
for v in item_comments.values(): |
| 1115 |
if v and v[1]: |
| 1116 |
for ct in v[1]: |
| 1117 |
ct.reset() |
| 1118 |
try: |
| 1119 |
node.comment.append(comment.end) |
| 1120 |
except AttributeError: |
| 1121 |
pass |
| 1122 |
except AttributeError: |
| 1123 |
item_comments = {} |
| 1124 |
for item_key in omap: |
| 1125 |
item_val = omap[item_key] |
| 1126 |
node_item = self.represent_data({item_key: item_val}) |
| 1127 |
# node_item.flow_style = False |
| 1128 |
# node item has two scalars in value: node_key and node_value |
| 1129 |
item_comment = item_comments.get(item_key) |
| 1130 |
if item_comment: |
| 1131 |
if item_comment[1]: |
| 1132 |
node_item.comment = [None, item_comment[1]] |
| 1133 |
assert getattr(node_item.value[0][0], "comment", None) is None |
| 1134 |
node_item.value[0][0].comment = [item_comment[0], None] |
| 1135 |
nvc = getattr(node_item.value[0][1], "comment", None) |
| 1136 |
if nvc is not None: # end comment already there |
| 1137 |
nvc[0] = item_comment[2] |
| 1138 |
nvc[1] = item_comment[3] |
| 1139 |
else: |
| 1140 |
node_item.value[0][1].comment = item_comment[2:] |
| 1141 |
# if not (isinstance(node_item, ScalarNode) \ |
| 1142 |
# and not node_item.style): |
| 1143 |
# best_style = False |
| 1144 |
value.append(node_item) |
| 1145 |
if flow_style is None: |
| 1146 |
if self.default_flow_style is not None: |
| 1147 |
node.flow_style = self.default_flow_style |
| 1148 |
else: |
| 1149 |
node.flow_style = best_style |
| 1150 |
return node |
| 1151 |
|
| 1152 |
def represent_set(self, setting): |
| 1153 |
# type: (Any) -> Any |
| 1154 |
flow_style = False |
| 1155 |
tag = u"tag:yaml.org,2002:set" |
| 1156 |
# return self.represent_mapping(tag, value) |
| 1157 |
value = [] # type: List[Any] |
| 1158 |
flow_style = setting.fa.flow_style(flow_style) |
| 1159 |
try: |
| 1160 |
anchor = setting.yaml_anchor() |
| 1161 |
except AttributeError: |
| 1162 |
anchor = None |
| 1163 |
node = MappingNode(tag, value, flow_style=flow_style, anchor=anchor) |
| 1164 |
if self.alias_key is not None: |
| 1165 |
self.represented_objects[self.alias_key] = node |
| 1166 |
best_style = True |
| 1167 |
# no sorting! !! |
| 1168 |
try: |
| 1169 |
comment = getattr(setting, comment_attrib) |
| 1170 |
node.comment = comment.comment |
| 1171 |
if node.comment and node.comment[1]: |
| 1172 |
for ct in node.comment[1]: |
| 1173 |
ct.reset() |
| 1174 |
item_comments = comment.items |
| 1175 |
for v in item_comments.values(): |
| 1176 |
if v and v[1]: |
| 1177 |
for ct in v[1]: |
| 1178 |
ct.reset() |
| 1179 |
try: |
| 1180 |
node.comment.append(comment.end) |
| 1181 |
except AttributeError: |
| 1182 |
pass |
| 1183 |
except AttributeError: |
| 1184 |
item_comments = {} |
| 1185 |
for item_key in setting.odict: |
| 1186 |
node_key = self.represent_key(item_key) |
| 1187 |
node_value = self.represent_data(None) |
| 1188 |
item_comment = item_comments.get(item_key) |
| 1189 |
if item_comment: |
| 1190 |
assert getattr(node_key, "comment", None) is None |
| 1191 |
node_key.comment = item_comment[:2] |
| 1192 |
node_key.style = node_value.style = "?" |
| 1193 |
if not (isinstance(node_key, ScalarNode) and not node_key.style): |
| 1194 |
best_style = False |
| 1195 |
if not (isinstance(node_value, ScalarNode) and not node_value.style): |
| 1196 |
best_style = False |
| 1197 |
value.append((node_key, node_value)) |
| 1198 |
best_style = best_style |
| 1199 |
return node |
| 1200 |
|
| 1201 |
def represent_dict(self, data): |
| 1202 |
# type: (Any) -> Any |
| 1203 |
"""write out tag if saved on loading""" |
| 1204 |
try: |
| 1205 |
t = data.tag.value |
| 1206 |
except AttributeError: |
| 1207 |
t = None |
| 1208 |
if t: |
| 1209 |
if t.startswith("!!"): |
| 1210 |
tag = "tag:yaml.org,2002:" + t[2:] |
| 1211 |
else: |
| 1212 |
tag = t |
| 1213 |
else: |
| 1214 |
tag = u"tag:yaml.org,2002:map" |
| 1215 |
return self.represent_mapping(tag, data) |
| 1216 |
|
| 1217 |
def represent_list(self, data): |
| 1218 |
# type: (Any) -> Any |
| 1219 |
try: |
| 1220 |
t = data.tag.value |
| 1221 |
except AttributeError: |
| 1222 |
t = None |
| 1223 |
if t: |
| 1224 |
if t.startswith("!!"): |
| 1225 |
tag = "tag:yaml.org,2002:" + t[2:] |
| 1226 |
else: |
| 1227 |
tag = t |
| 1228 |
else: |
| 1229 |
tag = u"tag:yaml.org,2002:seq" |
| 1230 |
return self.represent_sequence(tag, data) |
| 1231 |
|
| 1232 |
def represent_datetime(self, data): |
| 1233 |
# type: (Any) -> Any |
| 1234 |
inter = "T" if data._yaml["t"] else " " |
| 1235 |
_yaml = data._yaml |
| 1236 |
if _yaml["delta"]: |
| 1237 |
data += _yaml["delta"] |
| 1238 |
value = data.isoformat(inter) |
| 1239 |
else: |
| 1240 |
value = data.isoformat(inter) |
| 1241 |
if _yaml["tz"]: |
| 1242 |
value += _yaml["tz"] |
| 1243 |
return self.represent_scalar(u"tag:yaml.org,2002:timestamp", to_unicode(value)) |
| 1244 |
|
| 1245 |
def represent_tagged_scalar(self, data): |
| 1246 |
# type: (Any) -> Any |
| 1247 |
try: |
| 1248 |
tag = data.tag.value |
| 1249 |
except AttributeError: |
| 1250 |
tag = None |
| 1251 |
try: |
| 1252 |
anchor = data.yaml_anchor() |
| 1253 |
except AttributeError: |
| 1254 |
anchor = None |
| 1255 |
return self.represent_scalar(tag, data.value, style=data.style, anchor=anchor) |
| 1256 |
|
| 1257 |
def represent_scalar_bool(self, data): |
| 1258 |
# type: (Any) -> Any |
| 1259 |
try: |
| 1260 |
anchor = data.yaml_anchor() |
| 1261 |
except AttributeError: |
| 1262 |
anchor = None |
| 1263 |
return SafeRepresenter.represent_bool(self, data, anchor=anchor) |
| 1264 |
|
| 1265 |
|
| 1266 |
RoundTripRepresenter.add_representer(type(None), RoundTripRepresenter.represent_none) |
| 1267 |
|
| 1268 |
RoundTripRepresenter.add_representer( |
| 1269 |
LiteralScalarString, RoundTripRepresenter.represent_literal_scalarstring |
| 1270 |
) |
| 1271 |
|
| 1272 |
RoundTripRepresenter.add_representer( |
| 1273 |
FoldedScalarString, RoundTripRepresenter.represent_folded_scalarstring |
| 1274 |
) |
| 1275 |
|
| 1276 |
RoundTripRepresenter.add_representer( |
| 1277 |
SingleQuotedScalarString, RoundTripRepresenter.represent_single_quoted_scalarstring |
| 1278 |
) |
| 1279 |
|
| 1280 |
RoundTripRepresenter.add_representer( |
| 1281 |
DoubleQuotedScalarString, RoundTripRepresenter.represent_double_quoted_scalarstring |
| 1282 |
) |
| 1283 |
|
| 1284 |
RoundTripRepresenter.add_representer( |
| 1285 |
PlainScalarString, RoundTripRepresenter.represent_plain_scalarstring |
| 1286 |
) |
| 1287 |
|
| 1288 |
# RoundTripRepresenter.add_representer(tuple, Representer.represent_tuple) |
| 1289 |
|
| 1290 |
RoundTripRepresenter.add_representer( |
| 1291 |
ScalarInt, RoundTripRepresenter.represent_scalar_int |
| 1292 |
) |
| 1293 |
|
| 1294 |
RoundTripRepresenter.add_representer( |
| 1295 |
BinaryInt, RoundTripRepresenter.represent_binary_int |
| 1296 |
) |
| 1297 |
|
| 1298 |
RoundTripRepresenter.add_representer(OctalInt, RoundTripRepresenter.represent_octal_int) |
| 1299 |
|
| 1300 |
RoundTripRepresenter.add_representer(HexInt, RoundTripRepresenter.represent_hex_int) |
| 1301 |
|
| 1302 |
RoundTripRepresenter.add_representer( |
| 1303 |
HexCapsInt, RoundTripRepresenter.represent_hex_caps_int |
| 1304 |
) |
| 1305 |
|
| 1306 |
RoundTripRepresenter.add_representer( |
| 1307 |
ScalarFloat, RoundTripRepresenter.represent_scalar_float |
| 1308 |
) |
| 1309 |
|
| 1310 |
RoundTripRepresenter.add_representer( |
| 1311 |
ScalarBoolean, RoundTripRepresenter.represent_scalar_bool |
| 1312 |
) |
| 1313 |
|
| 1314 |
RoundTripRepresenter.add_representer(CommentedSeq, RoundTripRepresenter.represent_list) |
| 1315 |
|
| 1316 |
RoundTripRepresenter.add_representer(CommentedMap, RoundTripRepresenter.represent_dict) |
| 1317 |
|
| 1318 |
RoundTripRepresenter.add_representer( |
| 1319 |
CommentedOrderedMap, RoundTripRepresenter.represent_ordereddict |
| 1320 |
) |
| 1321 |
|
| 1322 |
if sys.version_info >= (2, 7): |
| 1323 |
import collections |
| 1324 |
|
| 1325 |
RoundTripRepresenter.add_representer( |
| 1326 |
collections.OrderedDict, RoundTripRepresenter.represent_ordereddict |
| 1327 |
) |
| 1328 |
|
| 1329 |
RoundTripRepresenter.add_representer(CommentedSet, RoundTripRepresenter.represent_set) |
| 1330 |
|
| 1331 |
RoundTripRepresenter.add_representer( |
| 1332 |
TaggedScalar, RoundTripRepresenter.represent_tagged_scalar |
| 1333 |
) |
| 1334 |
|
| 1335 |
RoundTripRepresenter.add_representer(TimeStamp, RoundTripRepresenter.represent_datetime) |