170 lines
7.1 KiB
Python
170 lines
7.1 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""死代码体检:列出「定义了但零调用」的函数 / 类 / 常量。
|
||
|
||
为什么需要:2026-10-01 连续发现两处同类问题——
|
||
① import_job.root_of_xml_text() 定义了却全项目零调用(改解析流程时被遗弃)
|
||
② schema.sql 长期不完整(只改调用方、没回写被调用方)
|
||
这类残留越积越多,最后没人敢删东西。所以做成可重复跑的体检。
|
||
|
||
判定口径(**保守优先**:宁可漏报,不可误报成「可删」)
|
||
- 引用数 = 全项目(.py / .js / .html)里出现的次数,**排除**整行注释
|
||
- HTML 里的 onclick / onchange / oninput 等事件属性算引用(前端函数常只在这里被调用)
|
||
- 定义处自身不计入
|
||
- 出现在字符串 / 路由表 / 动态分发里的,会被计为引用 → 判「被引用」,不敢误判
|
||
|
||
用法:
|
||
python app/tools/deadcode_scan.py # 全项目
|
||
python app/tools/deadcode_scan.py --py # 只看 Python
|
||
python app/tools/deadcode_scan.py --js # 只看 JS
|
||
python app/tools/deadcode_scan.py --md 报告.md # 顺便写 Markdown 报告
|
||
"""
|
||
import io, os, re, sys
|
||
|
||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
assert os.path.basename(ROOT) == "造价审核", "项目根算错了:%s" % ROOT
|
||
|
||
SKIP_DIR = {"__pycache__", "_deprecated", ".git", "node_modules", "uploads", "data", "dist", "build"}
|
||
# 约定上不该判死的东西
|
||
PY_KEEP = {"main", "__init__", "do_GET", "do_POST", "do_PUT", "do_DELETE",
|
||
"log_message", "end_headers", "translate_path", "guess_type", "run"}
|
||
JS_KEEP = {"onWBTab", "WB_TAB", "WB_RAW", "onclick"}
|
||
|
||
|
||
def walk(exts):
|
||
out = []
|
||
for dirpath, dirnames, filenames in os.walk(ROOT):
|
||
dirnames[:] = [d for d in dirnames if d not in SKIP_DIR]
|
||
for fn in filenames:
|
||
if any(fn.endswith(e) for e in exts):
|
||
out.append(os.path.join(dirpath, fn))
|
||
return sorted(out)
|
||
|
||
|
||
def strip_comments(text, lang):
|
||
"""去掉整行注释(保守:行内注释保留,避免把真引用误判成死代码)"""
|
||
lines = []
|
||
for ln in text.split("\n"):
|
||
s = ln.strip()
|
||
if lang == "py" and s.startswith("#"):
|
||
lines.append("")
|
||
elif lang == "js" and (s.startswith("//") or s.startswith("*") or s.startswith("/*")):
|
||
lines.append("")
|
||
else:
|
||
lines.append(ln)
|
||
return "\n".join(lines)
|
||
|
||
|
||
def collect_files():
|
||
py = [p for p in walk((".py",))]
|
||
js = [p for p in walk((".js",))]
|
||
html = [p for p in walk((".html",))]
|
||
return py, js, html
|
||
|
||
|
||
def read(p):
|
||
try:
|
||
return io.open(p, encoding="utf-8").read()
|
||
except Exception:
|
||
return ""
|
||
|
||
|
||
def py_defs(src):
|
||
"""返回 [(名称, 行号, 类型)]"""
|
||
out = []
|
||
for m in re.finditer(r"^(\s*)(def|class)\s+(\w+)", src, re.M):
|
||
kind = "函数" if m.group(2) == "def" else "类"
|
||
out.append((m.group(3), src[:m.start()].count("\n") + 1, kind))
|
||
# 模块级常量:全大写(含下划线),至少 3 字符,排除常见内置
|
||
for m in re.finditer(r"^([A-Z][A-Z0-9_]{2,})\s*=", src, re.M):
|
||
out.append((m.group(1), src[:m.start()].count("\n") + 1, "常量"))
|
||
return out
|
||
|
||
|
||
def js_defs(src):
|
||
out = []
|
||
for m in re.finditer(r"^\s*(?:async\s+)?function\s+(\w+)\s*\(", src, re.M):
|
||
out.append((m.group(1), src[:m.start()].count("\n") + 1, "JS函数"))
|
||
for m in re.finditer(r"^\s*(?:var|let|const)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:function|async\s+function|\()", src, re.M):
|
||
out.append((m.group(1), src[:m.start()].count("\n") + 1, "JS函数"))
|
||
return out
|
||
|
||
|
||
def main():
|
||
only = "--py" if "--py" in sys.argv else ("--js" if "--js" in sys.argv else None)
|
||
md_path = None
|
||
if "--md" in sys.argv:
|
||
i = sys.argv.index("--md")
|
||
if i + 1 < len(sys.argv):
|
||
md_path = sys.argv[i + 1]
|
||
|
||
py_files, js_files, html_files = collect_files()
|
||
# 语料:去掉整行注释后的全部文本
|
||
corpus = []
|
||
for p in py_files:
|
||
corpus.append(strip_comments(read(p), "py"))
|
||
for p in js_files:
|
||
corpus.append(strip_comments(read(p), "js"))
|
||
for p in html_files:
|
||
corpus.append(read(p)) # HTML 里的 onclick 必须算引用,不去注释
|
||
all_text = "\n".join(corpus)
|
||
|
||
findings = []
|
||
if only in (None, "--py"):
|
||
for p in py_files:
|
||
src = read(p)
|
||
clean = strip_comments(src, "py")
|
||
for name, ln, kind in py_defs(src):
|
||
if name in PY_KEEP or name.startswith("__") and name != "__init__":
|
||
continue
|
||
if name.endswith("__"):
|
||
continue
|
||
# 定义处自身 1 次;若只出现这 1 次 → 零调用
|
||
total = len(re.findall(r"\b" + re.escape(name) + r"\b", all_text))
|
||
mine = len(re.findall(r"\b" + re.escape(name) + r"\b", clean))
|
||
if total <= 1 and mine <= 1:
|
||
findings.append((os.path.relpath(p, ROOT), ln, kind, name, total))
|
||
if only in (None, "--js"):
|
||
for p in js_files + html_files:
|
||
src = read(p)
|
||
clean = strip_comments(src, "js")
|
||
for name, ln, kind in js_defs(src):
|
||
if name in JS_KEEP:
|
||
continue
|
||
total = len(re.findall(r"\b" + re.escape(name) + r"\b", all_text))
|
||
mine = len(re.findall(r"\b" + re.escape(name) + r"\b", clean))
|
||
if total <= 1 and mine <= 1:
|
||
findings.append((os.path.relpath(p, ROOT), ln, kind, name, total))
|
||
|
||
findings.sort(key=lambda x: (x[0], x[1]))
|
||
print("=" * 74)
|
||
print("死代码体检(定义了但全项目零调用)")
|
||
print("=" * 74)
|
||
print("扫描范围:%d 个 .py / %d 个 .js / %d 个 .html" % (len(py_files), len(js_files), len(html_files)))
|
||
print("(已排除 __pycache__ / _deprecated / data / uploads)\n")
|
||
if not findings:
|
||
print(" 没有发现零调用的定义。")
|
||
return 0
|
||
print("%-38s %-6s %-8s %s" % ("文件", "行", "类型", "名称"))
|
||
print("-" * 74)
|
||
for f, ln, kind, name, n in findings:
|
||
print("%-38s %-6s %-8s %s" % (f[:38], ln, kind, name))
|
||
print("\n合计 %d 项" % len(findings))
|
||
print("\n⚠️ 判定说明:引用数按「全项目出现次数」统计,已排除整行注释。")
|
||
print(" 出现在字符串/动态分发里的会算作引用(保守,不误判为可删)。")
|
||
print(" 删除前请人工确认一次,尤其是可能被外部脚本或将来功能用到的。")
|
||
|
||
if md_path:
|
||
with io.open(md_path, "w", encoding="utf-8") as fh:
|
||
fh.write("# 死代码体检报告\n\n")
|
||
fh.write("扫描范围:%d 个 .py / %d 个 .js / %d 个 .html\n\n" % (len(py_files), len(js_files), len(html_files)))
|
||
fh.write("| 文件 | 行 | 类型 | 名称 | 引用数 |\n|---|---|---|---|---|\n")
|
||
for f, ln, kind, name, n in findings:
|
||
fh.write("| %s | %s | %s | `%s` | %d |\n" % (f, ln, kind, name, n))
|
||
print("\n报告已写入:%s" % md_path)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|