299 lines
15 KiB
Python
Executable File
299 lines
15 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""프로젝트 문서 폴더가 같은 모양인지 본다.
|
|
|
|
프로젝트 하나가 폴더 하나다. 그 안의 배치는 `docs/_templates/` 가 정본이고
|
|
CLAUDE.md 「문서 위치」가 같은 것을 말로 적은 것이다.
|
|
|
|
docs/<프로젝트>/
|
|
├── source/ 밖에서 가져온 원본
|
|
├── state.json · source-index.md
|
|
├── analysis/ · notes/ · checkpoints/
|
|
├── final/ SSOT
|
|
│ ├── document.md
|
|
│ ├── assets/<이름>/ 그림 하나가 폴더 하나. 기록의 assets: file: 도 여기를 가리킨다
|
|
│ ├── .techviz/<이름>/ 그림의 정본
|
|
│ └── evidence/{raw,meta,rendered,browser}
|
|
└── tech-log-studio/
|
|
|
|
python3 scripts/verify-project-layout.py [프로젝트 ...] [--strict] [--samples N]
|
|
|
|
**SVG 는 정본이 아니다.** `.techviz/<이름>/` 없이 남은 그림은 다시 만들 수 없다.
|
|
이 검사기는 그것을 세지만 실패로 만들지는 않는다 — 언제 다시 만들지는 편집 판단이다.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import glob
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
from techlog import Report # noqa: E402
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
EVIDENCE_DIRS = {"raw", "meta", "rendered", "browser"}
|
|
# 분석하는 동안에만 있는 작업 재료. 분석이 끝나면 final/document.md 로 합치고 지운다.
|
|
# 끝난 프로젝트의 폴더는 final/ 과 tech-log-studio/ (밖에서 가져왔으면 source/) 뿐이다
|
|
WORKING_MATERIAL = ("analysis", "notes", "checkpoints", "state.json", "source-index.md")
|
|
# 밖에서 가져올 때만 있는 재료. final/ 이 그 내용을 담으면 원본은 사본이 된다
|
|
IMPORT_MATERIAL = "source"
|
|
def _svg_stems(assets: str) -> list[tuple[str, str]]:
|
|
"""(stem, 상대경로). 그림은 한 곳에만 산다 — 사본을 두는 폴더를 따로 두지 않는다."""
|
|
return [(os.path.basename(path)[:-4], os.path.relpath(path, assets))
|
|
for path in sorted(glob.glob(os.path.join(assets, "**", "*.svg"), recursive=True))]
|
|
|
|
|
|
|
|
|
|
def _load_overlap():
|
|
"""`check-figure-overlap.py` 의 검사 함수. 없으면 None."""
|
|
path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
"check-figure-overlap.py")
|
|
if not os.path.exists(path):
|
|
return None
|
|
spec = importlib.util.spec_from_file_location("check_figure_overlap", path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module.check
|
|
|
|
|
|
def _context_sha(path: str) -> str | None:
|
|
"""`techviz prepare` 가 context 에 적는 것과 같은 해시.
|
|
|
|
**원본 바이트가 아니다.** prepare 는 문서의 관리 블록(`techviz:begin … end`)을 접은
|
|
정규화본을 해싱한다. 원본으로 비교하면 관리 블록이 있는 프로젝트는 그림을 방금 다시
|
|
만들어도 영영 「SSOT 가 바뀌었다」로 남는다. 도구가 없으면 대조하지 않는다.
|
|
"""
|
|
try:
|
|
raw = open(path, encoding="utf-8").read()
|
|
except OSError:
|
|
return None
|
|
home = os.environ.get("TECHVIZ_HOME",
|
|
"/home/donghyeon/workspace/ai-tool/technical-visualization-haness")
|
|
src = os.path.join(home, "src")
|
|
if not os.path.isdir(os.path.join(src, "techviz")):
|
|
return None
|
|
if src not in sys.path:
|
|
sys.path.insert(0, src)
|
|
try:
|
|
from techviz.document import canonicalize_document # noqa: PLC0415
|
|
except ImportError:
|
|
return None
|
|
return hashlib.sha256(canonicalize_document(raw).encode("utf-8")).hexdigest()
|
|
|
|
|
|
def verify(project: str) -> Report:
|
|
rep = Report(project)
|
|
base = os.path.join(ROOT, "docs", project)
|
|
final = os.path.join(base, "final")
|
|
studio = os.path.join(base, "tech-log-studio")
|
|
|
|
# ── SSOT ───────────────────────────────────────────────────────
|
|
if not os.path.exists(os.path.join(final, "document.md")):
|
|
rep.error("final/document.md 가 없다", project)
|
|
return rep
|
|
|
|
# ── 분석 작업 재료 ─────────────────────────────────────────────
|
|
# 분석 중이면 있어야 하고, 끝났으면 final 로 합치고 없어야 한다
|
|
left = [n for n in WORKING_MATERIAL if os.path.exists(os.path.join(base, n))]
|
|
status = None
|
|
state_path = os.path.join(base, "state.json")
|
|
if os.path.exists(state_path):
|
|
try:
|
|
status = json.load(open(state_path, encoding="utf-8")).get("analysisStatus")
|
|
except (json.JSONDecodeError, OSError):
|
|
rep.error("state.json 을 읽지 못했다", project)
|
|
if os.path.isdir(os.path.join(base, "analysis")):
|
|
for name in ("state.json", "source-index.md"):
|
|
if not os.path.exists(os.path.join(base, name)):
|
|
rep.error(f"analysis/ 가 있는데 {name} 이 없다", project)
|
|
if left:
|
|
rep.facts["analysis"] = status or "진행 중"
|
|
if status == "COMPLETE":
|
|
rep.warn("분석이 끝났는데 작업 재료가 남아 있다",
|
|
f"{' · '.join(left)} — final/document.md 로 합치고 지운다")
|
|
imported = os.path.join(base, IMPORT_MATERIAL)
|
|
if os.path.isdir(imported):
|
|
n = sum(1 for _ in glob.iglob(os.path.join(imported, "**", "*"), recursive=True))
|
|
rep.warn("반입 원본이 남아 있다",
|
|
f"source/ {n}개 — final/ 이 그 내용을 담고 있으면 사본이다")
|
|
|
|
# ── 증거 ───────────────────────────────────────────────────────
|
|
evidence = os.path.join(final, "evidence")
|
|
if os.path.isdir(evidence):
|
|
for name in sorted(os.listdir(evidence)):
|
|
if os.path.isdir(os.path.join(evidence, name)) and name not in EVIDENCE_DIRS:
|
|
rep.error("evidence 하위 폴더 이름이 규약 밖이다",
|
|
f"final/evidence/{name} — raw · meta · rendered · browser")
|
|
raw = os.path.join(evidence, "raw")
|
|
counts = {}
|
|
for name in EVIDENCE_DIRS:
|
|
d = os.path.join(evidence, name)
|
|
counts[name] = len(glob.glob(os.path.join(d, "**", "*"), recursive=True)) \
|
|
if os.path.isdir(d) else 0
|
|
rep.facts["evidence"] = counts
|
|
# 6개월 뒤에 파일 이름만으로는 못 읽는다
|
|
for d in sorted(glob.glob(os.path.join(raw, "*"))):
|
|
if os.path.isdir(d) and not os.path.exists(os.path.join(d, "README.txt")):
|
|
rep.warn("evidence/raw 하위 폴더에 README.txt 가 없다",
|
|
os.path.relpath(d, base))
|
|
if counts.get("rendered") and not counts.get("meta"):
|
|
rep.error("터미널 SVG 는 있는데 meta 가 없다",
|
|
"실행한 명령의 원문과 메타데이터가 정본이다")
|
|
elif counts.get("raw") and not counts.get("meta"):
|
|
rep.warn("raw 는 있는데 meta 가 없다",
|
|
f"raw {counts['raw']}건 — command·cwd·executedAt·exitCode·revision 이 없다")
|
|
|
|
# ── 그림 ───────────────────────────────────────────────────────
|
|
ssot_sha = _context_sha(os.path.join(final, "document.md"))
|
|
assets = os.path.join(final, "assets")
|
|
techviz = os.path.join(final, ".techviz")
|
|
# 정본은 그림 이름 폴더다. .techviz 에 놓인 파일은 정본이 아니다
|
|
techviz_sources = {n for n in os.listdir(techviz)
|
|
if os.path.isdir(os.path.join(techviz, n))} \
|
|
if os.path.isdir(techviz) else set()
|
|
if os.path.isdir(assets):
|
|
sources = techviz_sources
|
|
svgs = _svg_stems(assets)
|
|
rep.facts["diagrams"] = {"svg": len(svgs), "techviz": len(sources)}
|
|
overlap = _load_overlap()
|
|
for stem, rel in svgs:
|
|
if stem not in sources:
|
|
rep.warn("techviz 정본이 없는 그림", f"final/assets/{rel}")
|
|
# lint 는 좌표를 안 본다. 상자와 라벨이 서로를 덮는 것은 여기서만 걸린다
|
|
if overlap is not None:
|
|
for hit in overlap(os.path.join(assets, rel)):
|
|
rep.error("그림 안에서 상자와 라벨이 겹친다", f"final/assets/{rel} — {hit}")
|
|
if os.path.dirname(rel) in ("", "diagrams"):
|
|
rep.warn("그림이 이름 폴더로 묶여 있지 않다", f"final/assets/{rel}")
|
|
stems = {s for s, _ in svgs}
|
|
for name in sorted(sources - stems):
|
|
rep.warn("정본만 있고 그림이 없다", f"final/.techviz/{name}")
|
|
|
|
# 관계선이 없고 항목마다 같은 수의 details 를 늘어놓았으면 그것은 표다.
|
|
# 표는 값을 비교하고 그림은 포함·순서·경계처럼 자리로만 보이는 것을 맡는다
|
|
for name in sorted(sources):
|
|
spec_path = os.path.join(techviz, name, "spec.json")
|
|
if not os.path.exists(spec_path):
|
|
continue
|
|
try:
|
|
spec = json.load(open(spec_path, encoding="utf-8"))
|
|
except (ValueError, OSError):
|
|
continue
|
|
# 그림의 근거는 SSOT 다. 기록은 SSOT 의 인용이라 줄 번호가 근거가 되지 못하는데,
|
|
# techviz prepare 는 기록 .md 를 받아도 에러 없이 돈다. 여기서 잡는다
|
|
ctx = spec.get("source_context") or {}
|
|
doc = os.path.basename(str(ctx.get("document") or ""))
|
|
if doc and doc != "document.md":
|
|
rep.error("그림의 근거가 SSOT 가 아니다",
|
|
f"final/.techviz/{name} — source_context.document = {doc}")
|
|
elif ssot_sha and ctx.get("document_sha256") and \
|
|
ctx["document_sha256"] != ssot_sha:
|
|
rep.warn("SSOT 가 바뀐 뒤 그림을 다시 보지 않았다",
|
|
f"final/.techviz/{name}")
|
|
elif ssot_sha is None and ctx.get("document_sha256"):
|
|
rep.warn("그림이 어느 SSOT 를 보고 만들어졌는지 대조하지 못했다",
|
|
f"final/.techviz/{name} — techviz 도구가 없다")
|
|
|
|
nodes = spec.get("nodes") or []
|
|
if spec.get("edges") or len(nodes) < 2:
|
|
continue
|
|
counts = [len(n.get("details") or []) for n in nodes]
|
|
if all(counts) and len(set(counts)) == 1:
|
|
rep.warn("표로 되는 그림", f"final/.techviz/{name} — 관계선이 없고 "
|
|
f"{len(nodes)}항목이 같은 {counts[0]}줄을 늘어놓는다")
|
|
|
|
# ── 기록이 가리키는 그림 ───────────────────────────────────────
|
|
if os.path.isdir(studio):
|
|
wrong = 0
|
|
broken = 0
|
|
records = 0
|
|
cited_figures: set[str] = set()
|
|
cited_evidence: set[str] = set()
|
|
for path in sorted(glob.glob(os.path.join(studio, "*", "*", "*.md"))):
|
|
if os.path.basename(os.path.dirname(os.path.dirname(path))).startswith("_"):
|
|
continue
|
|
records += 1
|
|
text = open(path, encoding="utf-8").read()
|
|
for m in re.finditer(r"^ file: (\S+)$", text, re.M):
|
|
target = os.path.normpath(os.path.join(os.path.dirname(path), m.group(1)))
|
|
stem = (os.path.basename(target)[:-4] if target.endswith(".svg")
|
|
else os.path.basename(target))
|
|
cited_figures.add(stem)
|
|
if not os.path.exists(target):
|
|
broken += 1
|
|
if broken <= 5:
|
|
rep.error("기록이 가리키는 그림이 없다",
|
|
f"{os.path.relpath(path, base)} — {m.group(1)}")
|
|
continue
|
|
# 기록이 가리키는 그림도 다시 만들 수 있어야 한다. 사본을 따로 두면 정본이 둘이 된다
|
|
if stem not in techviz_sources:
|
|
wrong += 1
|
|
rep.warn("기록이 가리키는 그림에 techviz 정본이 없다",
|
|
f"{os.path.relpath(path, base)} — {os.path.basename(target)}")
|
|
for m in re.finditer(r"^ - (\.\./\S*final/evidence/\S+)$", text, re.M):
|
|
cited_evidence.add(
|
|
os.path.normpath(os.path.join(os.path.dirname(path), m.group(1))))
|
|
# ── SSOT 가 만들어 둔 것을 기록이 쓰고 있나 ────────────────────
|
|
# 기록이 하나도 없는 프로젝트는 아직 안 쓴 것이지 안 쓰기로 한 것이 아니다
|
|
if records:
|
|
unused_figures = [rel for stem, rel in _svg_stems(assets)
|
|
if stem not in cited_figures]
|
|
for rel in unused_figures:
|
|
rep.warn("기록이 쓰지 않는 SSOT 그림", f"final/assets/{rel}")
|
|
unused_evidence = [
|
|
p for p in sorted(glob.glob(os.path.join(evidence, "raw", "**", "*"),
|
|
recursive=True))
|
|
if os.path.isfile(p)
|
|
and os.path.basename(p) != "README.txt"
|
|
and p not in cited_evidence]
|
|
for p_ev in unused_evidence:
|
|
rep.warn("기록이 인용하지 않는 raw 증거", os.path.relpath(p_ev, base))
|
|
return rep
|
|
|
|
|
|
def render(rep: Report, samples: int) -> None:
|
|
facts = " · ".join(f"{k}={json.dumps(v, ensure_ascii=False) if isinstance(v, dict) else v}"
|
|
for k, v in rep.facts.items())
|
|
print(f" [{rep.project}] {facts or '—'}")
|
|
for label, bucket, mark in (("error", rep.errors, "✗"), ("warn", rep.warns, "!")):
|
|
for rule, details in sorted(bucket.items(), key=lambda kv: -len(kv[1])):
|
|
print(f" {mark} {label} {len(details):>4} {rule}")
|
|
for d in details[:samples]:
|
|
if d:
|
|
print(f" · {d}")
|
|
if samples and len(details) > samples:
|
|
print(f" … 외 {len(details) - samples}건")
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser(description="프로젝트 문서 폴더 배치를 본다.")
|
|
ap.add_argument("projects", nargs="*")
|
|
ap.add_argument("--samples", type=int, default=3)
|
|
ap.add_argument("--strict", action="store_true")
|
|
args = ap.parse_args()
|
|
|
|
projects = args.projects or sorted(
|
|
name for name in (
|
|
os.path.basename(os.path.dirname(os.path.dirname(p)))
|
|
for p in glob.glob(os.path.join(ROOT, "docs/*/final/document.md"))
|
|
) if not name.startswith("_")
|
|
)
|
|
reports = [verify(p) for p in projects]
|
|
e = sum(r.error_count for r in reports)
|
|
w = sum(r.warn_count for r in reports)
|
|
print(f"PROJECT LAYOUT: {'FAIL' if e or (args.strict and w) else 'PASS'}"
|
|
f" — 프로젝트 {len(reports)} · error {e} · warn {w}")
|
|
for r in reports:
|
|
render(r, args.samples)
|
|
return 1 if e or (args.strict and w) else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|