_build_index.py 2.56 KB
#!/usr/bin/env python3
"""_build_index — 合并所有 skill 的 categories 生成导航首页 index.html

用法:python _build_index.py
在所有 render.py 执行完后运行,读取各 skill 的 common.json 合并生成 index.html。
"""
import json
import os
from string import Template

HERE = os.path.dirname(os.path.abspath(__file__))
SHARED = os.path.join(HERE, "1-tech-implementation-plan", "templates", "shared")

def load_css():
    css_path = os.path.join(SHARED, "design-system.css")
    if os.path.exists(css_path):
        with open(css_path, encoding="utf-8") as f:
            return f.read()
    return ""

# 所有 skill 的 common.json 路径
COMMON_PATHS = [
    os.path.join(HERE, "1-tech-implementation-plan", "data", "common.json"),
    os.path.join(HERE, "2-detailed-design", "data", "common.json"),
    os.path.join(HERE, "3-operation-flow", "data", "common.json"),
    os.path.join(HERE, "4-database-schema", "data", "common.json"),
    os.path.join(HERE, "5-api-spec", "data", "common.json"),
    os.path.join(HERE, "sp-0-req-analysis", "data", "common.json"),
]

def main():
    # 合并所有 categories
    all_cats = []
    project = "未命名项目"
    version = "1.0"
    date = ""
    for p in COMMON_PATHS:
        if os.path.exists(p):
            with open(p, encoding="utf-8") as f:
                data = json.load(f)
            if "allCategories" in data:
                all_cats.extend(data["allCategories"])
            elif data.get("index"):
                all_cats.append(data["index"])
            # 取第一个项目信息
            if project == "未命名项目" and data.get("project"):
                project = data["project"]
                version = data.get("version", "1.0")
                date = data.get("date", "")

    # 按 title 的序号排序(1. 技术方案 → 5. API)
    all_cats.sort(key=lambda c: str(c.get("title", "")))

    # 加载模板
    idx_path = os.path.join(SHARED, "index.html")
    if not os.path.exists(idx_path):
        print(f"[ERROR] 模板不存在: {idx_path}")
        return
    idx_tmpl = Template(open(idx_path, encoding="utf-8").read())
    css = load_css()

    # 渲染
    html = idx_tmpl.safe_substitute(
        CSS=css,
        categories_json=json.dumps(all_cats, ensure_ascii=False),
        project=project,
        version=version,
        date=date,
    )
    out_path = os.path.join(HERE, "index.html")
    with open(out_path, "w", encoding="utf-8") as f:
        f.write(html)
    print(f"[OK] index.html 已生成 ({len(all_cats)} 个分类): {out_path}")

if __name__ == "__main__":
    main()