Files
tjhlp-gitea/scripts/src/tjhlp/config.py
T
admin 68fb567cb3 feat: Issue 模板引导链接改指课程官网, 平台地址改由 public_url 注入
- 两个 config.yaml 的 contact_links 从 example.com 换成真实入口:
  官网《学会提问》/ 课程官网 / 平台提问速查, 让答疑平台与官网互相导流
- 模板支持 {{BASE_URL}}/{{ORG}}/{{REPO}} 占位符, 推送时替换,
  换学期建新组织不用改模板; 未配置时保留占位符并告警而不是推坏链接
- scripts: 新增 gitea.public_url(对外地址, 与 CLI 用的 url 区分),
  utils.web_base_url()/render_template_placeholders() 及单元测试
2026-09-11 17:07:11 +08:00

86 lines
2.4 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 = ""
# 面向用户的访问地址(Apache 反代后的地址, 如 https://cpp.tongji.sh/QA)。
# url 是 CLI 调 API 用的地址, 可能带内部端口, 不能直接写进 Issue Template 等
# 给同学看的链接里; 留空时回退到 url。
public_url: 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