def handle_imports(content, directory): import_files = content.get('import', []) if isinstance(import_files, basestring): import_files = [import_files] for fname in import_files[::-1]: import_path = os.path.join(directory, fname) print("importing: '%s'" % import_path) import_directory = os.path.dirname(import_path) with open(import_path) as f: import_content = handle_imports(yaml.load(f), import_directory) expand_periodic_fields(import_content) for wild_key in ('globals/*/fields', 'entities/*/fields'): multi_keys = expand_wild(wild_key, import_content) for multi_key in multi_keys: import_fields = multi_get(import_content, multi_key) local_fields = multi_get(content, multi_key, []) # fields are in "yaml ordered dict" format and we want # simple list of items import_fields = [d.items()[0] for d in import_fields] local_fields = [d.items()[0] for d in local_fields] # merge the lists merged_fields = merge_items(import_fields, local_fields) # convert them back to "yaml ordered dict" merged_fields = [{k: v} for k, v in merged_fields] multi_set(content, multi_key, merged_fields) content = merge_dicts(import_content, content) return content
def handle_imports(content, directory): import_files = content.get('import', []) if isinstance(import_files, basestring): import_files = [import_files] for fname in import_files[::-1]: import_path = os.path.abspath(os.path.join(directory, fname)) print("importing: '%s'" % import_path) import_directory = os.path.dirname(import_path) with open(import_path) as f: import_content = handle_imports(yaml.load(f), import_directory) expand_periodic_fields(import_content) for wild_key in ('globals/*/fields', 'entities/*/fields'): multi_keys = expand_wild(wild_key, import_content) for multi_key in multi_keys: import_fields = multi_get(import_content, multi_key) local_fields = multi_get(content, multi_key, []) # fields are in "yaml ordered dict" format and we want # simple list of items import_fields = [d.items()[0] for d in import_fields] local_fields = [d.items()[0] for d in local_fields] # merge the lists merged_fields = merge_items(import_fields, local_fields) # convert them back to "yaml ordered dict" merged_fields = [{k: v} for k, v in merged_fields] multi_set(content, multi_key, merged_fields) content = merge_dicts(import_content, content) return content
def expand_periodic_fields(content): periodic = multi_get(content, 'globals/periodic') if isinstance(periodic, list) and \ all(isinstance(f, dict) for f in periodic): multi_set(content, 'globals/periodic', {'fields': periodic})