[new] new project
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
import sys
|
||||
import yaml
|
||||
import os
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
# 确保该目录在模块搜索路径中
|
||||
if str(SCRIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
|
||||
# --- 1. Protobuf 依赖导入 ---
|
||||
# 注意:这依赖于 protoc 编译生成的 school_index_pb2.py 文件
|
||||
try:
|
||||
from school_index_pb2 import SchoolIndex, School, Adapter, AdapterCategory
|
||||
except ImportError:
|
||||
print("错误:无法导入 Protobuf 模块 (school_index_pb2)。请确认文件已存在。")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
# --- 2. 工程常量与版本定义 ---
|
||||
# 协议版本:结构大改动时手动递增。
|
||||
PROTOCOL_VERSION = 2
|
||||
|
||||
# YAML 文件路径常量
|
||||
ROOT_INDEX_PATH = Path("index/root_index.yaml")
|
||||
RESOURCES_ROOT = Path("resources")
|
||||
OUTPUT_PB_FILE = "school_index.pb"
|
||||
|
||||
|
||||
# --- 3. 辅助函数:获取版本ID (用于 version_id 字段) ---
|
||||
def get_version_id():
|
||||
"""
|
||||
【统一标准】:只使用精确到毫秒的时间戳作为数据版本ID。
|
||||
"""
|
||||
# 获取当前时间(包含微秒)
|
||||
now = datetime.datetime.now()
|
||||
|
||||
# 格式化时间部分
|
||||
time_str = now.strftime("TIME_%Y%m%d%H%M%S")
|
||||
micro_str = f"{now.microsecond // 1000:03d}"
|
||||
|
||||
return f"{time_str}_{micro_str}"
|
||||
|
||||
|
||||
# --- 4. 辅助函数:YAML 解析逻辑 ---
|
||||
def get_adapter_category_enum(category_str):
|
||||
"""将 YAML 字符串类别映射到 Protobuf 枚举值。"""
|
||||
enum_value = getattr(AdapterCategory, category_str, AdapterCategory.ADAPTER_CATEGORY_UNKNOWN)
|
||||
return enum_value
|
||||
|
||||
def parse_all_yaml():
|
||||
"""解析所有 YAML 文件,返回结构化数据。"""
|
||||
if not ROOT_INDEX_PATH.exists():
|
||||
raise FileNotFoundError(f"根索引文件未找到: {ROOT_INDEX_PATH}")
|
||||
|
||||
with open(ROOT_INDEX_PATH, 'r', encoding='utf-8') as f:
|
||||
root_data = yaml.safe_load(f)
|
||||
|
||||
schools_data = root_data.get('schools', [])
|
||||
parsed_schools = []
|
||||
|
||||
for school_entry in schools_data:
|
||||
# 1. 拼接 adapters.yaml 的路径
|
||||
folder_name = school_entry['resource_folder']
|
||||
adapter_yaml_path = RESOURCES_ROOT / folder_name / "adapters.yaml"
|
||||
|
||||
if not adapter_yaml_path.exists():
|
||||
print(f"警告:未找到适配器配置 {adapter_yaml_path},跳过学校 {school_entry['id']}")
|
||||
continue
|
||||
|
||||
# 2. 读取适配器详情
|
||||
with open(adapter_yaml_path, 'r', encoding='utf-8') as f:
|
||||
adapter_data = yaml.safe_load(f)
|
||||
|
||||
# 将适配器列表添加到学校数据中
|
||||
school_entry['adapters'] = adapter_data.get('adapters', [])
|
||||
parsed_schools.append(school_entry)
|
||||
|
||||
return parsed_schools
|
||||
|
||||
|
||||
# --- 5. 核心构建函数:数据映射与填充 ---
|
||||
def build_protobuf_index(parsed_schools_data):
|
||||
"""将解析后的数据填充到 Protobuf 消息中。"""
|
||||
index = SchoolIndex()
|
||||
# 设置顶层版本信息
|
||||
index.protocol_version = PROTOCOL_VERSION
|
||||
index.version_id = get_version_id()
|
||||
|
||||
for school_data in parsed_schools_data:
|
||||
# 1. 填充 School 消息
|
||||
school_msg = index.schools.add()
|
||||
school_msg.id = school_data.get('id', '')
|
||||
school_msg.name = school_data.get('name', '')
|
||||
school_msg.initial = school_data.get('initial', '')
|
||||
school_msg.resource_folder = school_data.get('resource_folder', '')
|
||||
|
||||
# 2. 填充 Adapter 列表
|
||||
for adapter_data in school_data.get('adapters', []):
|
||||
adapter_msg = school_msg.adapters.add()
|
||||
|
||||
# 填充普通 string 字段
|
||||
adapter_msg.adapter_id = adapter_data.get('adapter_id', '')
|
||||
adapter_msg.adapter_name = adapter_data.get('adapter_name', '')
|
||||
adapter_msg.asset_js_path = adapter_data.get('asset_js_path', '')
|
||||
adapter_msg.description = adapter_data.get('description', '')
|
||||
adapter_msg.maintainer = adapter_data.get('maintainer', '')
|
||||
|
||||
# 填充 optional 字段:只有当字段不为 None 时才设置
|
||||
import_url = adapter_data.get('import_url')
|
||||
if import_url is not None:
|
||||
adapter_msg.import_url = import_url
|
||||
|
||||
# 填充枚举字段
|
||||
category_str = adapter_data.get('category', 'ADAPTER_CATEGORY_UNKNOWN')
|
||||
adapter_msg.category = get_adapter_category_enum(category_str)
|
||||
|
||||
return index
|
||||
|
||||
|
||||
# --- 6. 主执行流程 ---
|
||||
if __name__ == "__main__":
|
||||
|
||||
OUTPUT_FILE = OUTPUT_PB_FILE
|
||||
print(f"目标输出文件: {OUTPUT_FILE}")
|
||||
|
||||
try:
|
||||
print("--- 阶段一:解析 YAML 源文件 ---")
|
||||
parsed_data = parse_all_yaml()
|
||||
|
||||
print("\n--- 阶段二:构建 Protobuf 消息 ---")
|
||||
index_message = build_protobuf_index(parsed_data)
|
||||
|
||||
print(f"Protobuf 协议版本: {index_message.protocol_version}")
|
||||
print(f"数据版本ID: {index_message.version_id}")
|
||||
|
||||
print("\n--- 阶段三:序列化并写入磁盘 ---")
|
||||
# 序列化并写入二进制文件
|
||||
with open(OUTPUT_FILE, "wb") as f:
|
||||
# Protobuf 核心序列化方法
|
||||
f.write(index_message.SerializeToString())
|
||||
|
||||
print(f"\n构建成功!二进制文件已保存到: {OUTPUT_FILE}")
|
||||
print(f"文件大小: {os.path.getsize(OUTPUT_FILE) / 1024:.2f} KB")
|
||||
|
||||
except Exception as e:
|
||||
print(f"构建失败!致命错误: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"required": ["adapters"],
|
||||
"properties": {
|
||||
"adapters": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["adapter_id", "adapter_name", "category", "asset_js_path", "maintainer", "description"],
|
||||
"properties": {
|
||||
"adapter_id": { "type": "string", "description": "唯一标识,建议格式:学校ID_序号" },
|
||||
"adapter_name": { "type": "string", "description": "适配器中文名称" },
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": ["BACHELOR_AND_ASSOCIATE", "POSTGRADUATE", "GENERAL_TOOL"],
|
||||
"description": "分类:本科/专科、研究生、通用工具"
|
||||
},
|
||||
"asset_js_path": { "type": "string", "description": "适配脚本相对路径(如 school.js)" },
|
||||
"import_url": { "type": "string", "description": "系统登录URL(教务系统必填)" },
|
||||
"maintainer": { "type": "string", "description": "维护者 GitHub 用户名或姓名" },
|
||||
"description": { "type": "string", "description": "简要说明" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"required": ["schools"],
|
||||
"properties": {
|
||||
"schools": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["id", "name", "initial", "resource_folder"],
|
||||
"properties": {
|
||||
"id": { "type": "string", "description": "唯一标识,学校保持全大写,建议使用唯一域名" },
|
||||
"name": { "type": "string", "description": "学校或工具的中文全称" },
|
||||
"initial": { "type": "string", "pattern": "^[A-Z]$", "description": "名称首字母(大写),用于排序" },
|
||||
"resource_folder": { "type": "string", "description": "资源文件夹名称,建议与id一致" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
# NO CHECKED-IN PROTOBUF GENCODE
|
||||
# source: school_index.proto
|
||||
# Protobuf Python Version: 6.32.1
|
||||
"""Generated protocol buffer code."""
|
||||
from google.protobuf import descriptor as _descriptor
|
||||
from google.protobuf import descriptor_pool as _descriptor_pool
|
||||
from google.protobuf import runtime_version as _runtime_version
|
||||
from google.protobuf import symbol_database as _symbol_database
|
||||
from google.protobuf.internal import builder as _builder
|
||||
_runtime_version.ValidateProtobufRuntimeVersion(
|
||||
_runtime_version.Domain.PUBLIC,
|
||||
6,
|
||||
32,
|
||||
1,
|
||||
'',
|
||||
'school_index.proto'
|
||||
)
|
||||
# @@protoc_insertion_point(imports)
|
||||
|
||||
_sym_db = _symbol_database.Default()
|
||||
|
||||
|
||||
|
||||
|
||||
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12school_index.proto\x12\x0cschool_index\"b\n\x0bSchoolIndex\x12\x18\n\x10protocol_version\x18\x01 \x01(\x03\x12\x12\n\nversion_id\x18\x02 \x01(\t\x12%\n\x07schools\x18\x03 \x03(\x0b\x32\x14.school_index.School\"u\n\x06School\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0f\n\x07initial\x18\x03 \x01(\t\x12\x17\n\x0fresource_folder\x18\x04 \x01(\t\x12\'\n\x08\x61\x64\x61pters\x18\x05 \x03(\x0b\x32\x15.school_index.Adapter\"\xcc\x01\n\x07\x41\x64\x61pter\x12\x12\n\nadapter_id\x18\x01 \x01(\t\x12\x14\n\x0c\x61\x64\x61pter_name\x18\x02 \x01(\t\x12/\n\x08\x63\x61tegory\x18\x03 \x01(\x0e\x32\x1d.school_index.AdapterCategory\x12\x15\n\rasset_js_path\x18\x04 \x01(\t\x12\x17\n\nimport_url\x18\x05 \x01(\tH\x00\x88\x01\x01\x12\x13\n\x0b\x64\x65scription\x18\x06 \x01(\t\x12\x12\n\nmaintainer\x18\x07 \x01(\tB\r\n\x0b_import_url*o\n\x0f\x41\x64\x61pterCategory\x12\x1c\n\x18\x41\x44\x41PTER_CATEGORY_UNKNOWN\x10\x00\x12\x10\n\x0cGENERAL_TOOL\x10\x01\x12\x1a\n\x16\x42\x41\x43HELOR_AND_ASSOCIATE\x10\x02\x12\x10\n\x0cPOSTGRADUATE\x10\x03\x62\x06proto3')
|
||||
|
||||
_globals = globals()
|
||||
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
|
||||
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'school_index_pb2', _globals)
|
||||
if not _descriptor._USE_C_DESCRIPTORS:
|
||||
DESCRIPTOR._loaded_options = None
|
||||
_globals['_ADAPTERCATEGORY']._serialized_start=462
|
||||
_globals['_ADAPTERCATEGORY']._serialized_end=573
|
||||
_globals['_SCHOOLINDEX']._serialized_start=36
|
||||
_globals['_SCHOOLINDEX']._serialized_end=134
|
||||
_globals['_SCHOOL']._serialized_start=136
|
||||
_globals['_SCHOOL']._serialized_end=253
|
||||
_globals['_ADAPTER']._serialized_start=256
|
||||
_globals['_ADAPTER']._serialized_end=460
|
||||
# @@protoc_insertion_point(module_scope)
|
||||
Reference in New Issue
Block a user