41 lines
1.3 KiB
Python
41 lines
1.3 KiB
Python
import importlib.util
|
|
from pathlib import Path
|
|
|
|
import yaml
|
|
|
|
|
|
class Capability:
|
|
def __init__(self, name: str, contract: dict, impl_module, base_dir: Path):
|
|
self.name = name
|
|
self.contract = contract
|
|
self.impl = impl_module
|
|
self.base_dir = base_dir
|
|
|
|
|
|
def _load_impl(impl_path: Path):
|
|
spec = importlib.util.spec_from_file_location(impl_path.stem, impl_path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def load_registry(capabilities_dir) -> dict:
|
|
"""扫描 capabilities/*.yaml,加载契约文件及对应实现,返回 {能力名: Capability}。
|
|
|
|
新增能力只需在此目录下新增一份 yaml + impl/*.py,无需修改本文件。
|
|
"""
|
|
root = Path(capabilities_dir)
|
|
project_root = root.parent
|
|
registry = {}
|
|
|
|
for yaml_file in sorted(root.glob("*.yaml")):
|
|
contract = yaml.safe_load(yaml_file.read_text(encoding="utf-8"))
|
|
name = contract["name"]
|
|
impl_path = (project_root / contract["implementation"]).resolve()
|
|
if not impl_path.exists():
|
|
raise FileNotFoundError(f"能力 '{name}' 的实现文件不存在: {impl_path}")
|
|
module = _load_impl(impl_path)
|
|
registry[name] = Capability(name, contract, module, root)
|
|
|
|
return registry
|