package dev.caskeleton.buildlogic.architecture; import dev.caskeleton.buildlogic.ModuleRegistry; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.ExternalModuleDependency; import org.gradle.api.artifacts.ProjectDependency; import org.gradle.api.artifacts.result.ResolvedComponentResult; import org.gradle.api.provider.Provider; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; public final class ArchitecturePlugin implements Plugin { private static final List PRODUCTION_DECLARATIONS = List.of("api", "implementation", "compileOnly", "runtimeOnly"); private static final List APPLICATION_CLASSPATHS = List.of( "compileClasspath", "runtimeClasspath", "testCompileClasspath", "testRuntimeClasspath"); @Override public void apply(Project project) { Project root = project.getRootProject(); // The Gradle root is the repository root: it owns the registry, and every source_path in the // registry is relative to it. File repositoryRoot = root.getProjectDir(); File registryFile = new File(repositoryRoot, "gradle/modules.json"); ModuleRegistry registry = ModuleRegistry.read(registryFile, repositoryRoot); List modules = registry.modulesForBuild("main"); List registryViolations = registryViolations(registry, modules); var clean = project .getTasks() .register( "verifyCleanArchitectureDependencies", VerifyCleanArchitectureDependenciesTask.class, task -> { task.setGroup("verification"); task.setDescription("Verifies Clean Architecture project dependency direction."); task.getRegistryFile().fileValue(registryFile); task.getRegistryViolations().set(registryViolations); task.getUnregisteredBuildScripts() .set(registry.unregisteredBuildScripts(root.getProjectDir())); }); var purity = project .getTasks() .register( "verifyApplicationCoreDependencyPurity", task -> { task.setGroup("verification"); task.setDescription( "Verifies domain-core, shared-contract and every application-* module have only" + " project production dependencies and no framework on their classpaths."); }); var ignoredSources = project .getTasks() .register( "verifyNoIgnoredSourcePackages", VerifyNoIgnoredSourcePackagesTask.class, task -> { task.setGroup("verification"); task.setDescription( "Fails when a Java source file lives in a package that Git ignores or would" + " ignore."); task.getBuildRoot().set(root.getLayout().getProjectDirectory()); }); project .getGradle() .projectsEvaluated( ignored -> { Set declaredModules = new HashSet<>(); root.getSubprojects().stream() .filter(sub -> sub.getChildProjects().isEmpty()) .forEach(sub -> declaredModules.add(sub.getPath().replaceFirst("^:", ""))); // One task per module, registered in the project that owns the configurations. The // root task used to walk every other project and resolve its `compileClasspath`, // which asks Gradle for state another project holds the lock on — with // `org.gradle.parallel=true` that is a hard failure, and it is why the flag was // turned off instead of the verification moved. List moduleTaskPaths = new ArrayList<>(); for (ModuleRegistry.Module module : modules) { Project owner = root.project(module.gradlePath()); Set allowed = new HashSet<>(); for (String dependencyId : module.allowedDependencies()) { ModuleRegistry.Module dependency = registry.byId(dependencyId); if (dependency != null) { allowed.add(dependency.gradlePath().replaceFirst("^:", "")); } } Set declaredEdges = declaredProjectEdges(owner); Set declaredLibraries = declaredLibraryEdges(owner, registry.libraryGroups()); Provider compileClasspathRoot = owner .getConfigurations() .getByName("compileClasspath") .getIncoming() .getResolutionResult() .getRootComponent(); String moduleName = module.gradlePath().replaceFirst("^:", ""); owner .getTasks() .register( "verifyModuleDependencyDirection", VerifyModuleDependencyDirectionTask.class, task -> { task.setGroup("verification"); task.setDescription( "Verifies this module's declared and compile-visible project edges" + " against the architecture registry."); task.getModuleName().set(moduleName); task.getAllowedDependencies().set(allowed); task.getDeclaredProjectEdges().set(declaredEdges); task.getLibraryGroups().set(registry.libraryGroups()); task.getAllowedLibraries().set(module.allowedLibraries()); task.getDeclaredLibraryEdges().set(declaredLibraries); task.getCompileClasspathRoot().set(compileClasspathRoot); }); moduleTaskPaths.add(module.gradlePath() + ":verifyModuleDependencyDirection"); } clean.configure( task -> { task.getDeclaredModules().set(declaredModules); task.getGovernedModules() .set( modules.stream() .map(module -> module.gradlePath().replaceFirst("^:", "")) .toList()); task.dependsOn(moduleTaskPaths); }); // Same ownership rule as the direction check: the task that resolves a pure // module's classpaths lives in that module. domain-core and shared-contract are pure // too (HS1): without them a framework dependency added there passed the build and // was caught only if some class happened to import it. List purityTaskPaths = new ArrayList<>(); for (ModuleRegistry.Module module : modules) { if (!isPure(module.id())) { continue; } Project application = root.project(module.gradlePath()); Map> production = new LinkedHashMap<>(); for (String name : PRODUCTION_DECLARATIONS) { Configuration configuration = application.getConfigurations().findByName(name); if (configuration != null) { production.put(name, productionDeclarations(configuration)); } } Map> classpathRoots = new LinkedHashMap<>(); for (String name : APPLICATION_CLASSPATHS) { classpathRoots.put( name, application .getConfigurations() .getByName(name) .getIncoming() .getResolutionResult() .getRootComponent()); } String applicationPath = module.gradlePath(); application .getTasks() .register( "verifyModuleDependencyPurity", VerifyApplicationCoreDependencyPurityTask.class, task -> { task.setGroup("verification"); task.setDescription( "Verifies this application module declares only project production" + " dependencies and carries no diagnostic framework."); task.getModulePath().set(applicationPath); task.getProductionDeclarations().set(production); classpathRoots.forEach( (name, rootComponent) -> task.getResolvedClasspathRoots().put(name, rootComponent)); }); purityTaskPaths.add(module.gradlePath() + ":verifyModuleDependencyPurity"); } purity.configure(task -> task.dependsOn(purityTaskPaths)); // Every source set of every project — testFixtures, integrationTest, systemTest and // the sample included — because a file Git drops is lost whichever lane owns it. // Directories under a build directory are generated and never committed. List sourceRoots = new ArrayList<>(); for (Project sub : root.getSubprojects()) { SourceSetContainer sourceSets = sub.getExtensions().findByType(SourceSetContainer.class); if (sourceSets == null) { continue; } Path buildDirectory = sub.getLayout().getBuildDirectory().get().getAsFile().toPath(); for (SourceSet sourceSet : sourceSets) { for (File sourceRoot : sourceSet.getJava().getSrcDirs()) { if (!sourceRoot.toPath().startsWith(buildDirectory)) { sourceRoots.add(sourceRoot); } } } } ignoredSources.configure(task -> task.getSourceRoots().from(sourceRoots)); }); project .getTasks() .register( "architectureCheck", task -> { task.setGroup("verification"); task.setDescription("Runs the build's architecture invariants."); task.dependsOn(clean, purity, ignoredSources); }); } private static boolean isPure(String moduleId) { return moduleId.startsWith("application-") || moduleId.equals("domain-core") || moduleId.equals("shared-contract"); } /** * This module's declared {@code project(...)} edges, read while the owning project is configured. * *

Read here rather than in the task action: a {@link Configuration} cannot be stored in the * configuration cache, and every declaration this reads is final by {@code projectsEvaluated}. */ private static Set declaredProjectEdges(Project owner) { Set edges = new TreeSet<>(); for (String name : PRODUCTION_DECLARATIONS) { Configuration configuration = owner.getConfigurations().findByName(name); if (configuration == null) { continue; } configuration .getDependencies() .withType(ProjectDependency.class) .forEach(dependency -> edges.add(dependency.getPath().replaceFirst("^:", ""))); } return edges; } /** * This module's declared dependencies on an owned library ({@code group:artifact}, the group under * one of the registry's {@code library_groups}), read the same way and from the same production * configurations as the project edges, {@code runtimeOnly} included. */ private static Set declaredLibraryEdges(Project owner, List libraryGroups) { Set edges = new TreeSet<>(); if (libraryGroups.isEmpty()) { return edges; } for (String name : PRODUCTION_DECLARATIONS) { Configuration configuration = owner.getConfigurations().findByName(name); if (configuration == null) { continue; } configuration .getDependencies() .withType(ExternalModuleDependency.class) .forEach( dependency -> { if (ModuleRegistry.isOwnedGroup(libraryGroups, dependency.getGroup())) { edges.add(dependency.getGroup() + ":" + dependency.getName()); } }); } return edges; } /** * One production configuration's declarations, tagged by kind. * *

The tag, not a filter, is what is captured: deciding which kind is a violation is the purity * task's rule, and moving it here would put the rule in the collector. */ private static List productionDeclarations(Configuration configuration) { List declarations = new ArrayList<>(); configuration .getDependencies() .forEach( dependency -> { if (dependency instanceof ProjectDependency projectDependency) { declarations.add( VerifyApplicationCoreDependencyPurityTask.PROJECT_DECLARATION + ":" + projectDependency.getPath()); } else { String group = dependency.getGroup() == null ? "" : dependency.getGroup(); declarations.add("module:" + group + ":" + dependency.getName()); } }); return List.copyOf(declarations); } private static List registryViolations( ModuleRegistry registry, List modules) { List violations = new ArrayList<>(); for (ModuleRegistry.Module module : modules) { // The layers stay free of the owner's libraries by the registry itself, not only because the // purity check happens to refuse every non-project declaration in them. if (isPure(module.id()) && !module.allowedLibraries().isEmpty()) { violations.add( "'" + module.id() + "' is a layer module (domain-core, shared-contract, application-*) and may allow no" + " library, but allows " + module.allowedLibraries()); } for (String dependencyId : module.allowedDependencies()) { if (dependencyId.equals(module.id())) { violations.add("'" + module.id() + "' declares itself as an allowed dependency"); continue; } ModuleRegistry.Module dependency = registry.byId(dependencyId); if (dependency == null) { violations.add( "'" + module.id() + "' allows unknown dependency id '" + dependencyId + "'"); } else if (!dependency.buildName().equals(module.buildName())) { violations.add( "'" + module.id() + "' allows cross-build dependency id '" + dependencyId + "'"); } } } return List.copyOf(violations); } }