-
Notifications
You must be signed in to change notification settings - Fork 38.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This commit adds a new custom build Plugin, the `ArchitecturePlugin`. This plugin is using ArchUnit to enforce several rules in the main sources of the project: * All "package-info" should be `@NullMarked` * Classes should not import forbidden types (like "reactor.core.support.Assert" * Java Classes should not import "org.jetbrains.annotations.*" annotations * Classes should not call "toLowerCase"/"toUpperCase" without a Locale * There should not be any package tangle Duplicate rules were removed from checkstyle as a result. Note, these checks only consider the "main" source sets, so test fixtures and tests are not considered. Repackaged sources like JavaPoet, CGLib and ASM are also excluded from the analysis. Closes gh-34276
- Loading branch information
Showing
8 changed files
with
317 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
132 changes: 132 additions & 0 deletions
132
buildSrc/src/main/java/org/springframework/build/architecture/ArchitectureCheck.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
/* | ||
* Copyright 2002-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.build.architecture; | ||
|
||
import com.tngtech.archunit.core.domain.JavaClasses; | ||
import com.tngtech.archunit.core.importer.ClassFileImporter; | ||
import com.tngtech.archunit.lang.ArchRule; | ||
import com.tngtech.archunit.lang.EvaluationResult; | ||
import java.io.File; | ||
import java.io.IOException; | ||
import java.nio.file.Files; | ||
import java.nio.file.StandardOpenOption; | ||
import java.util.List; | ||
import org.gradle.api.DefaultTask; | ||
import org.gradle.api.GradleException; | ||
import org.gradle.api.Task; | ||
import org.gradle.api.file.DirectoryProperty; | ||
import org.gradle.api.file.FileCollection; | ||
import org.gradle.api.file.FileTree; | ||
import org.gradle.api.provider.ListProperty; | ||
import org.gradle.api.provider.Property; | ||
import org.gradle.api.tasks.IgnoreEmptyDirectories; | ||
import org.gradle.api.tasks.Input; | ||
import org.gradle.api.tasks.InputFiles; | ||
import org.gradle.api.tasks.Internal; | ||
import org.gradle.api.tasks.Optional; | ||
import org.gradle.api.tasks.OutputDirectory; | ||
import org.gradle.api.tasks.PathSensitive; | ||
import org.gradle.api.tasks.PathSensitivity; | ||
import org.gradle.api.tasks.SkipWhenEmpty; | ||
import org.gradle.api.tasks.TaskAction; | ||
|
||
import static org.springframework.build.architecture.ArchitectureRules.*; | ||
|
||
/** | ||
* {@link Task} that checks for architecture problems. | ||
* | ||
* @author Andy Wilkinson | ||
* @author Scott Frederick | ||
*/ | ||
public abstract class ArchitectureCheck extends DefaultTask { | ||
|
||
private FileCollection classes; | ||
|
||
public ArchitectureCheck() { | ||
getOutputDirectory().convention(getProject().getLayout().getBuildDirectory().dir(getName())); | ||
getProhibitObjectsRequireNonNull().convention(true); | ||
getRules().addAll(packageInfoShouldBeNullMarked(), | ||
classesShouldNotImportForbiddenTypes(), | ||
javaClassesShouldNotImportKotlinAnnotations(), | ||
allPackagesShouldBeFreeOfTangles(), | ||
noClassesShouldCallStringToLowerCaseWithoutLocale(), | ||
noClassesShouldCallStringToUpperCaseWithoutLocale()); | ||
getRuleDescriptions().set(getRules().map((rules) -> rules.stream().map(ArchRule::getDescription).toList())); | ||
} | ||
|
||
@TaskAction | ||
void checkArchitecture() throws IOException { | ||
JavaClasses javaClasses = new ClassFileImporter() | ||
.importPaths(this.classes.getFiles().stream().map(File::toPath).toList()); | ||
List<EvaluationResult> violations = getRules().get() | ||
.stream() | ||
.map((rule) -> rule.evaluate(javaClasses)) | ||
.filter(EvaluationResult::hasViolation) | ||
.toList(); | ||
File outputFile = getOutputDirectory().file("failure-report.txt").get().getAsFile(); | ||
outputFile.getParentFile().mkdirs(); | ||
if (!violations.isEmpty()) { | ||
StringBuilder report = new StringBuilder(); | ||
for (EvaluationResult violation : violations) { | ||
report.append(violation.getFailureReport()); | ||
report.append(String.format("%n")); | ||
} | ||
Files.writeString(outputFile.toPath(), report.toString(), StandardOpenOption.CREATE, | ||
StandardOpenOption.TRUNCATE_EXISTING); | ||
throw new GradleException("Architecture check failed. See '" + outputFile + "' for details."); | ||
} | ||
else { | ||
outputFile.createNewFile(); | ||
} | ||
} | ||
|
||
public void setClasses(FileCollection classes) { | ||
this.classes = classes; | ||
} | ||
|
||
@Internal | ||
public FileCollection getClasses() { | ||
return this.classes; | ||
} | ||
|
||
@InputFiles | ||
@SkipWhenEmpty | ||
@IgnoreEmptyDirectories | ||
@PathSensitive(PathSensitivity.RELATIVE) | ||
final FileTree getInputClasses() { | ||
return this.classes.getAsFileTree(); | ||
} | ||
|
||
@Optional | ||
@InputFiles | ||
@PathSensitive(PathSensitivity.RELATIVE) | ||
public abstract DirectoryProperty getResourcesDirectory(); | ||
|
||
@OutputDirectory | ||
public abstract DirectoryProperty getOutputDirectory(); | ||
|
||
@Internal | ||
public abstract ListProperty<ArchRule> getRules(); | ||
|
||
@Internal | ||
public abstract Property<Boolean> getProhibitObjectsRequireNonNull(); | ||
|
||
@Input | ||
// The rules themselves can't be an input as they aren't serializable so we use | ||
// their descriptions instead | ||
abstract ListProperty<String> getRuleDescriptions(); | ||
} |
74 changes: 74 additions & 0 deletions
74
buildSrc/src/main/java/org/springframework/build/architecture/ArchitecturePlugin.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
/* | ||
* Copyright 2002-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.build.architecture; | ||
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
import org.gradle.api.Plugin; | ||
import org.gradle.api.Project; | ||
import org.gradle.api.Task; | ||
import org.gradle.api.plugins.JavaPlugin; | ||
import org.gradle.api.plugins.JavaPluginExtension; | ||
import org.gradle.api.tasks.SourceSet; | ||
import org.gradle.api.tasks.TaskProvider; | ||
import org.gradle.language.base.plugins.LifecycleBasePlugin; | ||
|
||
/** | ||
* {@link Plugin} for verifying a project's architecture. | ||
* | ||
* @author Andy Wilkinson | ||
*/ | ||
public class ArchitecturePlugin implements Plugin<Project> { | ||
|
||
@Override | ||
public void apply(Project project) { | ||
project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> registerTasks(project)); | ||
} | ||
|
||
private void registerTasks(Project project) { | ||
JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class); | ||
List<TaskProvider<ArchitectureCheck>> architectureChecks = new ArrayList<>(); | ||
for (SourceSet sourceSet : javaPluginExtension.getSourceSets()) { | ||
if (sourceSet.getName().contains("test")) { | ||
// skip test source sets. | ||
continue; | ||
} | ||
TaskProvider<ArchitectureCheck> checkArchitecture = project.getTasks() | ||
.register(taskName(sourceSet), ArchitectureCheck.class, | ||
(task) -> { | ||
task.setClasses(sourceSet.getOutput().getClassesDirs()); | ||
task.getResourcesDirectory().set(sourceSet.getOutput().getResourcesDir()); | ||
task.dependsOn(sourceSet.getProcessResourcesTaskName()); | ||
task.setDescription("Checks the architecture of the classes of the " + sourceSet.getName() | ||
+ " source set."); | ||
task.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); | ||
}); | ||
architectureChecks.add(checkArchitecture); | ||
} | ||
if (!architectureChecks.isEmpty()) { | ||
TaskProvider<Task> checkTask = project.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME); | ||
checkTask.configure((check) -> check.dependsOn(architectureChecks)); | ||
} | ||
} | ||
|
||
private static String taskName(SourceSet sourceSet) { | ||
return "checkArchitecture" | ||
+ sourceSet.getName().substring(0, 1).toUpperCase() | ||
+ sourceSet.getName().substring(1); | ||
} | ||
|
||
} |
100 changes: 100 additions & 0 deletions
100
buildSrc/src/main/java/org/springframework/build/architecture/ArchitectureRules.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
/* | ||
* Copyright 2002-2025 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.springframework.build.architecture; | ||
|
||
import com.tngtech.archunit.core.domain.JavaClass; | ||
import com.tngtech.archunit.lang.ArchRule; | ||
import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; | ||
import com.tngtech.archunit.library.dependencies.SliceAssignment; | ||
import com.tngtech.archunit.library.dependencies.SliceIdentifier; | ||
import com.tngtech.archunit.library.dependencies.SlicesRuleDefinition; | ||
import java.util.List; | ||
|
||
abstract class ArchitectureRules { | ||
|
||
static ArchRule allPackagesShouldBeFreeOfTangles() { | ||
return SlicesRuleDefinition.slices() | ||
.assignedFrom(new SpringSlices()).should().beFreeOfCycles(); | ||
} | ||
|
||
static ArchRule noClassesShouldCallStringToLowerCaseWithoutLocale() { | ||
return ArchRuleDefinition.noClasses() | ||
.should() | ||
.callMethod(String.class, "toLowerCase") | ||
.because("String.toLowerCase(Locale.ROOT) should be used instead"); | ||
} | ||
|
||
static ArchRule noClassesShouldCallStringToUpperCaseWithoutLocale() { | ||
return ArchRuleDefinition.noClasses() | ||
.should() | ||
.callMethod(String.class, "toUpperCase") | ||
.because("String.toUpperCase(Locale.ROOT) should be used instead"); | ||
} | ||
|
||
static ArchRule packageInfoShouldBeNullMarked() { | ||
return ArchRuleDefinition.classes() | ||
.that().haveSimpleName("package-info") | ||
.should().beAnnotatedWith("org.jspecify.annotations.NullMarked") | ||
.allowEmptyShould(true); | ||
} | ||
|
||
static ArchRule classesShouldNotImportForbiddenTypes() { | ||
return ArchRuleDefinition.noClasses() | ||
.should().dependOnClassesThat() | ||
.haveFullyQualifiedName("reactor.core.support.Assert") | ||
.orShould().dependOnClassesThat() | ||
.haveFullyQualifiedName("org.slf4j.LoggerFactory") | ||
.orShould().dependOnClassesThat() | ||
.haveFullyQualifiedName("org.springframework.lang.NonNull") | ||
.orShould().dependOnClassesThat() | ||
.haveFullyQualifiedName("org.springframework.lang.Nullable"); | ||
} | ||
|
||
static ArchRule javaClassesShouldNotImportKotlinAnnotations() { | ||
return ArchRuleDefinition.noClasses() | ||
.that().haveSimpleNameNotEndingWith("Kt") | ||
.and().haveSimpleNameNotEndingWith("Dsl") | ||
.should().dependOnClassesThat() | ||
.resideInAnyPackage("org.jetbrains.annotations..") | ||
.allowEmptyShould(true); | ||
} | ||
|
||
static class SpringSlices implements SliceAssignment { | ||
|
||
private final List<String> ignoredPackages = List.of("org.springframework.asm", | ||
"org.springframework.cglib", | ||
"org.springframework.javapoet", | ||
"org.springframework.objenesis"); | ||
|
||
@Override | ||
public SliceIdentifier getIdentifierOf(JavaClass javaClass) { | ||
|
||
String packageName = javaClass.getPackageName(); | ||
for (String ignoredPackage : ignoredPackages) { | ||
if (packageName.startsWith(ignoredPackage)) { | ||
return SliceIdentifier.ignore(); | ||
} | ||
} | ||
return SliceIdentifier.of("spring framework"); | ||
} | ||
|
||
@Override | ||
public String getDescription() { | ||
return "Spring Framework Slices"; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.