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 tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; /** Typed representation of config/architecture/modules.json. */ public record ModuleRegistry(List modules, 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"); public ModuleRegistry { modules = List.copyOf(modules); Objects.requireNonNull(source, "source"); } public record Module( String id, String gradlePath, String sourcePath, File sourceDirectory, String buildName, List allowedDependencies) { 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); } } 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); } 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 one build. A row naming any other build (a typo included) would // be included by no settings and checked by no direction gate while ci stays green, so the // field is refused rather than read (the template's optional build, which used it, is gone). 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."); } 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)); } return new ModuleRegistry(modules, 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 or optional-platforms), 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 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); } }