1
0

refactor: 重构外部模板系统,改为单文件模板库模式

主要变更:
- 将 templates_dir 参数改为 template_file,支持单个模板库 YAML 文件
- 添加模板库 YAML 验证功能
- 为模板添加 base_dir 支持,正确解析相对路径资源
- 内联模板与外部模板同名时改为警告(内联优先)
- 移除模板缓存机制,直接使用模板库字典
- 更新所有相关测试以适配新的模板加载方式

此重构简化了模板管理,使模板资源的路径解析更加清晰明确。
This commit is contained in:
2026-03-05 13:26:29 +08:00
parent bd12fce14b
commit f1aae96a04
27 changed files with 2141 additions and 1988 deletions

View File

@@ -139,33 +139,60 @@ def validate_templates_yaml(data, file_path=""):
if 'templates' in data:
if not isinstance(data['templates'], dict):
raise YAMLError(f"{file_path}: 'templates' 必须是一个字典")
# 验证每个内联模板的结构
for template_name, template_data in data['templates'].items():
# 构建模板位置路径
template_location = f"{file_path}.templates.{template_name}"
# 验证模板是字典
if not isinstance(template_data, dict):
raise YAMLError(f"{template_location}: 模板定义必须是字典")
# 验证必需的 elements 字段
if 'elements' not in template_data:
raise YAMLError(f"{template_location}: 缺少必需字段 'elements'")
if not isinstance(template_data['elements'], list):
raise YAMLError(f"{template_location}: 'elements' 必须是一个列表")
# 验证可选的 vars 字段
if 'vars' in template_data:
if not isinstance(template_data['vars'], list):
raise YAMLError(f"{template_location}: 'vars' 必须是一个列表")
# 验证每个变量定义
for i, var_def in enumerate(template_data['vars']):
if not isinstance(var_def, dict):
raise YAMLError(f"{template_location}.vars[{i}]: 变量定义必须是字典")
# 验证必需的 name 字段
if 'name' not in var_def:
raise YAMLError(f"{template_location}.vars[{i}]: 缺少必需字段 'name'")
def validate_template_library_yaml(data, file_path=""):
"""
验证模板库文件结构(外部模板库)
Args:
data: 解析后的 YAML 数据
file_path: 文件路径(用于错误消息)
Raises:
YAMLError: 结构验证失败
"""
if not isinstance(data, dict):
raise YAMLError(f"{file_path}: 模板库文件必须是一个字典对象")
# 验证必需的 templates 字段
if 'templates' not in data:
raise YAMLError(f"{file_path}: 缺少必需字段 'templates'")
if not isinstance(data['templates'], dict):
raise YAMLError(f"{file_path}: 'templates' 必须是字典")
# 递归验证每个模板的结构
for template_name, template_data in data['templates'].items():
template_location = f"{file_path}.templates.{template_name}"
validate_template_yaml(template_data, template_location)