2016-03-07 22:20:48 +00:00
|
|
|
"""YAML utility functions."""
|
2016-01-24 06:37:15 +00:00
|
|
|
import logging
|
|
|
|
import os
|
2016-02-19 05:27:50 +00:00
|
|
|
from collections import OrderedDict
|
2016-01-24 06:37:15 +00:00
|
|
|
|
|
|
|
import yaml
|
|
|
|
|
|
|
|
from homeassistant.exceptions import HomeAssistantError
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def load_yaml(fname):
|
|
|
|
"""Load a YAML file."""
|
|
|
|
try:
|
|
|
|
with open(fname, encoding='utf-8') as conf_file:
|
|
|
|
# If configuration file is empty YAML returns None
|
|
|
|
# We convert that to an empty dict
|
2016-01-30 23:46:08 +00:00
|
|
|
return yaml.safe_load(conf_file) or {}
|
2016-01-24 06:37:15 +00:00
|
|
|
except yaml.YAMLError:
|
|
|
|
error = 'Error reading YAML configuration file {}'.format(fname)
|
|
|
|
_LOGGER.exception(error)
|
|
|
|
raise HomeAssistantError(error)
|
|
|
|
|
|
|
|
|
|
|
|
def _include_yaml(loader, node):
|
2016-03-07 22:20:48 +00:00
|
|
|
"""Load another YAML file and embeds it using the !include tag.
|
2016-01-24 06:37:15 +00:00
|
|
|
|
|
|
|
Example:
|
|
|
|
device_tracker: !include device_tracker.yaml
|
|
|
|
"""
|
|
|
|
fname = os.path.join(os.path.dirname(loader.name), node.value)
|
|
|
|
return load_yaml(fname)
|
|
|
|
|
|
|
|
|
|
|
|
def _ordered_dict(loader, node):
|
2016-03-07 22:20:48 +00:00
|
|
|
"""Load YAML mappings into an ordered dict to preserve key order."""
|
2016-01-24 06:37:15 +00:00
|
|
|
loader.flatten_mapping(node)
|
|
|
|
return OrderedDict(loader.construct_pairs(node))
|
|
|
|
|
|
|
|
|
2016-01-30 23:46:08 +00:00
|
|
|
yaml.SafeLoader.add_constructor('!include', _include_yaml)
|
|
|
|
yaml.SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
|
|
|
|
_ordered_dict)
|