Files
clean-architecture-backend-…/scripts/check-repo-layout.py
T
DongHyeonka 6a792b8144 refactor(layout)!: 옮긴 경로를 부르는 곳을 모두 새 배치에 맞춘다
문제: 앞 커밋이 Gradle 루트를 저장소 루트로 옮기고 계층 폴더를 묶었다.
빌드 스크립트·build-logic·시험·workflow·스크립트·문서가 아직 옛 배치
(Gradle 루트 = src/)를 가정해 빌드가 되지 않는다.

고른 방법:
- Gradle 경로와 registry id는 그대로 둔다(:app-bootstrap, :application-core,
  :composition:*). registry의 source_path만 새 폴더를 가리킨다. 폴더에 맞춘
  이름(:domain:core, :application:core)은 프로젝트 이름 core가 둘이 되어
  boot jar의 BOOT-INF/lib와 기본 capability가 겹치고, 파생 서비스의 모든
  project(':…') 줄을 바꾸게 한다.
- registry는 gradle/modules.json, 시험 이미지 목록은
  gradle/container-images.properties: 버전 카탈로그 옆, 빌드가 고정하는 것.
  config/는 코드 검사 도구 설정만 둔다.
- build-logic: settings·architecture 플러그인의 저장소 루트를 Gradle 루트로
  (getParentFile 제거). config contract의 파일 트리는 src/만 훑는다(루트를
  훑으면 docs·.claude/worktrees까지 줍는다).
- 빌드 스크립트: rootProject.projectDir.parentFile → rootProject.projectDir,
  rootProject.file('../…') → rootProject.file('…'), 옛 src 기준 include에
  src/를 붙인다. notification API surface의 application-notification 소스
  루트를 새 폴더로(놓치면 272개 타입이 surface에서 말없이 빠진다).
- 시험: 옛 src 기준 모듈 목록과 ../ 개수를 고친다. 없는 폴더를 말없이
  건너뛰던 목록(MessagingAuthority, NotificationPayloadAtRest 등)을 새
  폴더로, FileserverDocumentationCoverageTest는 Gradle 경로 → 폴더를
  registry로 찾는다. Docker 계약은 WORKDIR /build, 새 jar 경로.
- Docker: 빌드 context를 저장소 루트로, .dockerignore는 허용 목록으로 다시
  써서 전에 context였던 것만 들어가게 한다. compose의 build.context는 .,
  env_file은 ./.env.
- workflow: working-directory: src 기본값과 그것을 되돌리던 줄을 지운다.
- scripts: verify.sh, ci/*, bootstrap-local, new-feature,
  verify-feature-scaffold, mongo 검증, hooks, check-repo-layout 허용 목록.
  check-docs의 경로 검사는 build-logic/·gradle/로 시작하는 경로도 본다.
- 문서: AGENTS.md 지도, README 구조 표, leaf AGENTS.md의 cd src, gates·
  operate·결정 색인, src/bootstrap/AGENTS.md를 조립 계층 family 규칙으로
  다시 쓴다. 기록 문서(docs/design·history·reviews, 지난 upgrade 안내,
  capability-status 제거 표)는 머리 블록만 고친다. 파생 서비스용 안내
  docs/upgrade/2026-11-relayout.md를 더한다.

위험: bootRun working dir가 저장소 루트가 되어 .env와 상대 경로 설정이
루트 기준이다. 루트 .env는 compose 보간에도 읽힌다(upgrade 안내 5절).
파생 서비스는 태그 pre-relayout-2026-11까지 받은 뒤 이 묶음을 받는다.

검증: desktop에서 캐시 없이 scripts/verify.sh docs·pr·main·release,
compose smoke 18 lane, 빠른 시작(scripts/verify.sh app). 결과는 PR 본문.
구조 리뷰(arch-reviewer) 지적 5건을 반영했다.

BREAKING CHANGE: Gradle은 저장소 루트에서 돈다(cd src 없음). registry는
gradle/modules.json, 이미지 빌드 context는 저장소 루트다. 옛 경로 → 새 경로
표는 docs/upgrade/2026-11-relayout.md.
Refs: design-docs repo-structure/01-backend-layout.md 6.1절 가-2·가-3
2026-11-11 22:15:42 +09:00

204 lines
8.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""저장소 루트와 src/ 최상위에 허용 목록 밖의 항목이 생기면 실패한다.
왜: src/ 아래 계층이 아닌 폴더가 2026-07-24의 둘에서 두 달 사이 여덟으로 늘었고, 어느 커밋도 최상위
모양을 묻지 않았다. 루트에는 개발 환경·테스트 fixture·운영 인프라가 섞인 compose 파일과 infra/ 폴더가
쌓였다(2026-11-07 저장소 정리, design-docs repo-structure/01-backend-layout.md). 소유자는 배치 규칙을
리뷰 기준에 두고, 이 허용 목록 검사로도 막기로 정했다(같은 날, repo-structure/README.md 3.1절).
무엇을 보나:
1. 저장소 루트의 추적 파일·폴더가 ROOT_ALLOWED 안에 있는가.
2. src/ 바로 아래의 추적 파일·폴더가 SRC_ALLOWED 안에 있는가. src/에는 계층 폴더만 있다(파일 없음).
3. registry(gradle/modules.json)의 모든 source_path가 허용된 src/ 폴더 아래에 있는가.
4. (경고만) 개발 환경·테스트 fixture 파일(compose 파일, 셸 스크립트, compose/ 아래 보조 파일)을 다른
추적 파일이 하나도 가리키지 않으면 이름을 출력한다. 아무도 읽지 않는 파일이 소리 없이 남는 것이
infra/ 12개가 쌓인 방식이다. 경로를 변수로 조립하는 workflow는 이 검사가 따라가지 못하므로 경고로만 둔다.
추적 파일만 본다(git ls-files). build 출력과 IDE 폴더는 처음부터 대상이 아니다.
새 최상위 항목이 정말 필요하면 아래 목록과 루트 AGENTS.md 「지도」의 최상위 줄을 같은
변경에서 고친다. 최상위 폴더를 만들거나 옮기는 일은 파일 하나여도 큰 일이다(docs/work/README.md 2절).
Gradle 밖에 둔다: 빌드는 저장소 배치를 판단하지 않는다(scripts/check-work-docs.py와 같은 자리).
python3 scripts/check-repo-layout.py
"""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path, PurePosixPath
REPO_ROOT = Path(__file__).resolve().parent.parent
REGISTRY = "gradle/modules.json"
# 저장소 루트 = Gradle 루트: 빌드 도구와 빌드 파일, 문서·스크립트·CI·개발 환경, 그리고 코드(src)다.
# 2026-11-11에 Gradle 루트를 src/에서 여기로 옮겼다(design-docs repo-structure/01-backend-layout.md 6.1절 가-3).
ROOT_ALLOWED = {
# 폴더
".claude": "Claude Code 세션 설정(추적: settings.json의 권한·훅, rules·skills·agents)",
".gitea": "Gitea Actions workflow(pr·main·release)와 공용 action",
".github": "CODEOWNERS, PR 템플릿, 의존성 취약점 정책",
"build-logic": "빌드 규칙(included build)",
"compose": "compose.yaml이 마운트하는 보조 파일",
"config": "코드 검사 도구 설정(checkstyle, spotbugs)",
"docs": "문서",
"gradle": "wrapper, 버전 카탈로그, 모듈 registry, 시험 컨테이너 이미지 목록",
"scripts": "Gradle 밖 검사·실행 스크립트",
"src": "계층별 앱 코드",
# 파일
".dockerignore": "이미지 빌드 context(저장소 루트)에서 뺄 것",
".env.example": "env 계약",
".env.local.example": "로컬 env 예",
".gitattributes": "Git 설정",
".gitignore": "Git 설정",
".lycheeignore": "링크 검사(lychee)가 건너뛸 URL. lychee는 저장소 루트의 이 이름만 읽는다",
".tool-versions": "JDK 버전 고정",
".trivyignore.yaml": "취약점 검사 예외",
"AGENTS.md": "규칙 정본이자 작업 지도",
"CLAUDE.md": "Claude Code 진입점(AGENTS.md를 가져온다)",
"README.md": "저장소 소개",
"Dockerfile": "릴리스 이미지",
"build.gradle": "루트 빌드",
"compose.yaml": "개발 환경(하나뿐)",
"gradle.properties": "Gradle 설정",
"gradlew": "wrapper",
"gradlew.bat": "wrapper",
"renovate.json": "의존성 갱신 봇 설정",
"settings-gradle.lockfile": "settings 잠금",
"settings.gradle": "settings",
"testcontainers.properties.example": "Testcontainers 로컬 설정 예",
}
# src/ 바로 아래: 계층 폴더만. 같은 계층의 leaf는 그 계층 폴더 아래에 둔다(application/core, bootstrap/app).
# 빌드 도구와 빌드 파일은 저장소 루트에 있다. 계층이 아닌 라이브러리(메시징·gRPC)는 2026-11-08에 별도 repo로
# 나갔다(docs/work/reference/related-repos.md). 그 자리(platforms)는 다시 두지 않는다.
SRC_ALLOWED = {
"domain": "계층(domain/core)",
"shared-contract": "계층",
"application": "계층(application/core와 capability application leaf)",
"adapter": "계층(adapter leaf 묶음: inbound, outbound)",
"bootstrap": "조립 계층(Clean Architecture의 Main): 조립 루트 app과 조립 leaf",
}
# 아무도 가리키지 않으면 경고할 파일: 개발 환경과 테스트 fixture.
FIXTURE_SUFFIXES = (".sh", ".acl", ".json", ".yaml", ".yml")
FIXTURE_PREFIXES = ("compose/", "scripts/", "src/bootstrap/app/compose-lanes/")
HISTORY_PREFIXES = (
"docs/reviews/",
"docs/superpowers/",
"docs/evidence/",
"docs/study/",
"docs/adr/",
)
def tracked_files() -> list[str]:
result = subprocess.run(
["git", "ls-files", "-z"],
cwd=REPO_ROOT,
check=True,
capture_output=True,
)
return [path for path in result.stdout.decode("utf-8").split("\0") if path]
def top_level(paths: list[str], prefix: str) -> set[str]:
names = set()
for path in paths:
if not path.startswith(prefix):
continue
rest = path[len(prefix):]
names.add(rest.split("/", 1)[0])
return names
def registry_violations() -> list[str]:
modules = json.loads((REPO_ROOT / REGISTRY).read_text(encoding="utf-8"))["modules"]
problems = []
for module in modules:
source = PurePosixPath(module["source_path"])
parts = source.parts
if len(parts) < 2 or parts[0] != "src" or parts[1] not in SRC_ALLOWED:
problems.append(
f"{REGISTRY}: {module['id']} source_path {source} is not under an allowed src/ folder"
)
return problems
def is_fixture(path: str) -> bool:
if path.endswith(("README.md", ".gitignore")):
return False
name = PurePosixPath(path).name
if path.startswith(FIXTURE_PREFIXES) and name.endswith(FIXTURE_SUFFIXES):
return True
return "compose" in name and name.endswith((".yaml", ".yml"))
def unreferenced_fixtures(paths: list[str]) -> list[str]:
this_script = str(Path(__file__).resolve().relative_to(REPO_ROOT))
readable = [
p for p in paths if not p.startswith(HISTORY_PREFIXES) and p != this_script
]
texts = {}
for path in readable:
file = REPO_ROOT / path
try:
if file.stat().st_size > 2_000_000:
continue
texts[path] = file.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
continue
lonely = []
for path in sorted(p for p in paths if is_fixture(p)):
pure = PurePosixPath(path)
# The file's own path or name, or its folder when a compose file mounts the whole folder
# (./compose/redis/acl). A one-segment folder such as compose/ names too much to count.
needles = {path, pure.name}
if len(pure.parent.parts) >= 2:
needles.add(str(pure.parent))
referenced = any(
other != path and any(needle in text for needle in needles)
for other, text in texts.items()
)
if not referenced:
lonely.append(path)
return lonely
def main() -> int:
paths = tracked_files()
failures = []
for name in sorted(top_level(paths, "") - ROOT_ALLOWED.keys()):
failures.append(f"repository root: '{name}' is not in ROOT_ALLOWED")
for name in sorted(top_level(paths, "src/") - SRC_ALLOWED.keys()):
failures.append(f"src/: '{name}' is not in SRC_ALLOWED")
failures.extend(registry_violations())
for path in unreferenced_fixtures(paths):
print(f"warning: no tracked file refers to {path}")
if failures:
for failure in failures:
print(f"FAIL: {failure}", file=sys.stderr)
print(
"check-repo-layout: a new top-level entry changes the repository's shape. If it is "
"wanted, add it to the allow list in scripts/check-repo-layout.py and to the map in "
"AGENTS.md in the same change.",
file=sys.stderr,
)
return 1
print(
f"check-repo-layout: OK — {len(top_level(paths, ''))} root entries, "
f"{len(top_level(paths, 'src/'))} src/ entries, registry paths inside allowed folders"
)
return 0
if __name__ == "__main__":
sys.exit(main())