Files
clean-architecture-backend-…/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java
T
DongHyeonka 1388c06a9f refactor(layout)!: Gradle 루트와 계층 폴더를 옮긴다(옮기기만)
문제: Gradle 루트가 src/라서 빌드 도구(build-logic, gradle, config, 빌드
파일)가 계층 코드 폴더 옆에 섞여 있다. composition과 app-bootstrap은 같은
조립 계층인데 폴더가 따로이고, application 모듈 넷은 최상위에 흩어져 있다.
「Gradle은 src/에서 실행」이라는 예외 규칙이 모든 문서와 스크립트에 퍼졌다.

고른 방법: 저장소 루트를 Gradle 루트로 하고 src/에는 계층 코드만 둔다
(design-docs repo-structure/01-backend-layout.md 6.1절 가-2·가-3, 소유자
승인 2026-11-07). 이 커밋은 git mv만 한다. 이름 바꾸기 감지가 1541개
파일 모두를 R100으로 잡도록 내용을 바꾸지 않았다. 바뀐 곳은 둘뿐이다:
src/.gitignore의 줄을 루트 .gitignore로 옮겼다.

- 빌드 파일, gradle/, build-logic/ → 저장소 루트
- config/checkstyle·spotbugs → config/ (코드 검사 도구 설정만)
- registry config/architecture/modules.json → gradle/modules.json,
  시험 이미지 config/testing/container-images.properties
  → gradle/container-images.properties, registry 설명 → gradle/README.md
- Dockerfile, .dockerignore, .env*.example → 저장소 루트
- src/README.md(빌드·env 참조) → docs/build.md
- src/domain-core → src/domain/core,
  src/application-* → src/application/*,
  src/app-bootstrap → src/bootstrap/app,
  src/composition/* → src/bootstrap/*
- 기능 생성 템플릿 scripts/feature-scaffold/{templates,probes}/src/ 아래도
  같은 모양으로(domain/core, application/core, bootstrap/app)

위험: 이 커밋만으로는 빌드되지 않는다. 경로를 부르는 곳은 다음 커밋이
고친다. 두 커밋을 나눈 것은 파생 서비스가 merge할 때 이름 바꾸기와 내용
변경을 따로 보게 하려는 것이다.

검증: git diff --cached -M --name-status 에서 R100 1541개, 그 밖은
.gitignore 수정과 src/.gitignore 삭제뿐.

BREAKING CHANGE: 모든 빌드 파일과 계층 폴더의 경로가 바뀐다. 옛 경로 →
새 경로 표와 받는 순서는 docs/upgrade/2026-11-relayout.md에 있다.
Refs: design-docs repo-structure/01-backend-layout.md 6.1절
2026-11-11 21:04:21 +09:00

474 lines
20 KiB
Java

package dev.caskeleton.buildlogic.strictlane;
import dev.caskeleton.buildlogic.RequiredTestExecution;
import java.io.File;
import java.util.List;
import java.util.function.Predicate;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.GradleException;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.testing.Test;
import org.gradle.testing.base.TestingExtension;
public final class StrictTestLanePlugin implements Plugin<Project> {
/**
* The switch a performance lane's machine-dependent bounds used to sit behind, now always on.
*
* <p>Each leaf declared it with its own default — {@code false} for the httpclient lane, {@code
* true} for the Mongo lane — and only the workflows set it. {@code ./gradlew :performanceCheck}
* typed by hand therefore passed with the httpclient heap bound compared to nothing (the
* 2026-11-05 desktop gate). The convention owns it now: every performance lane's test JVM gets
* {@code true}, so a test that still reads the switch asserts, and a build that sets it to
* anything else fails before the lane runs. Nothing in this repository reads it any more; the
* value is for tests written against the old switch, such as a derived service's.
*/
static final String PERFORMANCE_ASSERTIONS = "performance.assertions.enabled";
@Override
public void apply(Project project) {
project.getPluginManager().withPlugin("java", ignored -> configure(project));
}
private static void configure(Project project) {
NamedDomainObjectContainer<StrictTestLaneSpec> lanes =
project.container(StrictTestLaneSpec.class, StrictTestLaneSpec::new);
StrictTestLaneExtension extension =
project
.getExtensions()
.create("strictTestLanes", StrictTestLaneExtension.class, lanes);
String ownerPath = project.getPath();
JavaPluginExtension java = project.getExtensions().getByType(JavaPluginExtension.class);
lanes.all(
lane -> {
// A lane named after the JVM test suite it runs is that suite's own Test task: the suite
// (jvm-test-suite, which replaced ca.auxiliary-source-set) registers it, the lane makes it
// strict. Any other name collision still fails in register().
TaskProvider<Test> laneTask =
isOwnSuiteTask(project, lane)
? project.getTasks().named(lane.getName(), Test.class)
: project.getTasks().register(lane.getName(), Test.class);
laneTask.configure(test -> configureLane(project, java, ownerPath, lane, test));
project
.getGradle()
.getTaskGraph()
.whenReady(
graph -> {
boolean selected =
graph.getAllTasks().stream().anyMatch(task -> task == laneTask.get());
if (!selected) {
return;
}
SourceSet sourceSet = java.getSourceSets().getByName(lane.getSourceSet());
if (sourceSet.getAllSource().getFiles().isEmpty()) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ ownerPath
+ " has no sources in source set '"
+ lane.getSourceSet()
+ "'. Gradle would skip it as NO-SOURCE and report success for a lane that ran nothing.");
}
});
});
project.afterEvaluate(
ignored -> lanes.forEach(lane -> validateLane(project, lane)));
lanes.all(
lane ->
project.afterEvaluate(
ignored -> {
if (!lane.isMainStage()) {
return;
}
String tag = lane.getTag();
if (tag == null || tag.isBlank()) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ ownerPath
+ " is a main-stage lane without a tag; the tag is what keeps its tests out of `test`.");
}
project
.getTasks()
.named("test", Test.class)
.configure(test -> test.useJUnitPlatform(options -> options.excludeTags(tag)));
project
.getTasks()
.matching(task -> task.getName().equals("mainCheck"))
.configureEach(task -> task.dependsOn(lane.getName()));
}));
registerAggregate(
project,
extension,
"strictTestLaneCheck",
"Runs every strict test lane this leaf declares.",
lane -> true);
registerAggregate(
project,
extension,
"testLaneCheck",
"Runs this leaf's hermetic test lanes.",
lane -> lane.getCategory() == TestLaneCategory.TEST);
registerAggregate(
project,
extension,
"integrationTestLaneCheck",
"Runs this leaf's external-infrastructure integration test lanes.",
lane -> lane.getCategory() == TestLaneCategory.INTEGRATION);
registerAggregate(
project,
extension,
"systemTestLaneCheck",
"Runs this leaf's full application/system test lanes.",
lane -> lane.getCategory() == TestLaneCategory.SYSTEM);
registerAggregate(
project,
extension,
"architectureTestLaneCheck",
"Runs this leaf's architecture test lanes.",
lane -> lane.getCategory() == TestLaneCategory.ARCHITECTURE);
registerAggregate(
project,
extension,
"performanceTestLaneCheck",
"Runs this leaf's performance test lanes.",
lane -> lane.getCategory() == TestLaneCategory.PERFORMANCE);
}
private static void registerAggregate(
Project project,
StrictTestLaneExtension extension,
String taskName,
String description,
Predicate<StrictTestLaneSpec> selection) {
project
.getTasks()
.register(
taskName,
task -> {
task.setGroup("verification");
task.setDescription(description);
task.dependsOn(
project.provider(
() ->
extension.getLanes().stream()
.filter(lane -> lane.getExplicitOnlyReason() == null)
.filter(selection)
.map(lane -> project.getTasks().named(lane.getName()))
.toList()));
// An explicit-only lane is left out, and the aggregate says so when it runs, so a
// green aggregate is never read as covering it.
var leftOut =
project.provider(
() ->
extension.getLanes().stream()
.filter(lane -> lane.getExplicitOnlyReason() != null)
.filter(selection)
.map(
lane ->
"strict test lane '"
+ lane.getName()
+ "' in "
+ project.getPath()
+ " runs only when named: "
+ lane.getExplicitOnlyReason()
+ ".")
.toList());
task.doLast(
running -> leftOut.get().forEach(note -> running.getLogger().lifecycle(note)));
});
}
private static void configureLane(
Project project,
JavaPluginExtension java,
String ownerPath,
StrictTestLaneSpec lane,
Test test) {
SourceSet sourceSet = java.getSourceSets().getByName(lane.getSourceSet());
if (startsARealServer(lane)) {
// INTEGRATION, SYSTEM and PERFORMANCE lanes start a server, a container or both, and
// several of those at once under `org.gradle.parallel` makes the machine decide the result.
// One slot for all of them, build-wide — ordering them inside a leaf was not enough, because
// the web and websocket lanes contend with each other across leaves. An ARCHITECTURE lane
// imports classes and starts nothing, so it does not wait for that slot (review 2026-11-01
// 08-06).
test.usesService(
project
.getGradle()
.getSharedServices()
.registerIfAbsent(
"exclusiveRealServerLane",
ExclusiveRealServerLaneService.class,
specification -> specification.getMaxParallelUsages().set(1)));
}
test.setGroup(
lane.getGroup() == null || lane.getGroup().isBlank() ? "verification" : lane.getGroup());
test.setDescription(lane.getDescription());
test.setTestClassesDirs(sourceSet.getOutput().getClassesDirs());
test.setClasspath(sourceSet.getRuntimeClasspath());
String tag = lane.getTag();
if (tag != null && !tag.trim().isEmpty()) {
test.useJUnitPlatform(options -> options.includeTags(tag));
} else {
test.useJUnitPlatform();
}
List<String> required = lane.getRequiredTests();
if (!required.isEmpty()) {
test.filter(
filter -> {
required.forEach(filter::includeTestsMatching);
filter.setFailOnNoMatchingTests(true);
});
}
test.getFailOnNoDiscoveredTests().set(true);
// A lane whose result follows from its declared inputs may be up to date or come from the
// build cache: the result it reuses was produced by a run that passed the checks below (no test
// ran, a skip, a required test missing), with the same classes, filter and properties. A lane
// whose result depends on what Gradle cannot see runs every time (review 2026-11-01 08-02).
// The verdict below reads the lane's policy, not only its test results, so the policy is an
// input: tightening it (rejectSkipped = true, another required test, another category) must
// judge the lane again rather than reuse a result produced under the looser policy. Without
// this a lane that skipped a test stayed green, up to date and from the build cache, after
// rejectSkipped was switched on (review 2026-11-03 RR-06-02).
test.getInputs()
.property("strictLane.rejectSkipped", project.provider(() -> rejectsSkipped(lane)));
test.getInputs()
.property("strictLane.requiredTests", project.provider(lane::getRequiredTests));
test.getInputs()
.property(
"strictLane.tag", project.provider(() -> lane.getTag() == null ? "" : lane.getTag()));
test.getInputs()
.property("strictLane.category", project.provider(() -> lane.getCategory().name()));
test.getInputs().property("strictLane.mainStage", project.provider(lane::isMainStage));
String rerunReason = rerunReason(lane);
if (rerunReason != null) {
test.getOutputs().upToDateWhen(ignored -> false);
test.getOutputs().doNotCacheIf(rerunReason, ignored -> true);
}
boolean performance = lane.getCategory() == TestLaneCategory.PERFORMANCE;
if (performance) {
// Set before the lane's own JVM arguments and system properties — Gradle turns a -D in
// jvmArgs into a system property — so a lane that still declares the switch replaces this
// value and the check below sees the override, instead of the override disappearing silently.
test.systemProperty(PERFORMANCE_ASSERTIONS, "true");
Provider<String> requested = project.getProviders().gradleProperty(PERFORMANCE_ASSERTIONS);
String laneName = lane.getName();
test.doFirst(
running -> requireAssertionsOn(laneName, ownerPath, requested.getOrNull(), (Test) running));
}
if (lane.getMaxHeapSize() != null && !lane.getMaxHeapSize().isBlank()) {
test.setMaxHeapSize(lane.getMaxHeapSize());
}
if (!lane.getJvmArgs().isEmpty()) {
test.setJvmArgs(lane.getJvmArgs());
}
lane.getShouldRunAfter().forEach(test::shouldRunAfter);
lane.getDependsOn().forEach(test::dependsOn);
lane.getSystemProperties().forEach(test::systemProperty);
for (File directory : lane.getInputDirectories()) {
test.getInputs().dir(directory).withPathSensitivity(PathSensitivity.RELATIVE);
}
StrictLaneExecutionTracker tracker = new StrictLaneExecutionTracker(!required.isEmpty());
test.addTestListener(tracker);
test.doLast(
ignored -> {
if (tracker.executedCount() == 0L) {
String detail;
if (tracker.skippedCount() > 0L) {
detail =
"; all "
+ tracker.skippedCount()
+ " test(s) it selected were skipped (@Disabled or an unmet assumption), and a skip is not a result";
} else if (tag != null && !tag.trim().isEmpty()) {
detail =
"; its tag '"
+ tag
+ "' matches nothing in source set '"
+ lane.getSourceSet()
+ "'";
} else if (required.isEmpty()) {
detail = " in source set '" + lane.getSourceSet() + "'";
} else {
detail = "; its required tests " + required + " matched no executable test";
}
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ ownerPath
+ " executed no test"
+ detail
+ " — a lane that runs nothing reports success for whatever it was meant to prove.");
}
if (rejectsSkipped(lane) && tracker.skippedCount() > 0L) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ ownerPath
+ " forbids skipped tests but observed "
+ tracker.skippedCount()
+ " skipped test(s)."
+ (performance
? " A performance lane always does: a skipped test is a bound nobody measured."
: ""));
}
if (!required.isEmpty()) {
List<String> absent =
RequiredTestExecution.absent(required, tracker.executedSelectors());
if (!absent.isEmpty()) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ ownerPath
+ " required "
+ absent
+ " and executed neither. A lane that named a test it no longer runs proves less than it claims.");
}
}
});
if (lane.getCustomize() != null) {
lane.getCustomize().execute(test);
}
}
/**
* A performance lane rejects skipped tests whatever it declares: its tests are its bounds, and a
* skip is a bound the run reports as passed without comparing it to anything.
*/
private static boolean rejectsSkipped(StrictTestLaneSpec lane) {
return lane.isRejectSkipped() || lane.getCategory() == TestLaneCategory.PERFORMANCE;
}
/**
* Fails a performance lane, before any test runs, when the build or the lane turns its bounds off.
* {@code true} from the build is accepted, so a command that still passes it keeps working.
*/
private static void requireAssertionsOn(
String laneName, String ownerPath, String requestedByBuild, Test test) {
if (requestedByBuild != null && !Boolean.parseBoolean(requestedByBuild.trim())) {
throw new GradleException(
"strict test lane '"
+ laneName
+ "' in "
+ ownerPath
+ " is a performance lane, and this build sets "
+ PERFORMANCE_ASSERTIONS
+ "="
+ requestedByBuild
+ " (-P"
+ PERFORMANCE_ASSERTIONS
+ ", or -Dorg.gradle.project."
+ PERFORMANCE_ASSERTIONS
+ " in GRADLE_OPTS). A performance lane asserts its bounds in every run: one without"
+ " them measures nothing it can fail on and still reports success. Remove the"
+ " property or set it to true.");
}
Object effective = test.getSystemProperties().get(PERFORMANCE_ASSERTIONS);
if (effective == null || !Boolean.parseBoolean(String.valueOf(effective).trim())) {
throw new GradleException(
"strict test lane '"
+ laneName
+ "' in "
+ ownerPath
+ " is a performance lane, but its test JVM would get "
+ PERFORMANCE_ASSERTIONS
+ "="
+ effective
+ " from this project's build (a lane systemProperty or jvmArgs, or a block that"
+ " configures the task). The strict-lane convention sets it to true for every"
+ " performance lane; delete the override.");
}
}
private static boolean startsARealServer(StrictTestLaneSpec lane) {
return lane.getCategory() != TestLaneCategory.TEST
&& lane.getCategory() != TestLaneCategory.ARCHITECTURE;
}
/**
* Why this lane's earlier result may not stand for this run, or {@code null} when it may.
*
* <ul>
* <li>INTEGRATION, SYSTEM, PERFORMANCE: a container image pulled by tag, the network, the clock
* and the machine's load are not task inputs, so the same inputs prove nothing about the
* same result.
* <li>A main-stage lane: it compares the leaf with repository documents it does not declare as
* inputs, and it is the stage whose run is the evidence.
* </ul>
*/
private static String rerunReason(StrictTestLaneSpec lane) {
if (startsARealServer(lane)) {
return "a "
+ lane.getCategory()
+ " lane depends on images, network and time that are not task inputs";
}
if (lane.isMainStage()) {
return "a main-stage lane reads repository documents that are not task inputs";
}
return null;
}
private static boolean isOwnSuiteTask(Project project, StrictTestLaneSpec lane) {
TestingExtension testing = project.getExtensions().findByType(TestingExtension.class);
return testing != null
&& lane.getName().equals(lane.getSourceSet())
&& testing.getSuites().getNames().contains(lane.getName())
&& project.getTasks().getNames().contains(lane.getName());
}
private static void validateLane(Project project, StrictTestLaneSpec lane) {
boolean hasTag = lane.getTag() != null && !lane.getTag().trim().isEmpty();
boolean hasRequired = !lane.getRequiredTests().isEmpty();
if (!hasTag && !hasRequired && lane.getSourceSet().equals("test")) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ project.getPath()
+ " selects nothing while running over the shared 'test' source set; it would run the entire suite under a name that claims it ran one thing. Give it a tag, a set of required tests, or a source set of its own.");
}
if (hasTag && hasRequired) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ project.getPath()
+ " declares both a tag and required tests; pick one selection.");
}
if (lane.getDescription() == null || lane.getDescription().trim().isEmpty()) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ project.getPath()
+ " declares no description");
}
if (project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets().findByName(lane.getSourceSet()) == null) {
throw new GradleException(
"strict test lane '"
+ lane.getName()
+ "' in "
+ project.getPath()
+ " references unknown source set '"
+ lane.getSourceSet()
+ "'.");
}
}
}