import tomlkit import json from pathlib import Path from tomlkit import TOMLDocument from typing import Any class Mod: __config: TOMLDocument __has_meta_json: bool __meta: dict[str, Any] __path: Path __name: str __description: str __author: str __enabled: bool @property def path(self) -> Path: return self.__path # Mod metadata @property def name(self) -> str | None: if "name" not in self.__config: return None return self.__config.get("name", str) @property def description(self) -> str | None: if "description" not in self.__config.keys(): return None else: return self.__config.get("description", str) @property def author(self) -> str | None: if "author" not in self.__config: return None return self.__config.get("author", str) @property def enabled(self) -> bool: return self.__enabled @enabled.setter def enabled(self, value: bool) -> None: if value == self.__enabled: # Nothing to do return config_toml = Path(self.__path, "config.toml") with config_toml.open("w") as config_file: self.__config["enabled"] = value tomlkit.dump(self.__config, config_file) self.__enabled = value def __init__(self, path: Path) -> None: self.__path = path self.__meta = {} try: config_toml = Path(self.__path, "config.toml") with config_toml.open() as config_file: self.__config = tomlkit.load(config_file) if "enabled" not in self.__config: raise InvalidModError("config.toml does not contain the enabled key") self.__enabled = self.__config.get("enabled", bool) except FileNotFoundError: raise InvalidModError("config.toml does not exist") meta_json: Path = Path(self.__path, "meta.json") if meta_json.exists(): self.__has_meta_json = True try: with meta_json.open() as file: self.__meta = json.load(file) except json.JSONDecodeError as e: print("Failed to parse meta.json!: ", e.msg) else: self.__has_meta_json = False def __str__(self) -> str: return f"Mod({self.__path})" class InvalidModError(Exception): """ This exception is raised when the Mod class gets given a path of something that's not a valid mod """ def __init__(self, message: str) -> None: super().__init__(message) self.message = message def __str__(self) -> str: return f"{self.message}"