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.
*
*
{@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 modules, List libraryGroups, File source) {
private static final ObjectMapper JSON = JsonMapper.builder().build();
private static final Set REQUIRED_MODULE_FIELDS =
Set.of("id", "gradle_path", "source_path", "allowed_dependencies");
private static final Set 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 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 allowedDependencies,
List 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 rootKeys = keys(root);
Set missingRootFields = new TreeSet<>(REQUIRED_ROOT_FIELDS);
missingRootFields.removeAll(rootKeys);
if (!missingRootFields.isEmpty()) {
throw new IllegalStateException(
"Module registry root is missing " + missingRootFields + ": " + registryFile);
}
List 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 ids = new LinkedHashSet<>();
Set gradlePaths = new LinkedHashSet<>();
Set sourceDirectories = new LinkedHashSet<>();
List 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 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 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 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.
*
* 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 unregisteredBuildScripts(File gradleRoot) {
Path root = canonical(gradleRoot).toPath();
Set owned = new HashSet<>();
for (Module module : modules) {
owned.add(canonical(module.sourceDirectory()).toPath());
}
List 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 modulesForBuild(String buildName) {
return modules.stream().filter(module -> module.buildName().equals(buildName)).toList();
}
private static Set keys(JsonNode node) {
Set 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 requireStringList(JsonNode raw, String field) {
if (raw == null || !raw.isArray()) {
throw new IllegalStateException("Module registry '" + field + "' must be a list.");
}
List 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 requireStringList(JsonNode raw, String id, String field) {
if (raw == null || !raw.isArray()) {
throw new IllegalStateException(
"Module registry entry '" + id + "' needs a '" + field + "' list.");
}
List 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);
}
}