Files
clean-architecture-backend-…/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java
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

388 lines
16 KiB
Java

package dev.caskeleton.buildlogic;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Typed representation of gradle/modules.json.
*
* <p>{@code libraryGroups} are the Maven group prefixes of the libraries this repository's owner
* publishes from other repositories (design-docs {@code repo-structure/05-library-repos.md} 10.2절,
* T2). Such a library is not a project, so the project-edge rules cannot see it; a module may depend
* on one only when its row lists the coordinate in {@code allowed_libraries}. Libraries of any other
* group are not governed by the registry.
*/
public record ModuleRegistry(List<Module> modules, List<String> libraryGroups, File source) {
private static final ObjectMapper JSON = JsonMapper.builder().build();
private static final Set<String> REQUIRED_MODULE_FIELDS =
Set.of("id", "gradle_path", "source_path", "allowed_dependencies");
private static final Set<String> REQUIRED_ROOT_FIELDS = Set.of("modules");
private static final Pattern GROUP = Pattern.compile("[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*");
private static final Pattern COORDINATE =
Pattern.compile("([A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*):([A-Za-z0-9_.-]+)");
public ModuleRegistry {
modules = List.copyOf(modules);
libraryGroups = List.copyOf(libraryGroups);
Objects.requireNonNull(source, "source");
}
/** Whether {@code group} is one of {@code libraryGroups} or below one of them. */
public static boolean isOwnedGroup(List<String> libraryGroups, String group) {
return group != null
&& libraryGroups.stream()
.anyMatch(prefix -> group.equals(prefix) || group.startsWith(prefix + "."));
}
public record Module(
String id,
String gradlePath,
String sourcePath,
File sourceDirectory,
String buildName,
List<String> allowedDependencies,
List<String> allowedLibraries) {
public Module {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(gradlePath, "gradlePath");
Objects.requireNonNull(sourcePath, "sourcePath");
Objects.requireNonNull(sourceDirectory, "sourceDirectory");
Objects.requireNonNull(buildName, "buildName");
allowedDependencies = List.copyOf(allowedDependencies);
allowedLibraries = List.copyOf(allowedLibraries);
}
}
public static ModuleRegistry read(File registryFile, File repositoryRoot) {
if (!registryFile.isFile()) {
throw new IllegalStateException("Missing module registry: " + registryFile);
}
JsonNode root;
try {
root = JSON.readTree(Files.readString(registryFile.toPath(), StandardCharsets.UTF_8));
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + registryFile, exception);
}
if (root == null || !root.isObject()) {
throw new IllegalStateException("Module registry root must be a JSON object: " + registryFile);
}
Set<String> rootKeys = keys(root);
Set<String> missingRootFields = new TreeSet<>(REQUIRED_ROOT_FIELDS);
missingRootFields.removeAll(rootKeys);
if (!missingRootFields.isEmpty()) {
throw new IllegalStateException(
"Module registry root is missing " + missingRootFields + ": " + registryFile);
}
List<String> libraryGroups = List.of();
if (root.has("library_groups")) {
libraryGroups = requireStringList(root.get("library_groups"), "library_groups");
for (String group : libraryGroups) {
if (!GROUP.matcher(group).matches()) {
throw new IllegalStateException(
"Module registry 'library_groups' entry '" + group + "' is not a Maven group.");
}
}
}
JsonNode modulesNode = root.get("modules");
if (modulesNode == null || !modulesNode.isArray() || modulesNode.isEmpty()) {
throw new IllegalStateException("Module registry has no modules: " + registryFile);
}
File canonicalRoot;
try {
canonicalRoot = repositoryRoot.getCanonicalFile();
} catch (IOException exception) {
throw new UncheckedIOException("failed to canonicalize " + repositoryRoot, exception);
}
String rootPrefix = canonicalRoot.getPath() + File.separator;
Set<String> ids = new LinkedHashSet<>();
Set<String> gradlePaths = new LinkedHashSet<>();
Set<String> sourceDirectories = new LinkedHashSet<>();
List<Module> modules = new ArrayList<>();
for (int index = 0; index < modulesNode.size(); index++) {
JsonNode module = modulesNode.get(index);
if (module == null || !module.isObject()) {
throw new IllegalStateException(
"Module registry entry " + index + " must be a JSON object.");
}
Set<String> missingFields = new TreeSet<>(REQUIRED_MODULE_FIELDS);
missingFields.removeAll(keys(module));
if (!missingFields.isEmpty()) {
JsonNode rawId = module.get("id");
String named =
rawId != null && rawId.isString() && !rawId.asText().isBlank()
? "'" + rawId.asText() + "'"
: "at index " + index;
throw new IllegalStateException(
"Module registry entry " + named + " is missing " + missingFields);
}
String id = requireNonBlankText(module, "id", index);
String gradlePath = requireNonBlankText(module, "gradle_path", index);
String sourcePath = requireNonBlankText(module, "source_path", index);
// Every module belongs to the main build. The only other build (the optional gRPC platform
// build) moved to the grpc-library repository on 2026-11-08, and a row naming any build but
// this one would be included by no settings and checked by no direction gate while ci stays
// green, so the field is refused rather than read.
if (module.has("build")) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' has a 'build' field; every module belongs to the main build, so remove it.");
}
String buildName = "main";
List<String> allowedDependencies =
requireStringList(module.get("allowed_dependencies"), id, "allowed_dependencies");
if (new HashSet<>(allowedDependencies).size() != allowedDependencies.size()) {
throw new IllegalStateException(
"Module registry entry '" + id + "' contains duplicate allowed dependencies.");
}
List<String> allowedLibraries =
module.has("allowed_libraries")
? requireStringList(module.get("allowed_libraries"), id, "allowed_libraries")
: List.of();
for (String library : allowedLibraries) {
var coordinate = COORDINATE.matcher(library);
if (!coordinate.matches()) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' allows library '"
+ library
+ "', which is not a group:artifact coordinate.");
}
if (!isOwnedGroup(libraryGroups, coordinate.group(1))) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' allows library '"
+ library
+ "' outside the registry's library_groups "
+ libraryGroups
+ "; only an owned library is listed, any other dependency is not governed here.");
}
}
if (new HashSet<>(allowedLibraries).size() != allowedLibraries.size()) {
throw new IllegalStateException(
"Module registry entry '" + id + "' contains duplicate allowed libraries.");
}
if (!ids.add(id)) {
throw new IllegalStateException(
"Module registry contains duplicate module id '" + id + "'.");
}
if (!gradlePath.startsWith(":")) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' has Gradle path '"
+ gradlePath
+ "' that does not start with ':'.");
}
if (!gradlePaths.add(gradlePath)) {
throw new IllegalStateException(
"Module registry contains duplicate Gradle path '" + gradlePath + "'.");
}
if (new File(sourcePath).isAbsolute()) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' source path must be repository-root-relative: '"
+ sourcePath
+ "'.");
}
File sourceDirectory;
try {
sourceDirectory = new File(canonicalRoot, sourcePath).getCanonicalFile();
} catch (IOException exception) {
throw new UncheckedIOException("failed to canonicalize " + sourcePath, exception);
}
if (!sourceDirectory.getPath().startsWith(rootPrefix)) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' source path escapes the repository root: '"
+ sourcePath
+ "'.");
}
if (!sourceDirectory.isDirectory()) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' source path is not an existing directory: "
+ sourceDirectory);
}
if (!sourceDirectories.add(sourceDirectory.getPath())) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' resolves to duplicate or aliased canonical source directory: "
+ sourceDirectory);
}
modules.add(
new Module(
id,
gradlePath,
sourcePath,
sourceDirectory,
buildName,
allowedDependencies,
allowedLibraries));
}
return new ModuleRegistry(modules, libraryGroups, registryFile);
}
public Module byId(String id) {
return modules.stream().filter(module -> module.id().equals(id)).findFirst().orElse(null);
}
/**
* Build scripts under {@code gradleRoot} that no registered module owns, relative to it.
*
* <p>The settings plugin includes only registered modules, so a leaf directory nobody registered
* is not compiled, not tested and not compared by any gate, while {@code ci} stays green (review
* 2026-11-01 08-05). The walk skips the root's own script, every directory with its own settings
* script (a separate build, such as build-logic), build output, and the
* inside of a module's {@code src} tree, where a build script is a test fixture.
*/
public List<String> unregisteredBuildScripts(File gradleRoot) {
Path root = canonical(gradleRoot).toPath();
Set<Path> owned = new HashSet<>();
for (Module module : modules) {
owned.add(canonical(module.sourceDirectory()).toPath());
}
List<String> unregistered = new ArrayList<>();
try {
Files.walkFileTree(
root,
new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) {
String name = directory.getFileName().toString();
boolean otherBuild =
!directory.equals(root)
&& (Files.isRegularFile(directory.resolve("settings.gradle"))
|| Files.isRegularFile(directory.resolve("settings.gradle.kts")));
boolean moduleSources =
name.equals("src") && owned.contains(directory.getParent());
if (otherBuild
|| moduleSources
|| name.equals("build")
// IDE compiler output (Eclipse/VS Code `bin/`, git-ignored as `src/**/bin/`) copies
// resource build scripts such as grpc-codegen's consumer fixtures; it is not source.
|| name.equals("bin")
|| name.startsWith(".")) {
return FileVisitResult.SKIP_SUBTREE;
}
if (!directory.equals(root)
&& !owned.contains(directory)
&& (Files.isRegularFile(directory.resolve("build.gradle"))
|| Files.isRegularFile(directory.resolve("build.gradle.kts")))) {
String script =
Files.isRegularFile(directory.resolve("build.gradle"))
? "build.gradle"
: "build.gradle.kts";
unregistered.add(
root.relativize(directory.resolve(script)).toString().replace(File.separatorChar, '/'));
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException exception) {
throw new UncheckedIOException("failed to walk " + root, exception);
}
unregistered.sort(null);
return List.copyOf(unregistered);
}
private static File canonical(File file) {
try {
return file.getCanonicalFile();
} catch (IOException exception) {
throw new UncheckedIOException("failed to canonicalize " + file, exception);
}
}
public List<Module> modulesForBuild(String buildName) {
return modules.stream().filter(module -> module.buildName().equals(buildName)).toList();
}
private static Set<String> keys(JsonNode node) {
Set<String> result = new LinkedHashSet<>();
node.properties().forEach(entry -> result.add(entry.getKey()));
return result;
}
private static String requireNonBlankText(JsonNode node, String field, Object entry) {
JsonNode value = node.get(field);
if (value == null || !value.isString() || value.asText().isBlank()) {
String prefix = entry instanceof Integer ? "entry " + entry : "entry '" + entry + "'";
throw new IllegalStateException(
"Module registry " + prefix + " needs a nonblank string '" + field + "'.");
}
return value.asText();
}
private static List<String> requireStringList(JsonNode raw, String field) {
if (raw == null || !raw.isArray()) {
throw new IllegalStateException("Module registry '" + field + "' must be a list.");
}
List<String> result = new ArrayList<>();
for (int index = 0; index < raw.size(); index++) {
JsonNode value = raw.get(index);
if (value == null || !value.isString() || value.asText().isBlank()) {
throw new IllegalStateException(
"Module registry '" + field + "' has a non-string or blank entry at index " + index + ".");
}
result.add(value.asText());
}
return List.copyOf(result);
}
private static List<String> requireStringList(JsonNode raw, String id, String field) {
if (raw == null || !raw.isArray()) {
throw new IllegalStateException(
"Module registry entry '" + id + "' needs a '" + field + "' list.");
}
List<String> result = new ArrayList<>();
for (int index = 0; index < raw.size(); index++) {
JsonNode value = raw.get(index);
if (value == null || !value.isString() || value.asText().isBlank()) {
throw new IllegalStateException(
"Module registry entry '"
+ id
+ "' has a non-string or blank "
+ field
+ " entry at index "
+ index
+ ".");
}
result.add(value.asText());
}
return List.copyOf(result);
}
}