import json import os import yaml from config import Config from renderer import Renderer from structure import Structure from xml_loader import XMLLoader class UnsupportedFormatException(Exception): ... class InstructionSetSchema: VALID_EXTENSIONS = ("yaml", "json", "xml") def __init__(self, path: str, configPath: str = "config.json", display: bool = False) -> None: self.config: Config = Config(configPath) self.display: bool = display self.path: str = path self.structures: dict[str, Structure] = {} self.load() def load(self) -> None: _, ext = os.path.splitext(self.path) ext = ext[1:].lower() if ext not in InstructionSetSchema.VALID_EXTENSIONS: fmts = tuple(map(lambda fmt: f".{fmt}", InstructionSetSchema.VALID_EXTENSIONS)) raise UnsupportedFormatException(f"'.{ext}' files are not supported. Valid formats: {fmts}") with open(self.path, "r") as f: if ext == "yaml": schema = yaml.safe_load(f) elif ext == "json": schema = json.load(f) elif ext == "xml": schema = XMLLoader.load(f) self.structures = {} for id_, data in schema["structures"].items(): id_ = str(id_) self.structures[id_] = Structure.load(id_, data) def save(self, path: str) -> None: renderer = Renderer(self.config, self.display) renderer.render(self) renderer.save(path) if self.display: input("Press ENTER to quit")