| 1 | |
|---|
| 2 | __all__ = ['BaseConstructor', 'SafeConstructor', 'Constructor', |
|---|
| 3 | 'ConstructorError'] |
|---|
| 4 | |
|---|
| 5 | from error import * |
|---|
| 6 | from nodes import * |
|---|
| 7 | from composer import * |
|---|
| 8 | |
|---|
| 9 | try: |
|---|
| 10 | import datetime |
|---|
| 11 | datetime_available = True |
|---|
| 12 | except ImportError: |
|---|
| 13 | datetime_available = False |
|---|
| 14 | |
|---|
| 15 | try: |
|---|
| 16 | set |
|---|
| 17 | except NameError: |
|---|
| 18 | from sets import Set as set |
|---|
| 19 | |
|---|
| 20 | import binascii, re |
|---|
| 21 | |
|---|
| 22 | class ConstructorError(MarkedYAMLError): |
|---|
| 23 | pass |
|---|
| 24 | |
|---|
| 25 | class BaseConstructor(Composer): |
|---|
| 26 | |
|---|
| 27 | yaml_constructors = {} |
|---|
| 28 | yaml_multi_constructors = {} |
|---|
| 29 | |
|---|
| 30 | def __init__(self): |
|---|
| 31 | self.constructed_objects = {} |
|---|
| 32 | |
|---|
| 33 | def check_data(self): |
|---|
| 34 | # If there are more documents available? |
|---|
| 35 | return self.check_node() |
|---|
| 36 | |
|---|
| 37 | def get_data(self): |
|---|
| 38 | # Construct and return the next document. |
|---|
| 39 | if self.check_node(): |
|---|
| 40 | return self.construct_document(self.get_node()) |
|---|
| 41 | |
|---|
| 42 | def __iter__(self): |
|---|
| 43 | # Iterator protocol. |
|---|
| 44 | while self.check_node(): |
|---|
| 45 | yield self.construct_document(self.get_node()) |
|---|
| 46 | |
|---|
| 47 | def construct_document(self, node): |
|---|
| 48 | data = self.construct_object(node) |
|---|
| 49 | self.constructed_objects = {} |
|---|
| 50 | return data |
|---|
| 51 | |
|---|
| 52 | def construct_object(self, node): |
|---|
| 53 | if node in self.constructed_objects: |
|---|
| 54 | return self.constructed_objects[node] |
|---|
| 55 | constructor = None |
|---|
| 56 | if node.tag in self.yaml_constructors: |
|---|
| 57 | constructor = lambda node: self.yaml_constructors[node.tag](self, node) |
|---|
| 58 | else: |
|---|
| 59 | for tag_prefix in self.yaml_multi_constructors: |
|---|
| 60 | if node.tag.startswith(tag_prefix): |
|---|
| 61 | tag_suffix = node.tag[len(tag_prefix):] |
|---|
| 62 | constructor = lambda node: \ |
|---|
| 63 | self.yaml_multi_constructors[tag_prefix](self, tag_suffix, node) |
|---|
| 64 | break |
|---|
| 65 | else: |
|---|
| 66 | if None in self.yaml_multi_constructors: |
|---|
| 67 | constructor = lambda node: \ |
|---|
| 68 | self.yaml_multi_constructors[None](self, node.tag, node) |
|---|
| 69 | elif None in self.yaml_constructors: |
|---|
| 70 | constructor = lambda node: \ |
|---|
| 71 | self.yaml_constructors[None](self, node) |
|---|
| 72 | elif isinstance(node, ScalarNode): |
|---|
| 73 | constructor = self.construct_scalar |
|---|
| 74 | elif isinstance(node, SequenceNode): |
|---|
| 75 | constructor = self.construct_sequence |
|---|
| 76 | elif isinstance(node, MappingNode): |
|---|
| 77 | constructor = self.construct_mapping |
|---|
| 78 | data = constructor(node) |
|---|
| 79 | self.constructed_objects[node] = data |
|---|
| 80 | return data |
|---|
| 81 | |
|---|
| 82 | def construct_scalar(self, node): |
|---|
| 83 | if not isinstance(node, ScalarNode): |
|---|
| 84 | if isinstance(node, MappingNode): |
|---|
| 85 | for key_node in node.value: |
|---|
| 86 | if key_node.tag == u'tag:yaml.org,2002:value': |
|---|
| 87 | return self.construct_scalar(node.value[key_node]) |
|---|
| 88 | raise ConstructorError(None, None, |
|---|
| 89 | "expected a scalar node, but found %s" % node.id, |
|---|
| 90 | node.start_mark) |
|---|
| 91 | return node.value |
|---|
| 92 | |
|---|
| 93 | def construct_sequence(self, node): |
|---|
| 94 | if not isinstance(node, SequenceNode): |
|---|
| 95 | raise ConstructorError(None, None, |
|---|
| 96 | "expected a sequence node, but found %s" % node.id, |
|---|
| 97 | node.start_mark) |
|---|
| 98 | return [self.construct_object(child) for child in node.value] |
|---|
| 99 | |
|---|
| 100 | def construct_mapping(self, node): |
|---|
| 101 | if not isinstance(node, MappingNode): |
|---|
| 102 | raise ConstructorError(None, None, |
|---|
| 103 | "expected a mapping node, but found %s" % node.id, |
|---|
| 104 | node.start_mark) |
|---|
| 105 | mapping = {} |
|---|
| 106 | merge = None |
|---|
| 107 | for key_node in node.value: |
|---|
| 108 | if key_node.tag == u'tag:yaml.org,2002:merge': |
|---|
| 109 | if merge is not None: |
|---|
| 110 | raise ConstructorError("while constructing a mapping", node.start_mark, |
|---|
| 111 | "found duplicate merge key", key_node.start_mark) |
|---|
| 112 | value_node = node.value[key_node] |
|---|
| 113 | if isinstance(value_node, MappingNode): |
|---|
| 114 | merge = [self.construct_mapping(value_node)] |
|---|
| 115 | elif isinstance(value_node, SequenceNode): |
|---|
| 116 | merge = [] |
|---|
| 117 | for subnode in value_node.value: |
|---|
| 118 | if not isinstance(subnode, MappingNode): |
|---|
| 119 | raise ConstructorError("while constructing a mapping", |
|---|
| 120 | node.start_mark, |
|---|
| 121 | "expected a mapping for merging, but found %s" |
|---|
| 122 | % subnode.id, subnode.start_mark) |
|---|
| 123 | merge.append(self.construct_mapping(subnode)) |
|---|
| 124 | merge.reverse() |
|---|
| 125 | else: |
|---|
| 126 | raise ConstructorError("while constructing a mapping", node.start_mark, |
|---|
| 127 | "expected a mapping or list of mappings for merging, but found %s" |
|---|
| 128 | % value_node.id, value_node.start_mark) |
|---|
| 129 | elif key_node.tag == u'tag:yaml.org,2002:value': |
|---|
| 130 | if '=' in mapping: |
|---|
| 131 | raise ConstructorError("while construction a mapping", node.start_mark, |
|---|
| 132 | "found duplicate value key", key_node.start_mark) |
|---|
| 133 | value = self.construct_object(node.value[key_node]) |
|---|
| 134 | mapping['='] = value |
|---|
| 135 | else: |
|---|
| 136 | key = self.construct_object(key_node) |
|---|
| 137 | try: |
|---|
| 138 | duplicate_key = key in mapping |
|---|
| 139 | except TypeError, exc: |
|---|
| 140 | raise ConstructorError("while constructing a mapping", node.start_mark, |
|---|
| 141 | "found unacceptable key (%s)" % exc, key_node.start_mark) |
|---|
| 142 | if duplicate_key: |
|---|
| 143 | raise ConstructorError("while constructing a mapping", node.start_mark, |
|---|
| 144 | "found duplicate key", key_node.start_mark) |
|---|
| 145 | value = self.construct_object(node.value[key_node]) |
|---|
| 146 | mapping[key] = value |
|---|
| 147 | if merge is not None: |
|---|
| 148 | merge.append(mapping) |
|---|
| 149 | mapping = {} |
|---|
| 150 | for submapping in merge: |
|---|
| 151 | mapping.update(submapping) |
|---|
| 152 | return mapping |
|---|
| 153 | |
|---|
| 154 | def construct_pairs(self, node): |
|---|
| 155 | if not isinstance(node, MappingNode): |
|---|
| 156 | raise ConstructorError(None, None, |
|---|
| 157 | "expected a mapping node, but found %s" % node.id, |
|---|
| 158 | node.start_mark) |
|---|
| 159 | pairs = [] |
|---|
| 160 | for key_node in node.value: |
|---|
| 161 | key = self.construct_object(key_node) |
|---|
| 162 | value = self.construct_object(node.value[key_node]) |
|---|
| 163 | pairs.append((key, value)) |
|---|
| 164 | return pairs |
|---|
| 165 | |
|---|
| 166 | def add_constructor(cls, tag, constructor): |
|---|
| 167 | if not 'yaml_constructors' in cls.__dict__: |
|---|
| 168 | cls.yaml_constructors = cls.yaml_constructors.copy() |
|---|
| 169 | cls.yaml_constructors[tag] = constructor |
|---|
| 170 | add_constructor = classmethod(add_constructor) |
|---|
| 171 | |
|---|
| 172 | def add_multi_constructor(cls, tag_prefix, multi_constructor): |
|---|
| 173 | if not 'yaml_multi_constructors' in cls.__dict__: |
|---|
| 174 | cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy() |
|---|
| 175 | cls.yaml_multi_constructors[tag_prefix] = multi_constructor |
|---|
| 176 | add_multi_constructor = classmethod(add_multi_constructor) |
|---|
| 177 | |
|---|
| 178 | class SafeConstructor(BaseConstructor): |
|---|
| 179 | |
|---|
| 180 | def construct_yaml_null(self, node): |
|---|
| 181 | self.construct_scalar(node) |
|---|
| 182 | return None |
|---|
| 183 | |
|---|
| 184 | bool_values = { |
|---|
| 185 | u'yes': True, |
|---|
| 186 | u'no': False, |
|---|
| 187 | u'true': True, |
|---|
| 188 | u'false': False, |
|---|
| 189 | u'on': True, |
|---|
| 190 | u'off': False, |
|---|
| 191 | } |
|---|
| 192 | |
|---|
| 193 | def construct_yaml_bool(self, node): |
|---|
| 194 | value = self.construct_scalar(node) |
|---|
| 195 | return self.bool_values[value.lower()] |
|---|
| 196 | |
|---|
| 197 | def construct_yaml_int(self, node): |
|---|
| 198 | value = str(self.construct_scalar(node)) |
|---|
| 199 | value = value.replace('_', '') |
|---|
| 200 | sign = +1 |
|---|
| 201 | if value[0] == '-': |
|---|
| 202 | sign = -1 |
|---|
| 203 | if value[0] in '+-': |
|---|
| 204 | value = value[1:] |
|---|
| 205 | if value == '0': |
|---|
| 206 | return 0 |
|---|
| 207 | elif value.startswith('0b'): |
|---|
| 208 | return sign*int(value[2:], 2) |
|---|
| 209 | elif value.startswith('0x'): |
|---|
| 210 | return sign*int(value[2:], 16) |
|---|
| 211 | elif value[0] == '0': |
|---|
| 212 | return sign*int(value, 8) |
|---|
| 213 | elif ':' in value: |
|---|
| 214 | digits = [int(part) for part in value.split(':')] |
|---|
| 215 | digits.reverse() |
|---|
| 216 | base = 1 |
|---|
| 217 | value = 0 |
|---|
| 218 | for digit in digits: |
|---|
| 219 | value += digit*base |
|---|
| 220 | base *= 60 |
|---|
| 221 | return sign*value |
|---|
| 222 | else: |
|---|
| 223 | return sign*int(value) |
|---|
| 224 | |
|---|
| 225 | inf_value = 1e300000 |
|---|
| 226 | nan_value = inf_value/inf_value |
|---|
| 227 | |
|---|
| 228 | def construct_yaml_float(self, node): |
|---|
| 229 | value = str(self.construct_scalar(node)) |
|---|
| 230 | value = value.replace('_', '') |
|---|
| 231 | sign = +1 |
|---|
| 232 | if value[0] == '-': |
|---|
| 233 | sign = -1 |
|---|
| 234 | if value[0] in '+-': |
|---|
| 235 | value = value[1:] |
|---|
| 236 | if value.lower() == '.inf': |
|---|
| 237 | return sign*self.inf_value |
|---|
| 238 | elif value.lower() == '.nan': |
|---|
| 239 | return self.nan_value |
|---|
| 240 | elif ':' in value: |
|---|
| 241 | digits = [float(part) for part in value.split(':')] |
|---|
| 242 | digits.reverse() |
|---|
| 243 | base = 1 |
|---|
| 244 | value = 0.0 |
|---|
| 245 | for digit in digits: |
|---|
| 246 | value += digit*base |
|---|
| 247 | base *= 60 |
|---|
| 248 | return sign*value |
|---|
| 249 | else: |
|---|
| 250 | return float(value) |
|---|
| 251 | |
|---|
| 252 | def construct_yaml_binary(self, node): |
|---|
| 253 | value = self.construct_scalar(node) |
|---|
| 254 | try: |
|---|
| 255 | return str(value).decode('base64') |
|---|
| 256 | except (binascii.Error, UnicodeEncodeError), exc: |
|---|
| 257 | raise ConstructorError(None, None, |
|---|
| 258 | "failed to decode base64 data: %s" % exc, node.start_mark) |
|---|
| 259 | |
|---|
| 260 | timestamp_regexp = re.compile( |
|---|
| 261 | ur'''^(?P<year>[0-9][0-9][0-9][0-9]) |
|---|
| 262 | -(?P<month>[0-9][0-9]?) |
|---|
| 263 | -(?P<day>[0-9][0-9]?) |
|---|
| 264 | (?:(?:[Tt]|[ \t]+) |
|---|
| 265 | (?P<hour>[0-9][0-9]?) |
|---|
| 266 | :(?P<minute>[0-9][0-9]) |
|---|
| 267 | :(?P<second>[0-9][0-9]) |
|---|
| 268 | (?:\.(?P<fraction>[0-9]*))? |
|---|
| 269 | (?:[ \t]*(?:Z|(?P<tz_hour>[-+][0-9][0-9]?) |
|---|
| 270 | (?::(?P<tz_minute>[0-9][0-9])?)?))?)?$''', re.X) |
|---|
| 271 | |
|---|
| 272 | def construct_yaml_timestamp(self, node): |
|---|
| 273 | value = self.construct_scalar(node) |
|---|
| 274 | match = self.timestamp_regexp.match(node.value) |
|---|
| 275 | values = match.groupdict() |
|---|
| 276 | for key in values: |
|---|
| 277 | if values[key]: |
|---|
| 278 | values[key] = int(values[key]) |
|---|
| 279 | else: |
|---|
| 280 | values[key] = 0 |
|---|
| 281 | fraction = values['fraction'] |
|---|
| 282 | if fraction: |
|---|
| 283 | while 10*fraction < 1000000: |
|---|
| 284 | fraction *= 10 |
|---|
| 285 | values['fraction'] = fraction |
|---|
| 286 | stamp = datetime.datetime(values['year'], values['month'], values['day'], |
|---|
| 287 | values['hour'], values['minute'], values['second'], values['fraction']) |
|---|
| 288 | diff = datetime.timedelta(hours=values['tz_hour'], minutes=values['tz_minute']) |
|---|
| 289 | return stamp-diff |
|---|
| 290 | |
|---|
| 291 | def construct_yaml_omap(self, node): |
|---|
| 292 | # Note: we do not check for duplicate keys, because it's too |
|---|
| 293 | # CPU-expensive. |
|---|
| 294 | if not isinstance(node, SequenceNode): |
|---|
| 295 | raise ConstructorError("while constructing an ordered map", node.start_mark, |
|---|
| 296 | "expected a sequence, but found %s" % node.id, node.start_mark) |
|---|
| 297 | omap = [] |
|---|
| 298 | for subnode in node.value: |
|---|
| 299 | if not isinstance(subnode, MappingNode): |
|---|
| 300 | raise ConstructorError("while constructing an ordered map", node.start_mark, |
|---|
| 301 | "expected a mapping of length 1, but found %s" % subnode.id, |
|---|
| 302 | subnode.start_mark) |
|---|
| 303 | if len(subnode.value) != 1: |
|---|
| 304 | raise ConstructorError("while constructing an ordered map", node.start_mark, |
|---|
| 305 | "expected a single mapping item, but found %d items" % len(subnode.value), |
|---|
| 306 | subnode.start_mark) |
|---|
| 307 | key_node = subnode.value.keys()[0] |
|---|
| 308 | key = self.construct_object(key_node) |
|---|
| 309 | value = self.construct_object(subnode.value[key_node]) |
|---|
| 310 | omap.append((key, value)) |
|---|
| 311 | return omap |
|---|
| 312 | |
|---|
| 313 | def construct_yaml_pairs(self, node): |
|---|
| 314 | # Note: the same code as `construct_yaml_omap`. |
|---|
| 315 | if not isinstance(node, SequenceNode): |
|---|
| 316 | raise ConstructorError("while constructing pairs", node.start_mark, |
|---|
| 317 | "expected a sequence, but found %s" % node.id, node.start_mark) |
|---|
| 318 | pairs = [] |
|---|
| 319 | for subnode in node.value: |
|---|
| 320 | if not isinstance(subnode, MappingNode): |
|---|
| 321 | raise ConstructorError("while constructing pairs", node.start_mark, |
|---|
| 322 | "expected a mapping of length 1, but found %s" % subnode.id, |
|---|
| 323 | subnode.start_mark) |
|---|
| 324 | if len(subnode.value) != 1: |
|---|
| 325 | raise ConstructorError("while constructing pairs", node.start_mark, |
|---|
| 326 | "expected a single mapping item, but found %d items" % len(subnode.value), |
|---|
| 327 | subnode.start_mark) |
|---|
| 328 | key_node = subnode.value.keys()[0] |
|---|
| 329 | key = self.construct_object(key_node) |
|---|
| 330 | value = self.construct_object(subnode.value[key_node]) |
|---|
| 331 | pairs.append((key, value)) |
|---|
| 332 | return pairs |
|---|
| 333 | |
|---|
| 334 | def construct_yaml_set(self, node): |
|---|
| 335 | value = self.construct_mapping(node) |
|---|
| 336 | return set(value) |
|---|
| 337 | |
|---|
| 338 | def construct_yaml_str(self, node): |
|---|
| 339 | value = self.construct_scalar(node) |
|---|
| 340 | try: |
|---|
| 341 | return str(value) |
|---|
| 342 | except UnicodeEncodeError: |
|---|
| 343 | return value |
|---|
| 344 | |
|---|
| 345 | def construct_yaml_seq(self, node): |
|---|
| 346 | return self.construct_sequence(node) |
|---|
| 347 | |
|---|
| 348 | def construct_yaml_map(self, node): |
|---|
| 349 | return self.construct_mapping(node) |
|---|
| 350 | |
|---|
| 351 | def construct_yaml_object(self, node, cls): |
|---|
| 352 | mapping = self.construct_mapping(node) |
|---|
| 353 | state = {} |
|---|
| 354 | for key in mapping: |
|---|
| 355 | state[key.replace('-', '_')] = mapping[key] |
|---|
| 356 | data = cls.__new__(cls) |
|---|
| 357 | if hasattr(data, '__setstate__'): |
|---|
| 358 | data.__setstate__(mapping) |
|---|
| 359 | else: |
|---|
| 360 | data.__dict__.update(mapping) |
|---|
| 361 | return data |
|---|
| 362 | |
|---|
| 363 | def construct_undefined(self, node): |
|---|
| 364 | raise ConstructorError(None, None, |
|---|
| 365 | "could not determine a constructor for the tag %r" % node.tag.encode('utf-8'), |
|---|
| 366 | node.start_mark) |
|---|
| 367 | |
|---|
| 368 | SafeConstructor.add_constructor( |
|---|
| 369 | u'tag:yaml.org,2002:null', |
|---|
| 370 | SafeConstructor.construct_yaml_null) |
|---|
| 371 | |
|---|
| 372 | SafeConstructor.add_constructor( |
|---|
| 373 | u'tag:yaml.org,2002:bool', |
|---|
| 374 | SafeConstructor.construct_yaml_bool) |
|---|
| 375 | |
|---|
| 376 | SafeConstructor.add_constructor( |
|---|
| 377 | u'tag:yaml.org,2002:int', |
|---|
| 378 | SafeConstructor.construct_yaml_int) |
|---|
| 379 | |
|---|
| 380 | SafeConstructor.add_constructor( |
|---|
| 381 | u'tag:yaml.org,2002:float', |
|---|
| 382 | SafeConstructor.construct_yaml_float) |
|---|
| 383 | |
|---|
| 384 | SafeConstructor.add_constructor( |
|---|
| 385 | u'tag:yaml.org,2002:binary', |
|---|
| 386 | SafeConstructor.construct_yaml_binary) |
|---|
| 387 | |
|---|
| 388 | if datetime_available: |
|---|
| 389 | SafeConstructor.add_constructor( |
|---|
| 390 | u'tag:yaml.org,2002:timestamp', |
|---|
| 391 | SafeConstructor.construct_yaml_timestamp) |
|---|
| 392 | |
|---|
| 393 | SafeConstructor.add_constructor( |
|---|
| 394 | u'tag:yaml.org,2002:omap', |
|---|
| 395 | SafeConstructor.construct_yaml_omap) |
|---|
| 396 | |
|---|
| 397 | SafeConstructor.add_constructor( |
|---|
| 398 | u'tag:yaml.org,2002:pairs', |
|---|
| 399 | SafeConstructor.construct_yaml_pairs) |
|---|
| 400 | |
|---|
| 401 | SafeConstructor.add_constructor( |
|---|
| 402 | u'tag:yaml.org,2002:set', |
|---|
| 403 | SafeConstructor.construct_yaml_set) |
|---|
| 404 | |
|---|
| 405 | SafeConstructor.add_constructor( |
|---|
| 406 | u'tag:yaml.org,2002:str', |
|---|
| 407 | SafeConstructor.construct_yaml_str) |
|---|
| 408 | |
|---|
| 409 | SafeConstructor.add_constructor( |
|---|
| 410 | u'tag:yaml.org,2002:seq', |
|---|
| 411 | SafeConstructor.construct_yaml_seq) |
|---|
| 412 | |
|---|
| 413 | SafeConstructor.add_constructor( |
|---|
| 414 | u'tag:yaml.org,2002:map', |
|---|
| 415 | SafeConstructor.construct_yaml_map) |
|---|
| 416 | |
|---|
| 417 | SafeConstructor.add_constructor(None, |
|---|
| 418 | SafeConstructor.construct_undefined) |
|---|
| 419 | |
|---|
| 420 | class Constructor(SafeConstructor): |
|---|
| 421 | pass |
|---|
| 422 | |
|---|