rivet/schema.py

56 lines
1.6 KiB
Python
Raw Permalink Normal View History

2023-11-24 16:37:26 +00:00
import json
import os
2024-03-24 10:33:34 +00:00
2023-11-24 13:34:44 +00:00
import yaml
from config import Config
from renderer import Renderer
from structure import Structure
2023-11-24 17:14:13 +00:00
from xml_loader import XMLLoader
2023-11-24 13:34:44 +00:00
2024-03-24 10:33:34 +00:00
2023-11-24 16:37:26 +00:00
class UnsupportedFormatException(Exception):
...
2024-03-24 10:33:34 +00:00
2023-11-24 13:34:44 +00:00
class InstructionSetSchema:
2023-11-24 17:14:13 +00:00
VALID_EXTENSIONS = ("yaml", "json", "xml")
2023-11-24 16:37:26 +00:00
2024-01-28 12:52:45 +00:00
def __init__(self, path: str, configPath: str = "config.json", display: bool = False) -> None:
2024-04-12 21:33:09 +00:00
self.config: Config = Config(configPath)
self.display: bool = display
self.path: str = path
self.structures: dict[str, Structure] = {}
2023-11-24 13:34:44 +00:00
self.load()
def load(self) -> None:
2023-11-24 16:37:26 +00:00
_, 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}")
2023-11-24 13:34:44 +00:00
with open(self.path, "r") as f:
2023-11-24 16:37:26 +00:00
if ext == "yaml":
schema = yaml.safe_load(f)
elif ext == "json":
schema = json.load(f)
2023-11-24 17:14:13 +00:00
elif ext == "xml":
schema = XMLLoader.load(f)
2023-11-24 13:34:44 +00:00
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:
2024-01-28 12:52:45 +00:00
renderer = Renderer(self.config, self.display)
2023-11-24 13:34:44 +00:00
renderer.render(self)
2024-01-28 12:52:45 +00:00
renderer.save(path)
if self.display:
2024-04-12 21:33:09 +00:00
input("Press ENTER to quit")