diff --git a/chatmastermind/glossary.py b/chatmastermind/glossary.py index 139666d..1a49fdc 100644 --- a/chatmastermind/glossary.py +++ b/chatmastermind/glossary.py @@ -7,7 +7,7 @@ import shutil import csv from pathlib import Path from dataclasses import dataclass, field -from typing import Type, TypeVar +from typing import Type, TypeVar, ClassVar GlossaryInst = TypeVar('GlossaryInst', bound='Glossary') @@ -43,12 +43,17 @@ class Glossary: entries: dict[str, str] = field(default_factory=lambda: dict()) file_path: Path | None = None ID: str | None = None + file_suffix: ClassVar[str] = '.glo' @classmethod def from_file(cls: Type[GlossaryInst], file_path: Path) -> GlossaryInst: """ Create a glossary from the given file. """ + if not file_path.exists(): + raise GlossaryError(f"Glossary file '{file_path}' does not exist") + if file_path.suffix != cls.file_suffix: + raise GlossaryError(f"File type '{file_path.suffix}' is not supported") with open(file_path, "r") as fd: try: data = yaml.load(fd, Loader=yaml.FullLoader) @@ -72,6 +77,11 @@ class Glossary: self.file_path = file_path if not self.file_path: raise GlossaryError("Got no valid path to write glossary") + # check / add valid suffix + if not self.file_path.suffix: + self.file_path = self.file_path.with_suffix(self.file_suffix) + elif self.file_path.suffix != self.file_suffix: + raise GlossaryError(f"File suffix '{self.file_path.suffix}' is not supported") # write YAML with tempfile.NamedTemporaryFile(dir=self.file_path.parent, prefix=self.file_path.name, mode="w", delete=False) as temp_fd: temp_file_path = Path(temp_fd.name)