Files
clean-architecture-backend-…/scripts/check-docs.py
T
DongHyeonka f56a100528 ci(docs): 문서 지도와 루트 README 절을 문서 검사가 본다
문제: 「모든 문서 폴더가 `docs/README.md` 지도에 있다」와 「루트 README가 정해진 절을
가진다」(design-docs `conventions/docs-system.md` 7절 K5·K6)를 아무것도 지키지 않는다.
테스트 자원 `broken-readme.md`(일부러 깨뜨린 입력)를 살아 있는 문서로 보고 언어 검사
예외에 둔다.

고른 방법: `scripts/check-docs.py`에 검사 둘을 더한다. docs-check workflow가 인자 없이
돌리므로 PR에서 바로 실패로 돈다.
- `map`: `docs/` 바로 아래 폴더가 모두 지도 표의 첫 칸에 있어야 한다. 파일 없이 폴더만
  가진 묶음 폴더(`history/`)는 그 바로 아래 폴더가 대신한다. `.md`가 없는 폴더(스냅숏,
  yaml)도 본다. 지도에 있지만 없는 폴더도 실패다.
- `readme`: 첫 줄 `# 제목`, 그 아래 한 문단, `README_SECTIONS`의 `##` 절이 그 순서로
  있어야 한다. 사이에 다른 절은 있어도 된다.
- 소스 세트 resources 폴더 아래 `.md`(`/src/<세트>/resources/`)는 문서로 보지 않는다.
  그래서 `broken-readme.md` 예외 줄을 지운다.

버린 대안: 지도 폴더를 모든 깊이까지 요구하기. 리뷰 라운드 폴더, 납품 패키지 폴더마다
행이 생겨 지도가 목록이 된다. 절을 정확히 일곱 개만 허용하기. 서비스가 절을 더할 수
없게 된다.

위험·한계: `FROZEN` 지문은 건드리지 않았다. leaf·family README 절 검사(K6 뒷부분)와 파일
이름 규칙·실행 산출물 검사(K5 뒷부분)는 넣지 않았다.

검증:
- `python3 -m unittest discover -s scripts/tests` 65건 rc=0(새 시험 22건).
- 판정 조건 18개를 하나씩 끈 사본마다 자기 시험이 실패했다(rc=1).
- `python3 scripts/check-docs.py` rc=0.
2026-11-07 17:18:19 +09:00

679 lines
33 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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, docs/notification/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에서 옛 지문을 새 지문으로 바꾼다. 지문은 그 줄(탭 포함)의 sha256 앞 16자다:
python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.argv[1].encode()).hexdigest()[:16])' "<줄>"
python3 scripts/check-docs.py # 넷 모두
python3 scripts/check-docs.py --only head # 하나만 (language, head, reference, number)
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/notification/adr/", "결정 기록"),
]
# 리뷰도 기록이다. 머리 블록은 아직 요구하지 않는다(docs/README.md).
NOT_LIVING = ("docs/design/", "docs/history/", "docs/reviews/")
DECISION_PREFIXES = ("docs/adr/", "docs/notification/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자. 늘리지 않는다(맨 위 설명).
FROZEN: frozenset[str] = frozenset({
"0176963415821bbe", "01984fd96d72b997", "02810bf817c5098f", "02f77e3cc483fa7b", "05fff3c3ff8a5c9a",
"06ea362843468b89", "0767d62996355ba0", "077f1849fe8bebcc", "07f88b24645a4899", "09f6eb7c3c494379",
"0a929e243076b4cb", "0d60ec2d41d698e3", "0d9db88d1d98c32b", "0f84458cb40e7c5e", "10894a287a405274",
"110ff8adc628d4e9", "115eed80f3bb629c", "14121ef25eb4aa46", "150219e901d062f4", "199044717780f929",
"1adc480d397a24fc", "1aedb5c86be16e62", "1ef3eec4c410622e", "1f3199d6bef7b3ab", "20a46563da0c570d",
"234a0dffc4f308bf", "23aa784e28c7f730", "24e61cd8377137f1", "26cdb5786cd3cef8", "26f59b7362b9e68d",
"29fa254236927dae", "2a0c27bb25080cdb", "2aa755121374e148", "2bcc75d4e1ebaa5d", "2e77660bd44c1d2c",
"2e7d24cb488ae4f9", "30c75a928243de75", "354c37493e90b01b", "3e867d0b440f18f5", "3fe449c9eca66d87",
"3ff905af6cc2df16", "4053b182a2b89223", "41f268d8aa836143", "4347c5b0dd84ec9b", "449fc1cac0f9380f",
"457310fef9d100a6", "4611a0bfd81bf42c", "462a63de89507bc6", "468248c165ce65f0", "47c9a2b490ceae84",
"4866a2abc9be3133", "48ca99496ac8265e", "494b23454cfaf902", "49d560912ccd3bd6", "49ee572590d74921",
"4c3afe5f9f4265d3", "4cef6042d25d7ce2", "4f4516913c6de5d6", "4f9b0fa57d925ddc", "50cecf0fd2f1ed1f",
"511ed51b27f98b9c", "52879b9f3cbdd66f", "52d9b8b42edf92c5", "52dd5ae3e9bfef22", "53f304d4f21e321e",
"5503b8002ae2673f", "55397a6480705e90", "561988b22b65f79f", "5640b6d1a24b9ad6", "56d9c8bc2e2d7a01",
"570b7b7be5396079", "57603aa52f880d03", "57c4df2758097604", "59e238f79e31e3db", "5acb4cacd9aa7a71",
"5b1f0d60cdd91b33", "5b783704ccce90b9", "5b833f85df94c6fd", "5caaf9a02506595e", "5cd2de3ab18314a9",
"5cda11b0371e8b48", "5e17fde0e8281e0b", "61241c19f875d528", "614d8160fecebe42", "62ac6e83f597894a",
"62ae3935928ec875", "62ae5138ca3f54bf", "29b4daf7b7befa61", "63887df3233e4e7f", "63bbbd89d07abcc5",
"63d3556d23363430", "6407c8198a2ce80f", "6669b8199b2f15be", "6710e607f9ae6ba2", "6c60928d93ca7831",
"6e57bc847800e849", "6f2fef4ed95b870d", "70f8b4b8cb326639", "7227a51a80d75567", "728afb0024d5da55",
"745fabbdac49b041", "74622ec18c9f9985", "74eab10487ee91a4", "7548695a3a57c058", "76030078f4c446ec",
"7698729bcfd126f7", "77ed807b2db1bdb4", "782bc48fcd75361c", "7846dce0563bde1f", "78b5bea3cfb3f84f",
"7a41c841fa3c71c3", "7b3944471a209cdc", "7ba95fb426152c3b", "814a101266f1e722", "8232460887910a0e",
"82b97043efd185d0", "83b56cb713adb544", "84ebb93c8c137862", "8559d433706ac279", "85e199be8e5a5df5",
"86c327f4147ec696", "8c3417a9291e07cf", "9031db861c91b202", "90697a358931eba2", "9084568d44e608c3",
"945be2a3aaccbb2c", "94c5248d3fe6f83f", "95feaea41a059d9a", "966dd5354d327ba4", "97c036827ae94466",
"97fed7ecb0c23137", "982773d6151ae295", "993631c9efdbaa48", "999cc41aeaa485d9", "9b976d47e8cca045",
"9db89af226707449", "9e9437780d412b86", "9ee05526226dd121", "9f6cb144b5b0013d", "a14aae022e52cabd",
"a2db3c73eea72747", "a6e2e42521f27aa8", "a7b7a83d8e7b5914", "a84c5847e6bc413a", "a9cdf0e474dfa4ca",
"ab9a1c81f4d00b17", "ac208a7edf8e6b9e", "ac524f5b860f4b73", "af6bfc4105841865", "b25dfdea45b42ece",
"b2ee46983b09686b", "b6c96aabf4daba15", "b99ef0dca48e547c", "bc89c106ed0333da", "399e08b7f60cd570",
"bd2edda7ff995e5a", "c0f36dd22b6d1df4", "c1cbe5ed9ccaf41a", "c2e62316bf302721", "c30f7e945ca5204b",
"c446b7882073d116", "c555077d0a4ca6dc", "c5556985dac877fb", "c66938fdb57ac8bd", "c7d3f2a6e0e819c7",
"437e813553f5782e", "c9147167591ac87f", "c9682c8986bdfa3f", "c9f15a774cbbb296", "c9f895250a7f6b1f",
"ca9ac59c7e4dd0dd", "ccfd7af308666817", "cde221c994e186e9", "d1c59fa1e5fd22ca", "d2c0d56090ffb617",
"d3a72db1fb71eaf6", "d58784f8ae176897", "d88381653e2c64f9", "d934528c9e7966f7", "da73ed73f0ec1dd9",
"da8381da9de5df66", "dd4f9524437dcc45", "dd6384bc82ce9677", "df5a6c2edc20af59", "e076b4232fc136e9",
"e1ada69597a5d6cd", "e1d8a4d6d6bbfb2e", "e2af4a0f5b0957d5", "e313fbfdd61fba0c", "e347453420828b08",
"e368dfa3ca97d4c7", "e3cc20cbd63d0adb", "e4435ba963a1fbef", "e5182c24f72e2747", "e660a27969605244",
"e7dad258cbc844a0", "e97d1ef509983caa", "e997a8c038464efb", "eb66b6c389ec09e4", "ed7764b9ec0265a0",
"ee8e568418c22e81", "ef22d97e0a67bed8", "f0baa883ab5f959d", "f12cb9b454600534", "f135bd1f9697ad4c",
"f166b8797656c86e", "f191a6842f342b74", "f3ea04dd3a66f76a", "f4c93c2e841f1c68", "f4d7edfeee65b0c3",
"f6528fa83345165e", "fa4172e085723211", "fc0c07879a70ce33", "fd706bf633a51444", "fd793c8cfa94f318",
"fe800048b661a783", "6cfa7cfc6f6a4a7e",
})
# --- 언어 판정: ~/.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}")
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:]))