# -*- coding: utf-8 -*- """代码地图生成 —— 省 token 铁律7 配套(2026-10-26 主人定)。 扫三大文件(common.js / workbench.html / api_server.py)的全部函数, 生成根目录 `代码地图.md`:文件 → 函数 → 行号 → 一句话说明。 定位先查地图、一次 sed 命中;增删函数后收尾重跑本脚本刷新: python test/代码地图生成.py 只读源码、只写 代码地图.md,不碰其他任何文件。 """ import io import os import re import sys import datetime ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) OUT = os.path.join(ROOT, "代码地图.md") FILES = [ ("CostReview/app/ui/common.js", "js", "前台后台共用层(渲染/编辑/树/缓存)"), ("CostReview/app/ui/workbench.html", "js", "工作台页面(脚本块)"), ("CostReview/app/server/api_server.py", "py", "后台 API 服务(全部接口)"), ] DESC_MAX = 60 RE_JS = re.compile( r"^\s*(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(" # function f( / async function f( r"|^\s*([A-Za-z_$][\w$]*)\s*:\s*(?:async\s+)?function\s*\(" # f: function( / f: async function( r"|^\s*window\.([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?function" # window.f = function ) RE_PY_DEF = re.compile(r"^(\s*)def\s+([A-Za-z_]\w*)\s*\(") RE_PY_CLS = re.compile(r"^class\s+([A-Za-z_]\w*)") def js_desc(lines, i): """向上找最近的注释行(// 或 块注),最多回看 4 行。""" for j in range(i - 1, max(-1, i - 5), -1): t = lines[j].strip() if not t: continue if t.startswith("//") or t.startswith("/*") or t.startswith("*"): return t.lstrip("/* ").rstrip("*/ \t")[:DESC_MAX] break return "" def py_desc(lines, i): for j in range(i - 1, max(-1, i - 5), -1): t = lines[j].strip() if not t: continue if t.startswith("#") and not t.startswith("#!"): return t.lstrip("# ")[:DESC_MAX] break # 没有上行注释就取 docstring 第一句 m = re.search(r'"""([^"\n]{6,})', lines[i] + "".join(lines[i + 1:i + 3])) return m.group(1).strip()[:DESC_MAX] if m else "" def scan_js(path): """返回 [(行号, 函数名, 说明)];html 只扫