wdb/d_wiki/config.py
2026-05-28 19:02:16 +08:00

60 lines
1.9 KiB
Python

from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from .yaml_compat import safe_load
@dataclass(frozen=True)
class KnowledgeBaseConfig:
name: str
root: Path
source_type: str
aliases_path: Path | None
queries_dir: Path | None
@dataclass(frozen=True)
class DWikiConfig:
path: Path
knowledge_bases: dict[str, KnowledgeBaseConfig]
def default_config_path() -> Path:
return Path(os.environ.get("D_WIKI_CONFIG", Path.cwd() / "d-wiki.yml")).expanduser()
def load_config(path: Path | None = None) -> DWikiConfig:
config_path = (path or default_config_path()).expanduser().resolve()
data = safe_load(config_path.read_text(encoding="utf-8")) or {}
raw_kbs = data.get("knowledge_bases")
if not isinstance(raw_kbs, dict):
raise ValueError("D_WIKI_CONFIG_MISSING_KNOWLEDGE_BASES")
bases: dict[str, KnowledgeBaseConfig] = {}
for name, raw in raw_kbs.items():
if not isinstance(raw, dict):
raise ValueError(f"D_WIKI_KB_INVALID: {name}")
root = Path(str(raw.get("root", ""))).expanduser()
if not root.is_absolute():
root = (config_path.parent / root).resolve()
aliases_path = _optional_path(config_path.parent, raw.get("aliases"))
queries_dir = _optional_path(config_path.parent, raw.get("queries"))
bases[str(name)] = KnowledgeBaseConfig(
name=str(name),
root=root,
source_type=str(raw.get("source_type", "markdown")),
aliases_path=aliases_path,
queries_dir=queries_dir,
)
return DWikiConfig(path=config_path, knowledge_bases=bases)
def _optional_path(base: Path, value: Any) -> Path | None:
if not value:
return None
path = Path(str(value)).expanduser()
return path if path.is_absolute() else (base / path).resolve()