42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
"""Content-type contract and extension discovery."""
|
|
|
|
from dataclasses import dataclass
|
|
from importlib import import_module
|
|
from pkgutil import iter_modules
|
|
|
|
from . import extensions
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ContentType:
|
|
name: str
|
|
required: tuple[str, ...]
|
|
optional: tuple[str, ...] = ()
|
|
|
|
def validate(self, fields):
|
|
if not isinstance(fields, dict):
|
|
raise ValueError("fields must be an object")
|
|
if fields.keys() - set(self.required + self.optional):
|
|
raise ValueError("unknown field for " + self.name)
|
|
for key in self.required:
|
|
if key not in fields:
|
|
raise ValueError("missing field: " + key)
|
|
for key, value in fields.items():
|
|
if not isinstance(value, str) or not value.strip():
|
|
raise ValueError(key + " must be a non-empty string")
|
|
|
|
|
|
def discover(package=extensions):
|
|
types = {}
|
|
for module in iter_modules(package.__path__):
|
|
if module.name.startswith("_"):
|
|
continue
|
|
path = package.__name__ + "." + module.name
|
|
definition = getattr(import_module(path), "content_type", None)
|
|
if not isinstance(definition, ContentType):
|
|
raise ValueError(path + " must export a ContentType as content_type")
|
|
if definition.name in types:
|
|
raise ValueError("duplicate content type: " + definition.name)
|
|
types[definition.name] = definition
|
|
return types
|