From f56a100528849ee2f7b98b07b2205a3759920cda Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 7 Nov 2026 17:18:19 +0900 Subject: [PATCH] =?UTF-8?q?ci(docs):=20=EB=AC=B8=EC=84=9C=20=EC=A7=80?= =?UTF-8?q?=EB=8F=84=EC=99=80=20=EB=A3=A8=ED=8A=B8=20README=20=EC=A0=88?= =?UTF-8?q?=EC=9D=84=20=EB=AC=B8=EC=84=9C=20=EA=B2=80=EC=82=AC=EA=B0=80=20?= =?UTF-8?q?=EB=B3=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: 「모든 문서 폴더가 `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. --- scripts/check-docs-exceptions.txt | 1 - scripts/check-docs.py | 146 ++++++++++++++++++++++++++++-- scripts/tests/test_check_docs.py | 121 +++++++++++++++++++++++++ 3 files changed, 261 insertions(+), 7 deletions(-) diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt index d3976e00..1d81c4a0 100644 --- a/scripts/check-docs-exceptions.txt +++ b/scripts/check-docs-exceptions.txt @@ -166,7 +166,6 @@ language src/adapter/outbound/redis-sdk/README.md language src/adapter/outbound/redis-sdk/compose/README.md language src/adapter/outbound/support/CLAUDE.md language src/app-bootstrap/CLAUDE.md -language src/app-bootstrap/src/test/resources/developer-experience/broken-readme.md language src/application-core/CLAUDE.md language src/build-logic/README.md language src/composition/outbox-relay/CLAUDE.md diff --git a/scripts/check-docs.py b/scripts/check-docs.py index 3e482356..c5736f85 100755 --- a/scripts/check-docs.py +++ b/scripts/check-docs.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""문서 검사 넷: 언어, 기록의 머리 블록, 참조, 복사한 숫자. 하나라도 걸리면 rc=1이다. +"""문서 검사 여섯: 언어, 기록의 머리 블록, 참조, 복사한 숫자, 문서 지도, 루트 README 절. 하나라도 걸리면 rc=1이다. 규칙의 정본은 design-docs `conventions/docs-system.md`이고, 이 repo의 적용은 `docs/README.md` 「문서 수명과 언어」다. 이 스크립트는 그 규칙 중 기계로 볼 수 있는 것만 본다. @@ -15,6 +15,14 @@ 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 기준선의 지문)에 있어야 한다. 목록에 새 줄을 더하면 실패한다. @@ -44,7 +52,7 @@ 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") +CHECKS = ("language", "head", "reference", "number", "map", "readme") # 기록: 본문은 쓴 때의 원문이다. 머리 블록만 고친다. 종류는 폴더가 정한다. RECORD_KINDS = [ @@ -80,6 +88,16 @@ 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", @@ -179,15 +197,19 @@ def fingerprint(line: str) -> str: return hashlib.sha256(line.encode("utf-8")).hexdigest()[:16] -def tracked_markdown(root: Path) -> list[str]: - """Markdown files git knows or would add: tracked plus untracked files that are not ignored.""" +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", "--", "*.md"], + ["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): @@ -485,7 +507,119 @@ def check_number(root: Path, files: list[str]) -> list[Problem]: return problems -RUNNERS = {"language": check_language, "head": check_head, "reference": check_reference, "number": check_number} +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]: diff --git a/scripts/tests/test_check_docs.py b/scripts/tests/test_check_docs.py index 64ebe46e..6638bfda 100644 --- a/scripts/tests/test_check_docs.py +++ b/scripts/tests/test_check_docs.py @@ -246,6 +246,127 @@ class NumberTest(RepositoryTestCase): self.assertEqual(self.errors_for("leaf 하나를 고른다.\n"), []) +class ScopeTest(RepositoryTestCase): + def test_markdown_under_a_source_set_resources_folder_is_not_a_document(self) -> None: + self.repo.write("src/app/src/test/resources/fixtures/broken-readme.md", "# Broken\n\n" + ENGLISH * 3) + self.assertEqual(self.repo.run(("language",)), []) + + def test_markdown_beside_a_source_set_is_still_a_document(self) -> None: + self.repo.write("src/app/src/test/README.md", "# Tests\n\n" + ENGLISH * 3) + self.assertFailsWith(self.repo.run(("language",)), "src/app/src/test/README.md: 영어 문서다") + + +def table(*rows: str) -> str: + return "| 폴더 | 무엇 |\n| --- | --- |\n" + "".join(f"| {row} | 설명 |\n" for row in rows) + + +class MapTest(RepositoryTestCase): + def errors_for(self, text: str) -> list[str]: + self.repo.write(check_docs.MAP_FILE, "# docs\n\n" + KOREAN + text) + return self.repo.run(("map",)) + + def test_a_map_that_names_every_folder_passes(self) -> None: + self.repo.write("docs/jpa/guide.md", KOREAN) + self.repo.write("docs/history/plans/2026-08-11-x-plan.md", KOREAN) + checks = "| 검사 | 보는 것 |\n| --- | --- |\n| `language` | 언어 |\n" + self.assertEqual(self.errors_for(table("`jpa/`", "`history/plans/`") + "\n" + checks), []) + + def test_a_folder_missing_from_the_map_fails(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertFailsWith(self.errors_for(table()), "지도에 없는 문서 폴더다: docs/redis/") + + def test_a_folder_without_markdown_must_be_mapped_too(self) -> None: + self.repo.write("docs/security/public-paths-snapshot.txt", "/api/healthcheck\n") + self.assertFailsWith(self.errors_for(table()), "지도에 없는 문서 폴더다: docs/security/") + + def test_a_folder_that_only_holds_folders_is_covered_by_its_subfolders(self) -> None: + self.repo.write("docs/history/plans/2026-08-11-x-plan.md", KOREAN) + self.repo.write("docs/history/study/x.md", KOREAN) + errors = self.errors_for(table("`history/`", "`history/plans/`")) + self.assertFailsWith(errors, "지도에 없는 문서 폴더다: docs/history/study/") + self.assertFalse(any("docs/history/plans/" in error for error in errors), errors) + + def test_folders_below_the_mapped_level_need_no_row(self) -> None: + self.repo.write("docs/history/packages/jpa/README.md", KOREAN) + self.repo.write("docs/mongodb/advanced/sharding.md", KOREAN) + self.repo.write("docs/mongodb/guide.md", KOREAN) + self.assertEqual(self.errors_for(table("`history/packages/`", "`mongodb/`")), []) + + def test_a_mapped_folder_that_does_not_exist_fails(self) -> None: + self.assertFailsWith(self.errors_for(table("`gone/`")), "지도의 폴더가 없다: docs/gone/") + + def test_a_folder_named_outside_the_first_cell_does_not_count(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertFailsWith(self.errors_for(table("운영") + "| 캐시 | `redis/` |\n"), + "지도에 없는 문서 폴더다: docs/redis/") + + def test_a_folder_inside_a_code_block_does_not_count(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertFailsWith(self.errors_for("```text\n" + table("`redis/`") + "```\n"), + "지도에 없는 문서 폴더다: docs/redis/") + + def test_a_folder_may_be_written_from_the_repository_root(self) -> None: + self.repo.write("docs/redis/operations.md", KOREAN) + self.assertEqual(self.errors_for(table("`docs/redis/`")), []) + + def test_a_placeholder_folder_is_not_an_entry(self) -> None: + self.assertEqual(self.errors_for(table("`history/packages/<어댑터>/`")), []) + + def test_a_repository_without_the_map_fails(self) -> None: + self.assertFailsWith(self.repo.run(("map",)), "문서 지도가 없다") + + +def readme(sections: tuple[str, ...] = check_docs.README_SECTIONS, title: str = "# 템플릿", + intro: str = "이 저장소가 무엇이고 누가 쓰는지 쓴 한 문단이다.") -> str: + parts = [title, "", intro, ""] if intro else [title, ""] + for section in sections: + parts += [section if section.startswith("#") else f"## {section}", "", KOREAN] + return "\n".join(parts) + + +class ReadmeTest(RepositoryTestCase): + def errors_for(self, text: str) -> list[str]: + self.repo.write(check_docs.README_FILE, text) + return self.repo.run(("readme",)) + + def test_every_section_in_order_passes(self) -> None: + self.assertEqual(self.errors_for(readme()), []) + + def test_other_sections_between_the_required_ones_pass(self) -> None: + sections = check_docs.README_SECTIONS[:2] + ("부록",) + check_docs.README_SECTIONS[2:] + self.assertEqual(self.errors_for(readme(sections)), []) + + def test_each_missing_section_fails(self) -> None: + for missing in check_docs.README_SECTIONS: + with self.subTest(missing=missing): + sections = tuple(section for section in check_docs.README_SECTIONS if section != missing) + self.assertFailsWith(self.errors_for(readme(sections)), f"「## {missing}」 절이 없다") + + def test_sections_out_of_order_fail(self) -> None: + sections = ("시작하기", "프로젝트 구조") + check_docs.README_SECTIONS[2:] + self.assertFailsWith(self.errors_for(readme(sections)), "「## 시작하기」 절은 「## 프로젝트 구조」 절 뒤에 온다") + + def test_a_readme_that_does_not_start_with_a_title_fails(self) -> None: + self.assertFailsWith(self.errors_for(readme(title="템플릿 소개")), "첫 줄은 `# 제목`이다") + self.assertFailsWith(self.errors_for("소개 한 줄\n\n" + readme()), "첫 줄은 `# 제목`이다") + + def test_a_readme_without_an_introduction_fails(self) -> None: + self.assertFailsWith(self.errors_for(readme(intro="")), "한 문단을 둔다") + + def test_a_section_heading_at_another_level_does_not_count(self) -> None: + sections = tuple("### 문서 지도" if section == "문서 지도" else section + for section in check_docs.README_SECTIONS) + self.assertFailsWith(self.errors_for(readme(sections)), "「## 문서 지도」 절이 없다") + + def test_a_section_heading_inside_a_code_block_does_not_count(self) -> None: + sections = tuple(section for section in check_docs.README_SECTIONS if section != "검증") + text = readme(sections) + "\n```markdown\n## 검증\n```\n" + self.assertFailsWith(self.errors_for(text), "「## 검증」 절이 없다") + + def test_a_repository_without_a_readme_fails(self) -> None: + self.assertFailsWith(self.repo.run(("readme",)), "루트 README가 없다") + + class CommandLineTest(unittest.TestCase): def test_an_unknown_check_is_a_usage_error(self) -> None: self.assertEqual(check_docs.main(["--only", "spelling"]), 2)