ldapcherry/ldapcherry/pyyamlwrapper.py

81 lines
2.1 KiB
Python
Raw Normal View History

2015-05-12 01:24:16 +02:00
# -*- coding: utf-8 -*-
import os
import sys
import yaml
2015-05-12 01:24:16 +02:00
from yaml.error import *
from yaml.nodes import *
from yaml.reader import *
from yaml.scanner import *
from yaml.parser import *
from yaml.composer import *
from yaml.constructor import *
from yaml.resolver import *
class RelationError(Exception):
def __init__(self, key, value):
2015-07-10 21:06:28 +02:00
self.key = key
2015-05-12 01:24:16 +02:00
self.value = value
2015-07-10 21:06:28 +02:00
2015-05-12 01:24:16 +02:00
class DumplicatedKey(Exception):
def __init__(self, host, key):
2015-07-10 21:06:28 +02:00
self.host = host
self.key = key
2015-05-12 01:24:16 +02:00
try:
2015-07-10 21:06:28 +02:00
from yaml import CLoader as Loader, CDumper as Dumper
2015-05-12 01:24:16 +02:00
except ImportError:
2015-07-10 21:06:28 +02:00
from yaml import Loader, Dumper
2015-05-12 01:24:16 +02:00
2015-06-06 22:23:21 +02:00
# PyYaml wrapper that loads yaml files throwing an exception
2015-07-11 22:03:58 +02:00
# if a key is dumplicated
2015-05-12 01:24:16 +02:00
class MyLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver):
def __init__(self, stream):
Reader.__init__(self, stream)
Scanner.__init__(self)
Parser.__init__(self)
Composer.__init__(self)
Constructor.__init__(self)
Resolver.__init__(self)
def construct_mapping(self, node, deep=False):
exc = sys.exc_info()[1]
if not isinstance(node, MappingNode):
2015-07-11 22:03:58 +02:00
raise ConstructorError(
None,
None,
"expected a mapping node, but found %s" % node.id,
node.start_mark
)
2015-05-12 01:24:16 +02:00
mapping = {}
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
try:
hash(key)
except TypeError:
2015-07-11 22:03:58 +02:00
raise ConstructorError(
"while constructing a mapping",
node.start_mark,
"found unacceptable key (%s)" % exc, key_node.start_mark
)
2015-05-12 01:24:16 +02:00
value = self.construct_object(value_node, deep=deep)
if key in mapping:
raise DumplicatedKey(key, '')
mapping[key] = value
return mapping
def loadNoDump(stream):
loader = MyLoader(stream)
try:
return loader.get_single_data()
finally:
loader.dispose()
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4