SHA256
forked from course-team/tjhlp-gitea
82 lines
2.1 KiB
Python
82 lines
2.1 KiB
Python
"""配置管理: Dynaconf 加载 + Pydantic 校验"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
from dynaconf import Dynaconf
|
|
from pydantic import AliasGenerator, BaseModel, ConfigDict, HttpUrl, SecretStr, field_validator
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Dynaconf 实例(在 scripts/ 目录下查找配置文件)
|
|
# ---------------------------------------------------------------------------
|
|
_SCRIPTS_DIR = Path(__file__).resolve().parent.parent.parent
|
|
|
|
settings = Dynaconf(
|
|
envvar_prefix="TJHLP",
|
|
settings_files=[
|
|
str(_SCRIPTS_DIR / "settings.toml"),
|
|
str(_SCRIPTS_DIR / ".secrets.toml"),
|
|
],
|
|
environments=True,
|
|
load_dotenv=True,
|
|
merge_enabled=True,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Pydantic 强类型配置模型
|
|
# ---------------------------------------------------------------------------
|
|
class LabelDef(BaseModel):
|
|
"""预定义 Label"""
|
|
|
|
name: str
|
|
color: str
|
|
description: str = ""
|
|
|
|
@field_validator("color")
|
|
@classmethod
|
|
def color_must_be_hex(cls, v: str) -> str:
|
|
v = v.lstrip("#")
|
|
if len(v) not in (3, 6) or not all(c in "0123456789abcdefABCDEF" for c in v):
|
|
raise ValueError(f"无效的颜色值: #{v}")
|
|
return f"#{v}"
|
|
|
|
|
|
class GiteaConfig(BaseModel):
|
|
"""Gitea 连接配置"""
|
|
|
|
model_config = ConfigDict(
|
|
alias_generator=AliasGenerator(validation_alias=str.upper),
|
|
populate_by_name=True,
|
|
)
|
|
|
|
url: HttpUrl
|
|
token: SecretStr
|
|
email_domain: str = "tongji.edu.cn"
|
|
default_org: str = ""
|
|
labels: list[LabelDef] = []
|
|
|
|
|
|
class Config(BaseModel):
|
|
"""总配置模型"""
|
|
|
|
model_config = ConfigDict(
|
|
alias_generator=AliasGenerator(
|
|
validation_alias=str.upper,
|
|
),
|
|
populate_by_name=True,
|
|
)
|
|
|
|
gitea: GiteaConfig
|
|
|
|
|
|
def get_config() -> Config:
|
|
"""获取完整配置"""
|
|
return Config.model_validate(settings.to_dict())
|
|
|
|
|
|
def get_gitea_config() -> GiteaConfig:
|
|
"""从 Dynaconf 加载并校验 Gitea 配置"""
|
|
return get_config().gitea
|