1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
5 # http://www.apache.org/licenses/LICENSE-2.0
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
14 from collections import OrderedDict
16 from six.moves import urllib
19 from toscaparser.common.exception import ExceptionCollector
20 from toscaparser.common.exception import URLException
21 from toscaparser.utils.gettextutils import _
24 if hasattr(yaml, 'CSafeLoader'):
25 yaml_loader = yaml.CSafeLoader
27 yaml_loader = yaml.SafeLoader
30 def load_yaml(path, a_file=True):
33 f = codecs.open(path, encoding='utf-8', errors='strict') if a_file \
34 else urllib.request.urlopen(path)
35 except urllib.error.URLError as e:
36 if hasattr(e, 'reason'):
37 msg = (_('Failed to reach server "%(path)s". Reason is: '
39 % {'path': path, 'reason': e.reason})
40 ExceptionCollector.appendException(URLException(what=msg))
42 elif hasattr(e, 'code'):
43 msg = (_('The server "%(path)s" couldn\'t fulfill the request. '
44 'Error code: "%(code)s".')
45 % {'path': path, 'code': e.code})
46 ExceptionCollector.appendException(URLException(what=msg))
48 except Exception as e:
50 return yaml.load(f.read(), Loader=yaml_loader)
53 def simple_parse(tmpl_str):
55 tpl = yaml.load(tmpl_str, Loader=yaml_loader)
56 except yaml.YAMLError as yea:
57 ExceptionCollector.appendException(ValueError(yea))
64 def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
65 class OrderedLoader(Loader):
68 def construct_mapping(loader, node):
69 loader.flatten_mapping(node)
70 return object_pairs_hook(loader.construct_pairs(node))
72 OrderedLoader.add_constructor(
73 yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
75 return yaml.load(stream, OrderedLoader)
78 def simple_ordered_parse(tmpl_str):
80 tpl = ordered_load(tmpl_str)
81 except yaml.YAMLError as yea:
82 ExceptionCollector.appendException(ValueError(yea))