added packloader and init py
This commit is contained in:
@@ -0,0 +1 @@
|
||||
__version__ = "0.1.0"
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from importlib.metadata import entry_points
|
||||
from pathlib import Path
|
||||
|
||||
REQUIRED_SECTIONS = {"meta", "keywords", "builtins", "exceptions", "error_messages", "stdlib"}
|
||||
|
||||
|
||||
class PackNotFoundError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidPackError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _discover_packs() -> dict[str, object]:
|
||||
"""Find all installed language packs via entry points."""
|
||||
eps = entry_points(group="foreignthon.langs")
|
||||
return {ep.name: ep.load() for ep in eps}
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def load_pack(lang_code: str) -> dict:
|
||||
"""Load and validate a language pack by its code (e.g. 'es', 'ta')."""
|
||||
packs = _discover_packs()
|
||||
|
||||
if lang_code not in packs:
|
||||
available = ", ".join(packs.keys()) or "none"
|
||||
raise PackNotFoundError(
|
||||
f"No language pack found for '{lang_code}'. "
|
||||
f"Available: {available}. "
|
||||
f"Try: pip install foreignthon-{lang_code}"
|
||||
)
|
||||
|
||||
module = packs[lang_code]
|
||||
pack_path: Path = module.get_pack_path()
|
||||
|
||||
with open(pack_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
_validate(data, lang_code)
|
||||
return data
|
||||
|
||||
|
||||
def _validate(data: dict, lang_code: str) -> None:
|
||||
missing = REQUIRED_SECTIONS - data.keys()
|
||||
if missing:
|
||||
raise InvalidPackError(
|
||||
f"Language pack '{lang_code}' is missing sections: {missing}"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
from importlib.resources import files
|
||||
|
||||
def get_pack_path():
|
||||
return files(__name__) / "es.json"
|
||||
|
||||
Reference in New Issue
Block a user