예외 목록은 줄기만 해야 하는데 빈틈이 있다. check-docs.py는 목록의 줄이 FROZEN에 있는지만 보고, FROZEN의 지문이 목록에 있는지는 보지 않는다. 그래서 번역해서 지운 줄의 지문이 FROZEN에 남고, 같은 줄을 다시 더해도 검사가 통과한다. 기준 커밋 03a313ed에서 이미 FROZEN 217개 중 9개가 목록에 줄이 없었다(앞 단계의 이름 바꾸기에서 남은 것). - run()이 FROZEN - (목록 줄의 지문)을 실패로 낸다. --only와 상관없이 돈다(목록의 줄이 FROZEN에 있는지 보는 검사와 같다). - 합친 트리의 목록이 비었으므로 FROZEN에서 217개를 모두 뺐다. 이제 목록에 어떤 줄을 더해도 실패한다. - 설명(스크립트 머리, 예외 목록 머리 주석, docs/README.md 「문서 검사」)에 「줄을 지우면 FROZEN에서 그 지문도 뺀다」를 더했다. 스크립트 머리의 「넷 모두」를 지금의 여섯 검사로 고쳤다. 버린 대안: FROZEN을 그대로 두고 자기 시험만 더하기. 실제 검사(PR workflow)는 자기 시험과 따로 돌므로, 목록과 FROZEN이 어긋난 트리가 check-docs.py만으로는 통과한다. 검사 자신이 막아야 한다. 자기 시험(scripts/tests/test_check_docs.py)에 셋을 더했다. - test_a_frozen_fingerprint_whose_line_was_removed_fails: 고장 낸 입력 (빈 목록 + 지문 하나)이 language·head 어느 검사로 돌려도 실패한다. - test_a_removed_line_added_back_fails_once_its_fingerprint_is_gone: 지문을 뺀 뒤 줄을 다시 더하면 「기준선에 없는 예외다」로 실패하고, 남은 줄에는 고아 지문 오류가 나지 않는다. - test_every_frozen_fingerprint_has_its_line_in_the_real_exception_list: 실제 FROZEN과 실제 목록이 맞는다. 조건을 끈 변이 시험(사본에 문자열 치환, 자기 시험 실행): - 고아 지문 검사를 지움 → rc=1, 첫째 시험 실패 - FROZEN을 03a313ed의 217개로 되돌림 → rc=1, 셋째 시험 실패. 실제 트리의 check-docs.py도 고아 지문 217건으로 실패한다. - 둘 다(바꾸기 전 코드) → rc=1, 첫째·셋째 시험 실패 검증(노트북): check-docs.py OK(여섯 검사 걸림 0), 자기 시험 68 OK, check-work-docs.py OK.
641 lines
29 KiB
Python
Executable File
641 lines
29 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""문서 검사 여섯: 언어, 기록의 머리 블록, 참조, 복사한 숫자, 문서 지도, 루트 README 절. 하나라도 걸리면 rc=1이다.
|
||
|
||
규칙의 정본은 design-docs `conventions/docs-system.md`이고, 이 repo의 적용은 `docs/README.md`
|
||
「문서 수명과 언어」다. 이 스크립트는 그 규칙 중 기계로 볼 수 있는 것만 본다.
|
||
|
||
language 살아 있는 문서(기록이 아닌 .md)는 한국어다. 판정은 보고 언어 훅 H11과 같다:
|
||
코드·명령·인용·링크·URL·경로·파일 이름을 빼고, 영어 낱말이 3개 이상이고
|
||
한글 덩어리 비율이 0.3 미만이면 영어다.
|
||
head 기록(docs/design, docs/history, docs/adr)의 .md는 맨 위에
|
||
머리 블록이 있다. 상태는 종류별 고정 어휘, 작성일은 날짜, 요약은 한국어, 현재
|
||
정본과 대체됨이 가리키는 경로는 지금 있다.
|
||
reference 살아 있는 문서의 인라인 코드 안 repo 경로(src/, docs/, scripts/, compose/, .github/로
|
||
시작. 2026-11-07에 지운 infra/ 아래 경로도 본다)와 Gradle 경로(:a:b)가 지금 트리와
|
||
registry에 있다. 코드 블록과 「이력」으로 시작하는 인용 블록은 건너뛴다. 마크다운
|
||
링크는 lychee와 check-work-docs.py --links가 본다.
|
||
number 살아 있는 문서가 정본이 정하는 숫자를 복사하지 않는다: Spring Boot 버전, leaf 개수.
|
||
map docs/README.md의 문서 지도가 지금 있는 문서 폴더를 모두 덮는다. 지도는 표의 첫 칸에 적은
|
||
`폴더/`다. docs/ 바로 아래 폴더가 대상이고, 파일 없이 폴더만 가진 묶음 폴더(history/)는
|
||
그 아래 폴더가 대신한다. 지도에 있지만 없는 폴더도 실패다.
|
||
readme 루트 README.md가 정해진 절을 정해진 순서로 가진다: 첫 줄의 제목, 그 아래 한 문단, 그리고
|
||
README_SECTIONS의 ## 제목. 그 사이에 다른 절이 있어도 된다.
|
||
|
||
소스 세트의 resources 폴더 아래 .md(src/**/src/<세트>/resources/)는 시험 입력이나 실행 자원이라 문서로
|
||
보지 않는다.
|
||
|
||
예외 목록(scripts/check-docs-exceptions.txt)은 줄기만 한다.
|
||
- 목록의 줄은 아래 FROZEN(2026-11-07 기준선의 지문)에 있어야 한다. 목록에 새 줄을 더하면 실패한다.
|
||
- FROZEN의 지문은 목록에 그 줄이 있어야 한다. 줄을 지우면 같은 변경에서 FROZEN에서 그 지문도 뺀다.
|
||
남겨 두면 실패한다. 남은 지문은 지운 줄을 다시 더하는 길이 되기 때문이다.
|
||
- 목록의 줄이 더는 걸리지 않으면(번역했거나 고쳤으면) 그 줄을 지우라고 실패한다.
|
||
- FROZEN을 늘리는 것은 규칙을 바꾸는 일이다. 소유자 결정 없이 하지 않는다. 파일을 옮겨 경로만
|
||
바뀐 줄은 FROZEN에서 옛 지문을 새 지문으로 바꾼다. 지문은 그 줄(탭 포함)의 sha256 앞 16자다:
|
||
python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.argv[1].encode()).hexdigest()[:16])' "<줄>"
|
||
- 2026-11-07 번역 단계에서 목록의 줄을 모두 지워 목록과 FROZEN이 비었다.
|
||
|
||
python3 scripts/check-docs.py # 여섯 모두
|
||
python3 scripts/check-docs.py --only head # 하나만 (language, head, reference, number, map, readme)
|
||
python3 -m unittest discover -s scripts/tests # 이 검사의 시험
|
||
|
||
Gradle 밖에 둔다. 빌드는 문서를 파싱하지 않는다(AGENTS.md 「Gradle 정책 권위」).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import datetime
|
||
import hashlib
|
||
import json
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
|
||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||
EXCEPTIONS_FILE = "scripts/check-docs-exceptions.txt"
|
||
REGISTRY_FILE = "src/config/architecture/modules.json"
|
||
CHECKS = ("language", "head", "reference", "number", "map", "readme")
|
||
|
||
# 기록: 본문은 쓴 때의 원문이다. 머리 블록만 고친다. 종류는 폴더가 정한다.
|
||
RECORD_KINDS = [
|
||
("docs/design/", "설계서"),
|
||
("docs/history/plans/evidence/", "증거"),
|
||
("docs/history/plans/", "계획서"),
|
||
("docs/history/packages/", "납품 패키지"),
|
||
("docs/history/evidence/", "증거"),
|
||
("docs/history/study/", "학습 문서"),
|
||
("docs/adr/", "결정 기록"),
|
||
]
|
||
# 리뷰도 기록이다. 머리 블록은 아직 요구하지 않는다(docs/README.md).
|
||
NOT_LIVING = ("docs/design/", "docs/history/", "docs/reviews/")
|
||
DECISION_PREFIXES = ("docs/adr/",)
|
||
# 살아 있는 문서 중 지운 것을 일부러 적는 곳: 제거 표, 파생 서비스용 변경 안내, 매뉴얼 규칙의 근거 기록.
|
||
# 참조·숫자 검사는 이 문서들을 보지 않는다(docs/README.md 「문서와 코드를 같은 변경에서 고친다」).
|
||
HISTORY_HOLDERS = ("docs/capability-status.md", "docs/upgrade/", "docs/work/evidence.md")
|
||
|
||
STATUS = {
|
||
"설계서": ("제안", "채택", "구현됨", "보류", "폐기", "대체됨", "확인 안 함"),
|
||
"결정 기록": ("제안", "채택", "채택(보완)", "폐기", "대체됨"),
|
||
"계획서": ("실행 중", "끝남", "중단", "대체됨", "확인 안 함"),
|
||
"납품 패키지": ("보관",),
|
||
"증거": ("보관",),
|
||
"학습 문서": ("보관",),
|
||
}
|
||
HEAD_START = "<!-- 머리 블록: 이 블록을 빼면 원문이다. 형식은 docs/README.md 「기록 문서의 머리 블록」 -->"
|
||
HEAD_END = "<!-- 머리 블록 끝 -->"
|
||
RECORD_LABEL = "> **기록 · {kind}** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다."
|
||
DECISION_LABEL = "> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다."
|
||
HEAD_FIELDS = ("상태", "작성일", "요약", "현재 정본")
|
||
HEAD_OPTIONAL = ("대체", "대체됨")
|
||
HEAD_SEARCH_LINES = 20
|
||
|
||
# 문서가 아닌 .md: 소스 세트의 resources 폴더 아래 파일은 테스트가 읽는 입력이나 실행 자원이다.
|
||
NOT_DOCUMENT = re.compile(r"/src/[A-Za-z]+/resources/")
|
||
|
||
# 문서 지도(K5)와 루트 README(K6). 절 목록의 정본은 design-docs `conventions/docs-system.md` 6.1절이다.
|
||
MAP_FILE = "docs/README.md"
|
||
DOCS_ROOT = "docs/"
|
||
README_FILE = "README.md"
|
||
README_SECTIONS = ("프로젝트 구조", "시작하기", "기능 켜고 끄기", "문서 지도", "검증", "새 서비스로 시작하기",
|
||
"규칙과 기여")
|
||
|
||
# 2026-11-07 기준선. 예외 목록의 줄마다 sha256 앞 16자. 늘리지 않는다(맨 위 설명).
|
||
# 처음 217개였다. 2026-11-07 번역 단계에서 목록이 비어 모두 뺐다.
|
||
FROZEN: frozenset[str] = frozenset()
|
||
|
||
# --- 언어 판정: ~/.claude/hooks/guard_report.py의 H11과 같은 규칙(design-docs conventions/delegation-loop.md 11절)
|
||
MIN_ENGLISH = 3
|
||
MIN_KOREAN_SHARE = 0.3
|
||
HANGUL = re.compile(r"[가-힣]+")
|
||
FENCE = re.compile(r"^[ \t]*(`{3,}|~{3,})")
|
||
INLINE = re.compile(r"(`+)(?:(?!\1).)+?\1", re.S)
|
||
MDLINK = re.compile(r"\[[^\]\n]*\]\([^)\s]*\)")
|
||
URL = re.compile(r"(?:\b[a-z][a-z0-9+.-]*://|\bwww\.)\S+", re.I)
|
||
PATHLIKE = re.compile(r"[^\s가-힣]*[/\\][^\s가-힣]*")
|
||
FILELIKE = re.compile(r"[^\s가-힣]+\.[A-Za-z]{1,10}(?::\d+)*(?![A-Za-z])")
|
||
QUOTED = re.compile(r"\"[^\"\n]*\"|“[^”\n]*”")
|
||
TOKEN = re.compile(r"[^\s가-힣]+")
|
||
WORD = re.compile(r"^[(\[\"'“‘*_]*[A-Za-z][a-z]*(?:['’][a-z]+)?(?:-[a-z]+)*[)\]\"'”’*_.,;:!?…]*$")
|
||
|
||
# --- 참조
|
||
PATH_ROOTS = ("src/", "docs/", "scripts/", "compose/", "infra/", ".github/")
|
||
PLACEHOLDER = re.compile(r"[*?<>{}\[\]$…]|\.\.\.|YYYY|NNN|[가-힣]")
|
||
LINE_SUFFIX = re.compile(r"(?::\d+(?:[-,]\d+)*)+$")
|
||
# 모든 leaf에 있는 소스 세트 이름(src/test, src/main/java)은 어느 leaf의 것인지 문장이 정한다.
|
||
SOURCE_SET = re.compile(r"^src/[A-Za-z]+(?:/(?:java|resources|proto|kotlin|groovy))?/?$")
|
||
GRADLE_PATH = re.compile(r"^:[A-Za-z][\w-]*(?::[A-Za-z][\w-]*)+$")
|
||
HISTORY_QUOTE = re.compile(r"^\s*>\s*(?:\*\*)?이력")
|
||
|
||
# --- 복사한 숫자
|
||
COPIED_NUMBERS = [
|
||
("Spring Boot 버전", re.compile(r"Spring Boot \d+\.\d+\.\d+")),
|
||
("leaf 개수", re.compile(r"\b\d+\s*개의?\s*leaf|\bleaf\s*\d+\s*개|\b\d+\s+(?:registered\s+)?lea(?:f|ves)\b",
|
||
re.I)),
|
||
]
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Problem:
|
||
check: str
|
||
path: str
|
||
key: str
|
||
message: str
|
||
line: int = 0
|
||
|
||
def exception_line(self) -> str:
|
||
return "\t".join(part for part in (self.check, self.path, self.key) if part)
|
||
|
||
def render(self) -> str:
|
||
where = f"{self.path}:{self.line}" if self.line else self.path
|
||
return f"[{self.check}] {where}: {self.message}"
|
||
|
||
|
||
def fingerprint(line: str) -> str:
|
||
return hashlib.sha256(line.encode("utf-8")).hexdigest()[:16]
|
||
|
||
|
||
def tracked_files(root: Path, pathspec: str) -> list[str]:
|
||
"""Files git knows or would add: tracked plus untracked files that are not ignored."""
|
||
result = subprocess.run(
|
||
["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", pathspec],
|
||
capture_output=True, check=True)
|
||
names = {name for name in result.stdout.decode("utf-8").split("\0") if name}
|
||
return sorted(name for name in names if (root / name).is_file())
|
||
|
||
|
||
def tracked_markdown(root: Path) -> list[str]:
|
||
return [name for name in tracked_files(root, "*.md") if not NOT_DOCUMENT.search(name)]
|
||
|
||
|
||
def record_kind(path: str) -> str | None:
|
||
for prefix, kind in RECORD_KINDS:
|
||
if path.startswith(prefix):
|
||
return kind
|
||
return None
|
||
|
||
|
||
def is_living(path: str) -> bool:
|
||
return not path.startswith(NOT_LIVING)
|
||
|
||
|
||
def strip_head_block(lines: list[str]) -> list[str]:
|
||
if lines and lines[0] == HEAD_START and HEAD_END in lines[:HEAD_SEARCH_LINES]:
|
||
return lines[lines.index(HEAD_END) + 1:]
|
||
return lines
|
||
|
||
|
||
def strip_front_matter(lines: list[str]) -> list[str]:
|
||
if lines and lines[0].strip() == "---":
|
||
for index in range(1, len(lines)):
|
||
if lines[index].strip() == "---":
|
||
return lines[index + 1:]
|
||
return lines
|
||
|
||
|
||
def body_lines(text: str) -> list[str]:
|
||
return strip_front_matter(strip_head_block(text.split("\n")))
|
||
|
||
|
||
def prose(text: str) -> str:
|
||
"""판정에서 뺄 것(코드·명령·인용·링크·URL·경로·파일 이름)을 지운 글. H11의 prose()와 같다."""
|
||
lines, fence = [], None
|
||
for line in text.split("\n"):
|
||
match = FENCE.match(line)
|
||
if fence:
|
||
if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence):
|
||
fence = None
|
||
continue
|
||
if match:
|
||
fence = match.group(1)
|
||
continue
|
||
if not line.lstrip().startswith(("$ ", ">")):
|
||
lines.append(line)
|
||
text = "\n".join(lines)
|
||
for pattern in (INLINE, MDLINK, URL, QUOTED, PATHLIKE, FILELIKE):
|
||
text = pattern.sub(" ", text)
|
||
return text
|
||
|
||
|
||
def language_counts(text: str) -> tuple[int, int]:
|
||
cleaned = prose(text)
|
||
korean = len(HANGUL.findall(cleaned))
|
||
english = sum(1 for token in TOKEN.findall(cleaned) if WORD.match(token))
|
||
return korean, english
|
||
|
||
|
||
def is_english(text: str) -> bool:
|
||
korean, english = language_counts(text)
|
||
return english >= MIN_ENGLISH and korean / (korean + english) < MIN_KOREAN_SHARE
|
||
|
||
|
||
def check_language(root: Path, files: list[str]) -> list[Problem]:
|
||
problems = []
|
||
for path in files:
|
||
if not is_living(path):
|
||
continue
|
||
body = "\n".join(body_lines((root / path).read_text(encoding="utf-8")))
|
||
if is_english(body):
|
||
korean, english = language_counts(body)
|
||
problems.append(Problem("language", path, "",
|
||
f"영어 문서다(한글 {korean}, 영어 낱말 {english}). 한국어로 쓴다"))
|
||
return problems
|
||
|
||
|
||
def head_block(lines: list[str]) -> tuple[list[str], int] | None:
|
||
if not lines or lines[0] != HEAD_START:
|
||
return None
|
||
window = lines[:HEAD_SEARCH_LINES]
|
||
if HEAD_END not in window:
|
||
return None
|
||
end = window.index(HEAD_END)
|
||
return lines[1:end], end
|
||
|
||
|
||
def backticked_paths(value: str) -> list[str]:
|
||
return re.findall(r"`([^`]+)`", value)
|
||
|
||
|
||
def check_head(root: Path, files: list[str]) -> list[Problem]:
|
||
problems = []
|
||
for path in files:
|
||
kind = record_kind(path)
|
||
if kind is None:
|
||
continue
|
||
|
||
def fail(message: str, line: int = 1) -> None:
|
||
problems.append(Problem("head", path, "", message, line))
|
||
|
||
lines = (root / path).read_text(encoding="utf-8").split("\n")
|
||
found = head_block(lines)
|
||
if found is None:
|
||
fail(f"맨 위에 머리 블록이 없다. 첫 줄은 `{HEAD_START}`, 블록은 `{HEAD_END}`로 닫는다")
|
||
continue
|
||
block, _ = found
|
||
label = DECISION_LABEL if kind == "결정 기록" else RECORD_LABEL.format(kind=kind)
|
||
if not block or block[0] != label:
|
||
fail(f"머리 블록 둘째 줄은 「{label}」이다", 2)
|
||
fields: dict[str, tuple[str, int]] = {}
|
||
for offset, line in enumerate(block[1:], start=3):
|
||
if not line.strip():
|
||
continue
|
||
match = re.match(r"^- ([^:]+): (.+)$", line)
|
||
if not match:
|
||
fail(f"머리 블록의 줄은 `- 칸: 값`이다: {line!r}", offset)
|
||
continue
|
||
name, value = match.group(1).strip(), match.group(2).strip()
|
||
if name not in HEAD_FIELDS + HEAD_OPTIONAL:
|
||
fail(f"머리 블록에 없는 칸이다: {name}", offset)
|
||
elif name in fields:
|
||
fail(f"칸이 두 번 나온다: {name}", offset)
|
||
else:
|
||
fields[name] = (value, offset)
|
||
for name in HEAD_FIELDS:
|
||
if name not in fields:
|
||
fail(f"「{name}」 칸이 없다")
|
||
status, at = fields.get("상태", ("", 1))
|
||
if "상태" in fields and status not in STATUS[kind]:
|
||
fail(f"{kind}의 상태는 {' · '.join(STATUS[kind])} 중 하나다: {status!r}", at)
|
||
written, at = fields.get("작성일", ("", 1))
|
||
if "작성일" in fields:
|
||
try:
|
||
datetime.date.fromisoformat(written)
|
||
except ValueError:
|
||
fail(f"작성일은 YYYY-MM-DD다: {written!r}", at)
|
||
summary, at = fields.get("요약", ("", 1))
|
||
if "요약" in fields and (not HANGUL.search(summary) or is_english(summary)):
|
||
fail("요약은 한국어 한 문장이다", at)
|
||
canonical, at = fields.get("현재 정본", ("", 1))
|
||
if "현재 정본" in fields:
|
||
targets = backticked_paths(canonical)
|
||
if not canonical.startswith("없음") and not targets:
|
||
fail("현재 정본은 `경로`(여럿이면 쉼표) 또는 「없음 — 이유」다", at)
|
||
for target in targets:
|
||
if not (root / target).exists():
|
||
fail(f"현재 정본 경로가 없다: {target}", at)
|
||
if status == "대체됨" and "대체됨" not in fields:
|
||
fail("상태가 대체됨이면 「대체됨」 칸에 대체한 문서를 적는다")
|
||
for name in HEAD_OPTIONAL:
|
||
if name in fields:
|
||
value, at = fields[name]
|
||
targets = backticked_paths(value)
|
||
if not targets:
|
||
fail(f"「{name}」 칸은 `경로`를 적는다", at)
|
||
for target in targets:
|
||
if not (root / target).exists():
|
||
fail(f"「{name}」 경로가 없다: {target}", at)
|
||
return problems
|
||
|
||
|
||
def inline_spans(lines: list[str]) -> list[tuple[int, str]]:
|
||
"""(줄 번호, 인라인 코드) — 코드 블록과 「이력」 인용 블록 밖에서만."""
|
||
spans, fence, history = [], None, False
|
||
for number, line in enumerate(lines, start=1):
|
||
match = FENCE.match(line)
|
||
if fence:
|
||
if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence):
|
||
fence = None
|
||
continue
|
||
if match:
|
||
fence = match.group(1)
|
||
continue
|
||
quoted = line.lstrip().startswith(">")
|
||
if quoted and HISTORY_QUOTE.match(line):
|
||
history = True
|
||
elif not quoted:
|
||
history = False
|
||
if history:
|
||
continue
|
||
for found in INLINE.finditer(line):
|
||
spans.append((number, found.group(0).strip("`").strip()))
|
||
return spans
|
||
|
||
|
||
def registry_projects(root: Path) -> set[str]:
|
||
registry = root / REGISTRY_FILE
|
||
if not registry.is_file():
|
||
return set()
|
||
modules = json.loads(registry.read_text(encoding="utf-8")).get("modules", [])
|
||
projects: set[str] = set()
|
||
for module in modules:
|
||
parts = module["gradle_path"].split(":")[1:]
|
||
for end in range(1, len(parts) + 1):
|
||
projects.add(":" + ":".join(parts[:end]))
|
||
return projects
|
||
|
||
|
||
def path_candidate(token: str) -> str | None:
|
||
token = token.strip().strip("'\"()[],;")
|
||
if token.startswith("./"):
|
||
token = token[2:]
|
||
if not token.startswith(PATH_ROOTS) or PLACEHOLDER.search(token) or "://" in token:
|
||
return None
|
||
token = LINE_SUFFIX.sub("", token.split("#", 1)[0]).rstrip(".:")
|
||
return token or None
|
||
|
||
|
||
def resolves(root: Path, document: str, target: str) -> bool:
|
||
if (root / target).exists():
|
||
return True
|
||
# src/main/... in a leaf document is written relative to that leaf.
|
||
folder = (root / document).parent
|
||
while folder != root and root in folder.parents:
|
||
if (folder / target).exists():
|
||
return True
|
||
folder = folder.parent
|
||
return False
|
||
|
||
|
||
def ignored(root: Path, paths: set[str]) -> set[str]:
|
||
if not paths:
|
||
return set()
|
||
result = subprocess.run(["git", "-C", str(root), "check-ignore", "--no-index", "--stdin"],
|
||
input="\n".join(sorted(paths)).encode("utf-8"), capture_output=True)
|
||
return set(result.stdout.decode("utf-8").split("\n")) - {""}
|
||
|
||
|
||
def checked_for_drift(path: str) -> bool:
|
||
return is_living(path) and not path.startswith(DECISION_PREFIXES) and not path.startswith(HISTORY_HOLDERS)
|
||
|
||
|
||
def path_suffixes(root: Path) -> set[str]:
|
||
"""Every trailing part of every file and folder git knows: `src/test/resources/x.sha256` written in a
|
||
manual about any leaf resolves when some leaf has it."""
|
||
result = subprocess.run(
|
||
["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
|
||
capture_output=True, check=True)
|
||
suffixes: set[str] = set()
|
||
for name in result.stdout.decode("utf-8").split("\0"):
|
||
parts = name.split("/")
|
||
for end in range(1, len(parts) + 1):
|
||
for start in range(end):
|
||
suffixes.add("/".join(parts[start:end]))
|
||
return suffixes
|
||
|
||
|
||
def check_reference(root: Path, files: list[str]) -> list[Problem]:
|
||
projects = registry_projects(root)
|
||
missing: list[tuple[str, int, str]] = []
|
||
problems = []
|
||
for path in files:
|
||
if not checked_for_drift(path):
|
||
continue
|
||
lines = body_lines((root / path).read_text(encoding="utf-8"))
|
||
offset = len((root / path).read_text(encoding="utf-8").split("\n")) - len(lines)
|
||
seen: set[str] = set()
|
||
for number, span in inline_spans(lines):
|
||
for token in span.split():
|
||
gradle = token.strip(".,;'\"()")
|
||
if GRADLE_PATH.match(gradle):
|
||
parent = gradle.rsplit(":", 1)[0]
|
||
if projects and gradle not in projects and parent not in projects and gradle not in seen:
|
||
seen.add(gradle)
|
||
problems.append(Problem("reference", path, gradle,
|
||
f"registry에 없는 Gradle 경로다: {gradle}", number + offset))
|
||
continue
|
||
target = path_candidate(token)
|
||
if target and SOURCE_SET.match(target):
|
||
continue
|
||
if target and target not in seen and not resolves(root, path, target):
|
||
seen.add(target)
|
||
missing.append((path, number + offset, target))
|
||
skip = ignored(root, {target for _, _, target in missing})
|
||
if missing:
|
||
skip |= path_suffixes(root)
|
||
for path, number, target in missing:
|
||
if target.rstrip("/") not in skip and target not in skip:
|
||
problems.append(Problem("reference", path, target, f"없는 경로다: {target}", number))
|
||
return problems
|
||
|
||
|
||
def check_number(root: Path, files: list[str]) -> list[Problem]:
|
||
problems = []
|
||
for path in files:
|
||
if not checked_for_drift(path):
|
||
continue
|
||
seen: set[str] = set()
|
||
for number, line in enumerate((root / path).read_text(encoding="utf-8").split("\n"), start=1):
|
||
for label, pattern in COPIED_NUMBERS:
|
||
for match in pattern.finditer(line):
|
||
text = match.group(0)
|
||
if text not in seen:
|
||
seen.add(text)
|
||
problems.append(Problem("number", path, text,
|
||
f"{label}를 복사했다: {text!r}. 정본을 가리킨다", number))
|
||
return problems
|
||
|
||
|
||
def required_folders(paths: list[str]) -> set[str]:
|
||
"""지도에 있어야 하는 폴더(`docs/` 기준): docs/ 바로 아래 폴더. 파일 없이 폴더만 가진 묶음 폴더는
|
||
그 바로 아래 폴더가 대신한다(history/ → history/plans/ 등). 더 깊이는 내려가지 않는다."""
|
||
def children(paths: list[str]) -> dict[str, list[str]]:
|
||
found: dict[str, list[str]] = {}
|
||
for path in paths:
|
||
name, slash, rest = path.partition("/")
|
||
if slash:
|
||
found.setdefault(name, []).append(rest)
|
||
return found
|
||
|
||
folders: set[str] = set()
|
||
for name, inside in children(paths).items():
|
||
if any("/" not in path for path in inside):
|
||
folders.add(f"{name}/")
|
||
else:
|
||
folders |= {f"{name}/{child}/" for child in children(inside)}
|
||
return folders
|
||
|
||
|
||
def outside_code(lines: list[str]) -> list[tuple[int, str]]:
|
||
"""(줄 번호, 줄) — 코드 블록 밖의 줄만."""
|
||
kept, fence = [], None
|
||
for number, line in enumerate(lines, start=1):
|
||
match = FENCE.match(line)
|
||
if fence:
|
||
if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence):
|
||
fence = None
|
||
continue
|
||
if match:
|
||
fence = match.group(1)
|
||
continue
|
||
kept.append((number, line))
|
||
return kept
|
||
|
||
|
||
def map_entries(lines: list[str]) -> list[tuple[int, str]]:
|
||
"""(줄 번호, `docs/` 기준 폴더) — 코드 블록 밖 표 행의 첫 칸에 인라인 코드로 적은 `폴더/`."""
|
||
entries = []
|
||
for number, line in outside_code(lines):
|
||
cells = line.strip().split("|")
|
||
if not line.strip().startswith("|") or len(cells) < 3:
|
||
continue
|
||
for found in INLINE.finditer(cells[1]):
|
||
token = found.group(0).strip("`").strip()
|
||
if token.startswith(DOCS_ROOT):
|
||
token = token[len(DOCS_ROOT):]
|
||
if token.endswith("/") and not PLACEHOLDER.search(token):
|
||
entries.append((number, token))
|
||
return entries
|
||
|
||
|
||
def check_map(root: Path, files: list[str]) -> list[Problem]:
|
||
del files # 지도는 .md만이 아니라 docs/ 아래 모든 파일의 폴더를 본다(스냅숏·yaml만 있는 폴더도 있다).
|
||
if not (root / MAP_FILE).is_file():
|
||
return [Problem("map", MAP_FILE, "", "문서 지도가 없다")]
|
||
documents = [path[len(DOCS_ROOT):] for path in tracked_files(root, DOCS_ROOT)]
|
||
entries = map_entries((root / MAP_FILE).read_text(encoding="utf-8").split("\n"))
|
||
mapped = {folder for _, folder in entries}
|
||
problems = [Problem("map", MAP_FILE, folder, f"지도에 없는 문서 폴더다: {DOCS_ROOT}{folder}. 지도에 행을 더한다")
|
||
for folder in sorted(required_folders(documents) - mapped)]
|
||
for number, folder in entries:
|
||
if not any(path.startswith(folder) for path in documents):
|
||
problems.append(Problem("map", MAP_FILE, folder, f"지도의 폴더가 없다: {DOCS_ROOT}{folder}", number))
|
||
return problems
|
||
|
||
|
||
def headings(lines: list[str]) -> list[tuple[int, int, str]]:
|
||
"""(줄 번호, 수준, 제목) — 코드 블록 밖의 # 제목."""
|
||
found = []
|
||
for number, line in outside_code(lines):
|
||
heading = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", line)
|
||
if heading:
|
||
found.append((number, len(heading.group(1)), heading.group(2)))
|
||
return found
|
||
|
||
|
||
def check_readme(root: Path, files: list[str]) -> list[Problem]:
|
||
del files
|
||
|
||
def fail(key: str, message: str, line: int = 0) -> None:
|
||
problems.append(Problem("readme", README_FILE, key, message, line))
|
||
|
||
problems: list[Problem] = []
|
||
if not (root / README_FILE).is_file():
|
||
fail("", "루트 README가 없다")
|
||
return problems
|
||
lines = (root / README_FILE).read_text(encoding="utf-8").split("\n")
|
||
found = headings(lines)
|
||
first = next((number for number, line in enumerate(lines, start=1) if line.strip()), 0)
|
||
if not found or found[0][:2] != (first, 1):
|
||
fail("제목", "첫 줄은 `# 제목`이다", first)
|
||
else:
|
||
sections = [number for number, level, _ in found if level == 2]
|
||
intro = lines[first:sections[0] - 1] if sections else lines[first:]
|
||
if not any(line.strip() and not line.lstrip().startswith(("#", "|", "```", "~~~")) for line in intro):
|
||
fail("소개", "제목 아래, 첫 ## 절 앞에 무엇인지·누가 쓰나 한 문단을 둔다", first)
|
||
positions = {}
|
||
for number, level, title in found:
|
||
if level == 2 and title in README_SECTIONS and title not in positions:
|
||
positions[title] = number
|
||
for title in README_SECTIONS:
|
||
if title not in positions:
|
||
fail(title, f"「## {title}」 절이 없다. 절 목록은 {' → '.join(README_SECTIONS)}다")
|
||
present = [title for title in README_SECTIONS if title in positions]
|
||
for before, after in zip(present, present[1:]):
|
||
if positions[before] > positions[after]:
|
||
fail(after, f"「## {after}」 절은 「## {before}」 절 뒤에 온다", positions[after])
|
||
return problems
|
||
|
||
|
||
RUNNERS = {"language": check_language, "head": check_head, "reference": check_reference, "number": check_number,
|
||
"map": check_map, "readme": check_readme}
|
||
|
||
|
||
def read_exceptions(text: str) -> list[str]:
|
||
return [line for line in text.split("\n") if line.strip() and not line.startswith("#")]
|
||
|
||
|
||
def run(root: Path, only: tuple[str, ...] = CHECKS, exceptions: str | None = None,
|
||
frozen: frozenset[str] = FROZEN) -> tuple[list[str], list[str]]:
|
||
"""(실패 줄, 보고 줄). 예외 목록을 적용한 뒤의 결과다."""
|
||
if exceptions is None:
|
||
exceptions_path = root / EXCEPTIONS_FILE
|
||
exceptions = exceptions_path.read_text(encoding="utf-8") if exceptions_path.is_file() else ""
|
||
allowed = read_exceptions(exceptions)
|
||
files = tracked_markdown(root)
|
||
errors: list[str] = []
|
||
report: list[str] = []
|
||
for entry in allowed:
|
||
if fingerprint(entry) not in frozen:
|
||
errors.append(f"[exceptions] {EXCEPTIONS_FILE}: 기준선에 없는 예외다. 예외 목록은 늘지 않는다: {entry!r}")
|
||
listed = {fingerprint(entry) for entry in allowed}
|
||
for orphan in sorted(frozen - listed):
|
||
errors.append(f"[exceptions] scripts/check-docs.py FROZEN: 예외 목록에 그 줄이 없는 지문이다. "
|
||
f"지운 줄의 지문은 FROZEN에서도 뺀다: {orphan}")
|
||
allowed_set = set(allowed)
|
||
for check in only:
|
||
problems = RUNNERS[check](root, files)
|
||
hit = {problem.exception_line() for problem in problems}
|
||
unexcused = [problem for problem in problems if problem.exception_line() not in allowed_set]
|
||
stale = [entry for entry in allowed if entry.split("\t", 1)[0] == check and entry not in hit]
|
||
errors += [problem.render() for problem in unexcused]
|
||
errors += [f"[exceptions] {EXCEPTIONS_FILE}: 더는 걸리지 않는다. 이 줄을 지운다: {entry!r}" for entry in stale]
|
||
excused = len(problems) - len(unexcused)
|
||
report.append(f"{check}: 걸림 {len(problems)}, 예외 {excused}, 실패 {len(unexcused)}")
|
||
return errors, report
|
||
|
||
|
||
def main(argv: list[str]) -> int:
|
||
only = CHECKS
|
||
if argv[:1] == ["--only"]:
|
||
if len(argv) != 2 or argv[1] not in CHECKS:
|
||
print(f"usage: check-docs.py [--only {'|'.join(CHECKS)}]", file=sys.stderr)
|
||
return 2
|
||
only = (argv[1],)
|
||
elif argv:
|
||
print(f"usage: check-docs.py [--only {'|'.join(CHECKS)}]", file=sys.stderr)
|
||
return 2
|
||
errors, report = run(REPO_ROOT, only)
|
||
for line in report:
|
||
print(line)
|
||
if errors:
|
||
print(f"\nFAILED: {len(errors)}", file=sys.stderr)
|
||
for error in errors:
|
||
print(f" {error}", file=sys.stderr)
|
||
return 1
|
||
print("\nOK")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main(sys.argv[1:]))
|