feat:新增代码注释
This commit is contained in:
@@ -11,36 +11,50 @@ from app.schemas.component_resource import (
|
||||
|
||||
class ComponentProvider:
|
||||
def __init__(self, catalog_path: str | Path | None = None):
|
||||
# 保存可选的目录文件路径,未指定时由查询方法使用项目内的默认目录
|
||||
self.catalog_path = catalog_path
|
||||
|
||||
def query(self, query: ComponentQuery) -> ComponentResult:
|
||||
# TODO 以后迁移数据库,保持组件查询接口不变
|
||||
# 优先使用调用方指定的路径,否则读取当前模块旁的 catalog/components.json
|
||||
path = (
|
||||
Path(self.catalog_path)
|
||||
if self.catalog_path is not None
|
||||
else Path(__file__).resolve().parent / "catalog" / "components.json"
|
||||
)
|
||||
|
||||
# 如果传入的是相对路径,以项目根目录为基准,避免受启动时工作目录影响
|
||||
if not path.is_absolute():
|
||||
path = Path(__file__).resolve().parents[2] / path
|
||||
|
||||
try:
|
||||
# 每次读取当前文件,避免更新目录后仍使用旧缓存
|
||||
# utf-8-sig 同时兼容带 BOM 和不带 BOM 的 UTF-8 文件
|
||||
content = path.read_text(encoding="utf-8-sig")
|
||||
except FileNotFoundError:
|
||||
# 如果目录文件不存在,返回未支持状态和原因,由调用方决定失败处理方式
|
||||
return ComponentResult(
|
||||
status="unsupported",
|
||||
message="尚未配置前端组件目录,请先导出真实组件定义",
|
||||
)
|
||||
|
||||
# 文件损坏或定义不合法直接报错,不能伪装成查无结果
|
||||
catalog = ComponentCatalog.model_validate_json(content)
|
||||
# 如果提供关键词,去除首尾空白并统一大小写,未提供时不启用关键词筛选
|
||||
keyword = (
|
||||
query.keyword.strip().casefold() if query.keyword is not None else None
|
||||
)
|
||||
|
||||
# 收集同时满足所有已提供条件的组件,未设置任何条件时返回全量目录
|
||||
matches = []
|
||||
for component in catalog.components:
|
||||
# 如果指定目录编号,则跳过编号不完全匹配的组件
|
||||
if query.key is not None and component.key != query.key:
|
||||
continue
|
||||
# 如果指定前端组件类型,则跳过类型不完全匹配的组件
|
||||
if query.type is not None and component.type != query.type:
|
||||
continue
|
||||
# 将编号、类型、名称、说明和标签拼成检索文本,并与关键词统一大小写
|
||||
searchable = " ".join(
|
||||
[
|
||||
component.key,
|
||||
@@ -50,9 +64,13 @@ class ComponentProvider:
|
||||
*component.tags,
|
||||
]
|
||||
).casefold()
|
||||
# 如果设置了关键词,但检索文本中不包含该关键词,则跳过当前组件
|
||||
if keyword is not None and keyword not in searchable:
|
||||
continue
|
||||
# 所有筛选条件通过,保留完整组件定义供后续规划和动作生成使用
|
||||
matches.append(component)
|
||||
|
||||
# 根据是否有匹配项区分查询成功和未找到,同时保留目录版本、来源及结果说明
|
||||
return ComponentResult(
|
||||
status="resolved" if matches else "not_found",
|
||||
components=matches,
|
||||
|
||||
Reference in New Issue
Block a user