From 954b56475eb524791d443a16a47fce9c306e2b31 Mon Sep 17 00:00:00 2001 From: mnestor Date: Sat, 14 May 2016 00:16:04 -0400 Subject: [PATCH] YAML: add !include_named_dir and ! include_list_dir (#2054) * add include_dir constructor for yaml parsing * changed to allow for flat and name based directory including * fixed ci errors * changed flat to list --- homeassistant/util/yaml.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/homeassistant/util/yaml.py b/homeassistant/util/yaml.py index bdf0c6d5c41..d70a8f1e3e0 100644 --- a/homeassistant/util/yaml.py +++ b/homeassistant/util/yaml.py @@ -3,6 +3,7 @@ import logging import os from collections import OrderedDict +import glob import yaml from homeassistant.exceptions import HomeAssistantError @@ -44,6 +45,22 @@ def _include_yaml(loader, node): return load_yaml(fname) +def _include_dir_named_yaml(loader, node): + """Load multiple files from dir.""" + mapping = OrderedDict() + files = os.path.join(os.path.dirname(loader.name), node.value, '*.yaml') + for fname in glob.glob(files): + filename = os.path.splitext(os.path.basename(fname))[0] + mapping[filename] = load_yaml(fname) + return mapping + + +def _include_dir_list_yaml(loader, node): + """Load multiple files from dir.""" + files = os.path.join(os.path.dirname(loader.name), node.value, '*.yaml') + return [load_yaml(f) for f in glob.glob(files)] + + def _ordered_dict(loader, node): """Load YAML mappings into an ordered dict to preserve key order.""" loader.flatten_mapping(node) @@ -84,3 +101,5 @@ yaml.SafeLoader.add_constructor('!include', _include_yaml) yaml.SafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _ordered_dict) yaml.SafeLoader.add_constructor('!env_var', _env_var_yaml) +yaml.SafeLoader.add_constructor('!include_dir_list', _include_dir_list_yaml) +yaml.SafeLoader.add_constructor('!include_dir_named', _include_dir_named_yaml)