Skip to content

Instantly share code, notes, and snippets.

@cimnine
Last active April 4, 2020 20:22
Show Gist options
  • Save cimnine/95f594bae302682cd12e1b38e0ba4484 to your computer and use it in GitHub Desktop.
Save cimnine/95f594bae302682cd12e1b38e0ba4484 to your computer and use it in GitHub Desktop.
import itertools
from ruamel.yaml import YAML
from pathlib import Path
def load_yaml(yaml_base_path: str):
yaml_path = Path(yaml_base_path)
content_list = []
content_list.append(load_file(yaml_path.with_suffix('.yml')))
load_dir(content_list, yaml_path.with_suffix('.d'))
return flatten(content_list)
def load_file(yaml_file_path: Path):
if not yaml_file_path.is_file():
return []
with yaml_file_path.open("r") as stream:
yaml = YAML(typ="safe")
return yaml.load(stream)
def load_dir(content_list: list, yaml_dir_path: Path):
if not yaml_dir_path.is_dir():
return
for yaml_file_path in yaml_dir_path.glob('*.yml')
content_list.append(load_file(yaml_file_path))
def flatten(content_list: list):
if len(content_list) == 0:
return content_list
if len(content_list) == 1:
return content_list[0]
if isinstance(content[0], list):
return flatten_list(content_list)
if isinstance(content_list[0], dict):
return flatten_dict(content_list)
def flatten_list(content_list: list):
# https://stackoverflow.com/a/952952
flat_list = []
for sublist in content_list:
if not sublist:
continue
for item in sublist:
flat_list.append(item)
return flat_list
def flatten_dict(content_list: list):
# https://stackoverflow.com/a/3495395
flat_dict = {}
for subdict in content_list:
if not subdict:
continue
flat_dict.update(subdict)
return flat_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment