glossary: added suffix check

This commit is contained in:
juk0de 2024-02-03 21:09:33 +01:00
parent 85315d9c1c
commit 6e89e014bf

View File

@ -7,7 +7,7 @@ import shutil
import csv import csv
from pathlib import Path from pathlib import Path
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Type, TypeVar from typing import Type, TypeVar, ClassVar
GlossaryInst = TypeVar('GlossaryInst', bound='Glossary') GlossaryInst = TypeVar('GlossaryInst', bound='Glossary')
@ -43,12 +43,17 @@ class Glossary:
entries: dict[str, str] = field(default_factory=lambda: dict()) entries: dict[str, str] = field(default_factory=lambda: dict())
file_path: Path | None = None file_path: Path | None = None
ID: str | None = None ID: str | None = None
file_suffix: ClassVar[str] = '.glo'
@classmethod @classmethod
def from_file(cls: Type[GlossaryInst], file_path: Path) -> GlossaryInst: def from_file(cls: Type[GlossaryInst], file_path: Path) -> GlossaryInst:
""" """
Create a glossary from the given file. 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: with open(file_path, "r") as fd:
try: try:
data = yaml.load(fd, Loader=yaml.FullLoader) data = yaml.load(fd, Loader=yaml.FullLoader)
@ -72,6 +77,11 @@ class Glossary:
self.file_path = file_path self.file_path = file_path
if not self.file_path: if not self.file_path:
raise GlossaryError("Got no valid path to write glossary") 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 # write YAML
with tempfile.NamedTemporaryFile(dir=self.file_path.parent, prefix=self.file_path.name, mode="w", delete=False) as temp_fd: 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) temp_file_path = Path(temp_fd.name)