add some include_dir options (#2074)

* add some include_dir options

* validate, and extend instead of add

* add yaml include tests
This commit is contained in:
happyleavesaoc 2016-05-17 18:47:44 -04:00 committed by Paulus Schoutsen
parent a431277de1
commit 15f89fc636
2 changed files with 110 additions and 2 deletions

View file

@ -46,7 +46,7 @@ def _include_yaml(loader, node):
def _include_dir_named_yaml(loader, node):
"""Load multiple files from dir."""
"""Load multiple files from dir as a dict."""
mapping = OrderedDict()
files = os.path.join(os.path.dirname(loader.name), node.value, '*.yaml')
for fname in glob.glob(files):
@ -55,12 +55,34 @@ def _include_dir_named_yaml(loader, node):
return mapping
def _include_dir_merge_named_yaml(loader, node):
"""Load multiple files from dir as a merged dict."""
mapping = OrderedDict()
files = os.path.join(os.path.dirname(loader.name), node.value, '*.yaml')
for fname in glob.glob(files):
loaded_yaml = load_yaml(fname)
if isinstance(loaded_yaml, dict):
mapping.update(loaded_yaml)
return mapping
def _include_dir_list_yaml(loader, node):
"""Load multiple files from dir."""
"""Load multiple files from dir as a list."""
files = os.path.join(os.path.dirname(loader.name), node.value, '*.yaml')
return [load_yaml(f) for f in glob.glob(files)]
def _include_dir_merge_list_yaml(loader, node):
"""Load multiple files from dir as a merged list."""
files = os.path.join(os.path.dirname(loader.name), node.value, '*.yaml')
merged_list = []
for fname in glob.glob(files):
loaded_yaml = load_yaml(fname)
if isinstance(loaded_yaml, list):
merged_list.extend(loaded_yaml)
return merged_list
def _ordered_dict(loader, node):
"""Load YAML mappings into an ordered dict to preserve key order."""
loader.flatten_mapping(node)
@ -102,4 +124,8 @@ 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_merge_list',
_include_dir_merge_list_yaml)
yaml.SafeLoader.add_constructor('!include_dir_named', _include_dir_named_yaml)
yaml.SafeLoader.add_constructor('!include_dir_merge_named',
_include_dir_merge_named_yaml)