Files
md2word/transit/config.py
zzy fc6afdea9d refactor(config): 重构配置类以支持动态元数据字段
配置类 ThesisConfig 现在使用 metadata 字典直接透传 TOML 配置,
无需为每个变量单独声明字段。新增模板变量只需修改 TOML 文件,
无需修改 Python 代码。

BREAKING CHANGE: 配置文件结构发生改变,从单独字段改为统一的
metadata 节点。
2026-05-08 23:07:23 +08:00

52 lines
1.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
import tomllib
@dataclass
class ThesisConfig:
"""论文配置数据。
``metadata`` 直接透传 TOML 的 ``[metadata]`` 节,不再为每个变量声明字段。
新增模板变量只需改 TOML无需修改 Python。
"""
metadata: dict = field(default_factory=dict)
# 以下字段仍有业务逻辑,保留为显式属性
title_from_md: bool = True
body_start_keywords: list[str] = field(default_factory=lambda: ["绪论", "引言"])
body_end_keywords: list[str] = field(
default_factory=lambda: ["致谢", "参考文献", "附录"]
)
body_style: str = "Body Text Indent"
level_offset: int = -1
reference_style: str = "列出段落1"
def to_dict(self) -> dict:
"""透传 metadata模板变量来源"""
return self.metadata
def load_config(path: str | Path) -> ThesisConfig:
"""从 TOML 文件加载论文配置。"""
path = Path(path)
with open(path, "rb") as f:
raw = tomllib.load(f)
meta = raw.get("metadata", {})
opts = raw.get("options", {})
return ThesisConfig(
metadata=meta,
title_from_md=opts.get("title_from_md", True),
body_start_keywords=opts.get("body_start_keywords", ["绪论", "引言"]),
body_end_keywords=opts.get(
"body_end_keywords", ["致谢", "参考文献", "附录"]
),
body_style=opts.get("body_style", "Body Text Indent"),
level_offset=opts.get("level_offset", -1),
reference_style=opts.get("reference_style", "列出段落1"),
)