| 1 |
# coding: utf-8 |
| 2 |
|
| 3 |
from __future__ import absolute_import |
| 4 |
|
| 5 |
import re |
| 6 |
|
| 7 |
if False: # MYPY |
| 8 |
from typing import Any, Dict, List, Union, Text, Optional # NOQA |
| 9 |
from strictyaml.ruamel.compat import VersionType # NOQA |
| 10 |
|
| 11 |
from strictyaml.ruamel.compat import string_types, _DEFAULT_YAML_VERSION # NOQA |
| 12 |
from strictyaml.ruamel.error import * # NOQA |
| 13 |
from strictyaml.ruamel.nodes import MappingNode, ScalarNode, SequenceNode # NOQA |
| 14 |
from strictyaml.ruamel.util import RegExp # NOQA |
| 15 |
|
| 16 |
__all__ = ["BaseResolver", "Resolver", "VersionedResolver"] |
| 17 |
|
| 18 |
|
| 19 |
# fmt: off |
| 20 |
# resolvers consist of |
| 21 |
# - a list of applicable version |
| 22 |
# - a tag |
| 23 |
# - a regexp |
| 24 |
# - a list of first characters to match |
| 25 |
implicit_resolvers = [ |
| 26 |
([(1, 2)], |
| 27 |
u'tag:yaml.org,2002:bool', |
| 28 |
RegExp(u'''^(?:true|True|TRUE|false|False|FALSE)$''', re.X), |
| 29 |
list(u'tTfF')), |
| 30 |
([(1, 1)], |
| 31 |
u'tag:yaml.org,2002:bool', |
| 32 |
RegExp(u'''^(?:y|Y|yes|Yes|YES|n|N|no|No|NO |
| 33 |
|true|True|TRUE|false|False|FALSE |
| 34 |
|on|On|ON|off|Off|OFF)$''', re.X), |
| 35 |
list(u'yYnNtTfFoO')), |
| 36 |
([(1, 2)], |
| 37 |
u'tag:yaml.org,2002:float', |
| 38 |
RegExp(u'''^(?: |
| 39 |
[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |
| 40 |
|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |
| 41 |
|[-+]?\\.[0-9_]+(?:[eE][-+][0-9]+)? |
| 42 |
|[-+]?\\.(?:inf|Inf|INF) |
| 43 |
|\\.(?:nan|NaN|NAN))$''', re.X), |
| 44 |
list(u'-+0123456789.')), |
| 45 |
([(1, 1)], |
| 46 |
u'tag:yaml.org,2002:float', |
| 47 |
RegExp(u'''^(?: |
| 48 |
[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |
| 49 |
|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |
| 50 |
|\\.[0-9_]+(?:[eE][-+][0-9]+)? |
| 51 |
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]* # sexagesimal float |
| 52 |
|[-+]?\\.(?:inf|Inf|INF) |
| 53 |
|\\.(?:nan|NaN|NAN))$''', re.X), |
| 54 |
list(u'-+0123456789.')), |
| 55 |
([(1, 2)], |
| 56 |
u'tag:yaml.org,2002:int', |
| 57 |
RegExp(u'''^(?:[-+]?0b[0-1_]+ |
| 58 |
|[-+]?0o?[0-7_]+ |
| 59 |
|[-+]?[0-9_]+ |
| 60 |
|[-+]?0x[0-9a-fA-F_]+)$''', re.X), |
| 61 |
list(u'-+0123456789')), |
| 62 |
([(1, 1)], |
| 63 |
u'tag:yaml.org,2002:int', |
| 64 |
RegExp(u'''^(?:[-+]?0b[0-1_]+ |
| 65 |
|[-+]?0?[0-7_]+ |
| 66 |
|[-+]?(?:0|[1-9][0-9_]*) |
| 67 |
|[-+]?0x[0-9a-fA-F_]+ |
| 68 |
|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), # sexagesimal int |
| 69 |
list(u'-+0123456789')), |
| 70 |
([(1, 2), (1, 1)], |
| 71 |
u'tag:yaml.org,2002:merge', |
| 72 |
RegExp(u'^(?:<<)$'), |
| 73 |
[u'<']), |
| 74 |
([(1, 2), (1, 1)], |
| 75 |
u'tag:yaml.org,2002:null', |
| 76 |
RegExp(u'''^(?: ~ |
| 77 |
|null|Null|NULL |
| 78 |
| )$''', re.X), |
| 79 |
[u'~', u'n', u'N', u'']), |
| 80 |
([(1, 2), (1, 1)], |
| 81 |
u'tag:yaml.org,2002:timestamp', |
| 82 |
RegExp(u'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] |
| 83 |
|[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? |
| 84 |
(?:[Tt]|[ \\t]+)[0-9][0-9]? |
| 85 |
:[0-9][0-9] :[0-9][0-9] (?:\\.[0-9]*)? |
| 86 |
(?:[ \\t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), |
| 87 |
list(u'0123456789')), |
| 88 |
([(1, 2), (1, 1)], |
| 89 |
u'tag:yaml.org,2002:value', |
| 90 |
RegExp(u'^(?:=)$'), |
| 91 |
[u'=']), |
| 92 |
# The following resolver is only for documentation purposes. It cannot work |
| 93 |
# because plain scalars cannot start with '!', '&', or '*'. |
| 94 |
([(1, 2), (1, 1)], |
| 95 |
u'tag:yaml.org,2002:yaml', |
| 96 |
RegExp(u'^(?:!|&|\\*)$'), |
| 97 |
list(u'!&*')), |
| 98 |
] |
| 99 |
# fmt: on |
| 100 |
|
| 101 |
|
| 102 |
class ResolverError(YAMLError): |
| 103 |
pass |
| 104 |
|
| 105 |
|
| 106 |
class BaseResolver(object): |
| 107 |
|
| 108 |
DEFAULT_SCALAR_TAG = u"tag:yaml.org,2002:str" |
| 109 |
DEFAULT_SEQUENCE_TAG = u"tag:yaml.org,2002:seq" |
| 110 |
DEFAULT_MAPPING_TAG = u"tag:yaml.org,2002:map" |
| 111 |
|
| 112 |
yaml_implicit_resolvers = {} # type: Dict[Any, Any] |
| 113 |
yaml_path_resolvers = {} # type: Dict[Any, Any] |
| 114 |
|
| 115 |
def __init__(self, loadumper=None): |
| 116 |
# type: (Any, Any) -> None |
| 117 |
self.loadumper = loadumper |
| 118 |
if ( |
| 119 |
self.loadumper is not None |
| 120 |
and getattr(self.loadumper, "_resolver", None) is None |
| 121 |
): |
| 122 |
self.loadumper._resolver = self.loadumper |
| 123 |
self._loader_version = None # type: Any |
| 124 |
self.resolver_exact_paths = [] # type: List[Any] |
| 125 |
self.resolver_prefix_paths = [] # type: List[Any] |
| 126 |
|
| 127 |
@property |
| 128 |
def parser(self): |
| 129 |
# type: () -> Any |
| 130 |
if self.loadumper is not None: |
| 131 |
if hasattr(self.loadumper, "typ"): |
| 132 |
return self.loadumper.parser |
| 133 |
return self.loadumper._parser |
| 134 |
return None |
| 135 |
|
| 136 |
@classmethod |
| 137 |
def add_implicit_resolver_base(cls, tag, regexp, first): |
| 138 |
# type: (Any, Any, Any) -> None |
| 139 |
if "yaml_implicit_resolvers" not in cls.__dict__: |
| 140 |
# deepcopy doesn't work here |
| 141 |
cls.yaml_implicit_resolvers = dict( |
| 142 |
(k, cls.yaml_implicit_resolvers[k][:]) |
| 143 |
for k in cls.yaml_implicit_resolvers |
| 144 |
) |
| 145 |
if first is None: |
| 146 |
first = [None] |
| 147 |
for ch in first: |
| 148 |
cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp)) |
| 149 |
|
| 150 |
@classmethod |
| 151 |
def add_implicit_resolver(cls, tag, regexp, first): |
| 152 |
# type: (Any, Any, Any) -> None |
| 153 |
if "yaml_implicit_resolvers" not in cls.__dict__: |
| 154 |
# deepcopy doesn't work here |
| 155 |
cls.yaml_implicit_resolvers = dict( |
| 156 |
(k, cls.yaml_implicit_resolvers[k][:]) |
| 157 |
for k in cls.yaml_implicit_resolvers |
| 158 |
) |
| 159 |
if first is None: |
| 160 |
first = [None] |
| 161 |
for ch in first: |
| 162 |
cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp)) |
| 163 |
implicit_resolvers.append(([(1, 2), (1, 1)], tag, regexp, first)) |
| 164 |
|
| 165 |
# @classmethod |
| 166 |
# def add_implicit_resolver(cls, tag, regexp, first): |
| 167 |
|
| 168 |
@classmethod |
| 169 |
def add_path_resolver(cls, tag, path, kind=None): |
| 170 |
# type: (Any, Any, Any) -> None |
| 171 |
# Note: `add_path_resolver` is experimental. The API could be changed. |
| 172 |
# `new_path` is a pattern that is matched against the path from the |
| 173 |
# root to the node that is being considered. `node_path` elements are |
| 174 |
# tuples `(node_check, index_check)`. `node_check` is a node class: |
| 175 |
# `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None` |
| 176 |
# matches any kind of a node. `index_check` could be `None`, a boolean |
| 177 |
# value, a string value, or a number. `None` and `False` match against |
| 178 |
# any _value_ of sequence and mapping nodes. `True` matches against |
| 179 |
# any _key_ of a mapping node. A string `index_check` matches against |
| 180 |
# a mapping value that corresponds to a scalar key which content is |
| 181 |
# equal to the `index_check` value. An integer `index_check` matches |
| 182 |
# against a sequence value with the index equal to `index_check`. |
| 183 |
if "yaml_path_resolvers" not in cls.__dict__: |
| 184 |
cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy() |
| 185 |
new_path = [] # type: List[Any] |
| 186 |
for element in path: |
| 187 |
if isinstance(element, (list, tuple)): |
| 188 |
if len(element) == 2: |
| 189 |
node_check, index_check = element |
| 190 |
elif len(element) == 1: |
| 191 |
node_check = element[0] |
| 192 |
index_check = True |
| 193 |
else: |
| 194 |
raise ResolverError("Invalid path element: %s" % (element,)) |
| 195 |
else: |
| 196 |
node_check = None |
| 197 |
index_check = element |
| 198 |
if node_check is str: |
| 199 |
node_check = ScalarNode |
| 200 |
elif node_check is list: |
| 201 |
node_check = SequenceNode |
| 202 |
elif node_check is dict: |
| 203 |
node_check = MappingNode |
| 204 |
elif ( |
| 205 |
node_check not in [ScalarNode, SequenceNode, MappingNode] |
| 206 |
and not isinstance(node_check, string_types) |
| 207 |
and node_check is not None |
| 208 |
): |
| 209 |
raise ResolverError("Invalid node checker: %s" % (node_check,)) |
| 210 |
if ( |
| 211 |
not isinstance(index_check, (string_types, int)) |
| 212 |
and index_check is not None |
| 213 |
): |
| 214 |
raise ResolverError("Invalid index checker: %s" % (index_check,)) |
| 215 |
new_path.append((node_check, index_check)) |
| 216 |
if kind is str: |
| 217 |
kind = ScalarNode |
| 218 |
elif kind is list: |
| 219 |
kind = SequenceNode |
| 220 |
elif kind is dict: |
| 221 |
kind = MappingNode |
| 222 |
elif kind not in [ScalarNode, SequenceNode, MappingNode] and kind is not None: |
| 223 |
raise ResolverError("Invalid node kind: %s" % (kind,)) |
| 224 |
cls.yaml_path_resolvers[tuple(new_path), kind] = tag |
| 225 |
|
| 226 |
def descend_resolver(self, current_node, current_index): |
| 227 |
# type: (Any, Any) -> None |
| 228 |
if not self.yaml_path_resolvers: |
| 229 |
return |
| 230 |
exact_paths = {} |
| 231 |
prefix_paths = [] |
| 232 |
if current_node: |
| 233 |
depth = len(self.resolver_prefix_paths) |
| 234 |
for path, kind in self.resolver_prefix_paths[-1]: |
| 235 |
if self.check_resolver_prefix( |
| 236 |
depth, path, kind, current_node, current_index |
| 237 |
): |
| 238 |
if len(path) > depth: |
| 239 |
prefix_paths.append((path, kind)) |
| 240 |
else: |
| 241 |
exact_paths[kind] = self.yaml_path_resolvers[path, kind] |
| 242 |
else: |
| 243 |
for path, kind in self.yaml_path_resolvers: |
| 244 |
if not path: |
| 245 |
exact_paths[kind] = self.yaml_path_resolvers[path, kind] |
| 246 |
else: |
| 247 |
prefix_paths.append((path, kind)) |
| 248 |
self.resolver_exact_paths.append(exact_paths) |
| 249 |
self.resolver_prefix_paths.append(prefix_paths) |
| 250 |
|
| 251 |
def ascend_resolver(self): |
| 252 |
# type: () -> None |
| 253 |
if not self.yaml_path_resolvers: |
| 254 |
return |
| 255 |
self.resolver_exact_paths.pop() |
| 256 |
self.resolver_prefix_paths.pop() |
| 257 |
|
| 258 |
def check_resolver_prefix(self, depth, path, kind, current_node, current_index): |
| 259 |
# type: (int, Text, Any, Any, Any) -> bool |
| 260 |
node_check, index_check = path[depth - 1] |
| 261 |
if isinstance(node_check, string_types): |
| 262 |
if current_node.tag != node_check: |
| 263 |
return False |
| 264 |
elif node_check is not None: |
| 265 |
if not isinstance(current_node, node_check): |
| 266 |
return False |
| 267 |
if index_check is True and current_index is not None: |
| 268 |
return False |
| 269 |
if (index_check is False or index_check is None) and current_index is None: |
| 270 |
return False |
| 271 |
if isinstance(index_check, string_types): |
| 272 |
if not ( |
| 273 |
isinstance(current_index, ScalarNode) |
| 274 |
and index_check == current_index.value |
| 275 |
): |
| 276 |
return False |
| 277 |
elif isinstance(index_check, int) and not isinstance(index_check, bool): |
| 278 |
if index_check != current_index: |
| 279 |
return False |
| 280 |
return True |
| 281 |
|
| 282 |
def resolve(self, kind, value, implicit): |
| 283 |
# type: (Any, Any, Any) -> Any |
| 284 |
if kind is ScalarNode and implicit[0]: |
| 285 |
if value == "": |
| 286 |
resolvers = self.yaml_implicit_resolvers.get("", []) |
| 287 |
else: |
| 288 |
resolvers = self.yaml_implicit_resolvers.get(value[0], []) |
| 289 |
resolvers += self.yaml_implicit_resolvers.get(None, []) |
| 290 |
for tag, regexp in resolvers: |
| 291 |
if regexp.match(value): |
| 292 |
return tag |
| 293 |
implicit = implicit[1] |
| 294 |
if bool(self.yaml_path_resolvers): |
| 295 |
exact_paths = self.resolver_exact_paths[-1] |
| 296 |
if kind in exact_paths: |
| 297 |
return exact_paths[kind] |
| 298 |
if None in exact_paths: |
| 299 |
return exact_paths[None] |
| 300 |
if kind is ScalarNode: |
| 301 |
return self.DEFAULT_SCALAR_TAG |
| 302 |
elif kind is SequenceNode: |
| 303 |
return self.DEFAULT_SEQUENCE_TAG |
| 304 |
elif kind is MappingNode: |
| 305 |
return self.DEFAULT_MAPPING_TAG |
| 306 |
|
| 307 |
@property |
| 308 |
def processing_version(self): |
| 309 |
# type: () -> Any |
| 310 |
return None |
| 311 |
|
| 312 |
|
| 313 |
class Resolver(BaseResolver): |
| 314 |
pass |
| 315 |
|
| 316 |
|
| 317 |
for ir in implicit_resolvers: |
| 318 |
if (1, 2) in ir[0]: |
| 319 |
Resolver.add_implicit_resolver_base(*ir[1:]) |
| 320 |
|
| 321 |
|
| 322 |
class VersionedResolver(BaseResolver): |
| 323 |
""" |
| 324 |
contrary to the "normal" resolver, the smart resolver delays loading |
| 325 |
the pattern matching rules. That way it can decide to load 1.1 rules |
| 326 |
or the (default) 1.2 rules, that no longer support octal without 0o, sexagesimals |
| 327 |
and Yes/No/On/Off booleans. |
| 328 |
""" |
| 329 |
|
| 330 |
def __init__(self, version=None, loader=None, loadumper=None): |
| 331 |
# type: (Optional[VersionType], Any, Any) -> None |
| 332 |
if loader is None and loadumper is not None: |
| 333 |
loader = loadumper |
| 334 |
BaseResolver.__init__(self, loader) |
| 335 |
self._loader_version = self.get_loader_version(version) |
| 336 |
self._version_implicit_resolver = {} # type: Dict[Any, Any] |
| 337 |
|
| 338 |
def add_version_implicit_resolver(self, version, tag, regexp, first): |
| 339 |
# type: (VersionType, Any, Any, Any) -> None |
| 340 |
if first is None: |
| 341 |
first = [None] |
| 342 |
impl_resolver = self._version_implicit_resolver.setdefault(version, {}) |
| 343 |
for ch in first: |
| 344 |
impl_resolver.setdefault(ch, []).append((tag, regexp)) |
| 345 |
|
| 346 |
def get_loader_version(self, version): |
| 347 |
# type: (Optional[VersionType]) -> Any |
| 348 |
if version is None or isinstance(version, tuple): |
| 349 |
return version |
| 350 |
if isinstance(version, list): |
| 351 |
return tuple(version) |
| 352 |
# assume string |
| 353 |
return tuple(map(int, version.split(u"."))) |
| 354 |
|
| 355 |
@property |
| 356 |
def versioned_resolver(self): |
| 357 |
# type: () -> Any |
| 358 |
""" |
| 359 |
select the resolver based on the version we are parsing |
| 360 |
""" |
| 361 |
version = self.processing_version |
| 362 |
if version not in self._version_implicit_resolver: |
| 363 |
for x in implicit_resolvers: |
| 364 |
if version in x[0]: |
| 365 |
self.add_version_implicit_resolver(version, x[1], x[2], x[3]) |
| 366 |
return self._version_implicit_resolver[version] |
| 367 |
|
| 368 |
def resolve(self, kind, value, implicit): |
| 369 |
# type: (Any, Any, Any) -> Any |
| 370 |
if kind is ScalarNode and implicit[0]: |
| 371 |
if value == "": |
| 372 |
resolvers = self.versioned_resolver.get("", []) |
| 373 |
else: |
| 374 |
resolvers = self.versioned_resolver.get(value[0], []) |
| 375 |
resolvers += self.versioned_resolver.get(None, []) |
| 376 |
for tag, regexp in resolvers: |
| 377 |
if regexp.match(value): |
| 378 |
return tag |
| 379 |
implicit = implicit[1] |
| 380 |
if bool(self.yaml_path_resolvers): |
| 381 |
exact_paths = self.resolver_exact_paths[-1] |
| 382 |
if kind in exact_paths: |
| 383 |
return exact_paths[kind] |
| 384 |
if None in exact_paths: |
| 385 |
return exact_paths[None] |
| 386 |
if kind is ScalarNode: |
| 387 |
return self.DEFAULT_SCALAR_TAG |
| 388 |
elif kind is SequenceNode: |
| 389 |
return self.DEFAULT_SEQUENCE_TAG |
| 390 |
elif kind is MappingNode: |
| 391 |
return self.DEFAULT_MAPPING_TAG |
| 392 |
|
| 393 |
@property |
| 394 |
def processing_version(self): |
| 395 |
# type: () -> Any |
| 396 |
try: |
| 397 |
version = self.loadumper._scanner.yaml_version |
| 398 |
except AttributeError: |
| 399 |
try: |
| 400 |
if hasattr(self.loadumper, "typ"): |
| 401 |
version = self.loadumper.version |
| 402 |
else: |
| 403 |
version = self.loadumper._serializer.use_version # dumping |
| 404 |
except AttributeError: |
| 405 |
version = None |
| 406 |
if version is None: |
| 407 |
version = self._loader_version |
| 408 |
if version is None: |
| 409 |
version = _DEFAULT_YAML_VERSION |
| 410 |
return version |