backup-tool/app/parser.py

52 lines
1.3 KiB
Python

"""Handles parsing a config file from disk."""
import yaml
from pathlib import Path
from typing import List, Union
from specs import Spec, DirectorySpec, VolumeSpec, ContainerSpec
import skeleton
def read_specs_file(path: Union[str, Path]) -> List[Spec]:
"""Read a config file and merge it with the skeleton.
Args:
path: path to the yaml config file
Returns:
A list of specs, parsed from the config.
"""
with open(path, "r") as yaml_file:
data = yaml.safe_load(yaml_file)
# NOTE shouldn't this be defined as a top-level variable?
categories = [
("directories", DirectorySpec),
("volumes", VolumeSpec),
("containers", ContainerSpec),
]
specs = []
for key, class_name in categories:
if not data["specs"].get(key):
continue
# Check what defaults are present
defaults = {}
if data.get("defaults"):
if data["defaults"].get("all"):
defaults = skeleton.merge(defaults, data["defaults"]["all"])
if data["defaults"].get(key):
defaults = skeleton.merge(defaults, data["defaults"][key])
specs.extend(
[
class_name.from_dict(name, spec, defaults)
for name, spec in data["specs"][key].items()
]
)
return specs