fix(build-logic)!: 없는 주 source root와 빈 root로 API surface를 줄이지 않는다 #53

Merged
donghyeon.kang merged 2 commits from fix/api-surface-silent-roots into main 2026-11-19 16:29:40 +00:00
9 changed files with 164 additions and 68 deletions
+1 -1
View File
@@ -26,7 +26,7 @@ registry, settings, build-logic, 루트 라이프사이클이 정하는 것을
## 설정 단계에서 보지 않는 것
- 플러그인의 `apply`·`afterEvaluate`는 leaf의 `src/` 아래 소스·자원이 있는지 보지 않는다. 이미지 빌드의 의존성 단계(`Dockerfile` builder)는 그것을 복사하지 않은 채 모든 project를 설정하고 `verifyDependencyLocks`를 돈다. 그 단계가 복사하는 것(Gradle wrapper와 설정, build 스크립트와 lockfile, `release/` 데이터, `build-logic/`)의 정본은 `Dockerfile`의 그 단계 `COPY` 줄이다. 그 단계에서 설정이 실패하면 이미지가 만들어지지 않는다.
- 파일이 있어야 하는 검사는 그 파일을 읽는 태스크의 실행에서 한다(예: `AdditionalSourceRoots`). 2026-11-13에 API surface의 추가 source root 검사를 설정 단계에 두었다가 nightly compose smoke의 18개 lane이 모두 이미지 빌드에서 멈췄다(2026-11-18 확인). 같은 Dockerfile을 쓰는 release 이미지 빌드와 로컬 `scripts/bootstrap-local.sh`도 같은 단계를 지난다.
- 파일이 있어야 하는 검사는 그 파일을 읽는 태스크의 실행에서 한다(예: API surface의 source root가 있고 `.java` 파일을 가졌는지는 surface 태스크가 부르는 `JavaPublicTypes.render`가 본다). 2026-11-13에 API surface의 추가 source root 검사를 설정 단계에 두었다가 nightly compose smoke의 18개 lane이 모두 이미지 빌드에서 멈췄다(2026-11-18 확인). 같은 Dockerfile을 쓰는 release 이미지 빌드와 로컬 `scripts/bootstrap-local.sh`도 같은 단계를 지난다.
- 설정 단계 동작을 바꿨으면 desktop에서 이미지 빌드를 한 번 본다: `bash scripts/run-compose-runtime-smoke.sh --lane off-local`.
## 단계 job의 모양
@@ -34,7 +34,8 @@ public final class ApiSurfacePolicy {
owningProjectPath
+ ": found no public types under "
+ String.join(", ", roots.stream().map(File::toString).toList())
+ ". The source roots moved; fix the paths rather than accepting an empty surface.");
+ ". Point the source roots at the leaf's public types rather than accepting an empty"
+ " surface.");
}
StringBuilder header = new StringBuilder();
header.append("# ").append(description).append('\n');
@@ -28,23 +28,44 @@ import javax.tools.ToolProvider;
public final class JavaPublicTypes {
private JavaPublicTypes() {}
/**
* The public top-level types under {@code sourceRoots}, each root a folder that holds at least
* one {@code .java} file. A root that moved away or was emptied used to be skipped, and while
* another root still had types the surface came out smaller instead of failing, so an approved
* update recorded a whole root's types as removed.
*
* @throws IllegalStateException naming every root that does not exist or holds no Java source
*/
public static List<String> render(Collection<File> sourceRoots) {
List<File> sources = new ArrayList<>();
List<File> missing = new ArrayList<>();
List<File> empty = new ArrayList<>();
if (sourceRoots != null) {
for (File root : sourceRoots) {
if (root == null || !root.isDirectory()) {
if (!root.isDirectory()) {
missing.add(root);
continue;
}
try (var paths = Files.walk(root.toPath())) {
paths.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".java"))
.map(java.nio.file.Path::toFile)
.forEach(sources::add);
} catch (IOException exception) {
throw new IllegalStateException("Could not walk Java source root " + root, exception);
List<File> found = javaSources(root);
if (found.isEmpty()) {
empty.add(root);
}
sources.addAll(found);
}
}
if (!missing.isEmpty() || !empty.isEmpty()) {
List<String> problems = new ArrayList<>();
if (!missing.isEmpty()) {
problems.add("source roots that do not exist: " + missing);
}
if (!empty.isEmpty()) {
problems.add("source roots with no .java file: " + empty);
}
throw new IllegalStateException(
String.join("; ", problems)
+ ". Fix apiSurface.sourceRoot or apiSurface.additionalSourceRoots rather than"
+ " approving a smaller surface.");
}
Set<String> types = new TreeSet<>();
for (CompilationUnitTree unit : parse(sources, "The public API surface")) {
if (unit.getPackageName() == null) {
@@ -84,6 +105,18 @@ public final class JavaPublicTypes {
return List.copyOf(imports);
}
private static List<File> javaSources(File root) {
try (var paths = Files.walk(root.toPath())) {
return paths
.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".java"))
.map(java.nio.file.Path::toFile)
.toList();
} catch (IOException exception) {
throw new IllegalStateException("Could not walk Java source root " + root, exception);
}
}
private static List<CompilationUnitTree> parse(Collection<File> files, String subject) {
List<File> sources = new ArrayList<>(files);
if (sources.isEmpty()) {
@@ -1,32 +0,0 @@
package dev.caskeleton.buildlogic.apisurface;
import java.io.File;
import java.util.Collection;
import java.util.List;
import org.gradle.api.GradleException;
/**
* The extra source roots an API surface reads, which must exist when the surface is computed.
*
* <p>A missing root used to be skipped without a word, so an approved update recorded a surface
* with a whole module's types gone (2026-11-12 review). The check runs when a surface task runs,
* not while Gradle configures the project: a build that configures every project without its
* sources — the image build's dependency-resolution stage copies only the build scripts — then
* failed on a folder no task of that build was going to read (nightly compose smoke,
* 2026-11-13..17).
*/
final class AdditionalSourceRoots {
private AdditionalSourceRoots() {}
static void requireExisting(String projectPath, Collection<File> roots) {
List<File> missing =
roots.stream().filter(root -> !root.isDirectory()).sorted().toList();
if (!missing.isEmpty()) {
throw new GradleException(
projectPath
+ " apiSurface.additionalSourceRoots names a folder that does not exist: "
+ missing);
}
}
}
@@ -39,8 +39,9 @@ public final class ApiSurfacePlugin implements Plugin<Project> {
.filter(path -> path != null && !path.isBlank())
.map(project::file)
.toList();
// Each additional root must exist, which the surface tasks check when they run
// (AdditionalSourceRoots says why not here).
// Every root must exist and hold a .java file. JavaPublicTypes checks that when a surface
// task runs, not here: the image build's dependency stage configures every project
// without its sources (build-logic/AGENTS.md).
List<File> roots = new ArrayList<>(sourcePaths.stream().map(project::file).toList());
roots.addAll(additional);
String verifyTaskName = "verify" + label + "ApiSurface";
@@ -63,7 +64,6 @@ public final class ApiSurfacePlugin implements Plugin<Project> {
+ label
+ " public API surface drifts.");
task.getSourceRoots().from(roots);
task.getAdditionalSourceRoots().from(additional);
task.getBaseline().fileValue(baseline);
task.getLabel().set(label);
task.getSurfaceDescription()
@@ -93,7 +93,6 @@ public final class ApiSurfacePlugin implements Plugin<Project> {
+ label
+ " public API surface baseline after review.");
task.getSourceRoots().from(roots);
task.getAdditionalSourceRoots().from(additional);
task.getBaseline().fileValue(baseline);
task.getLabel().set(label);
task.getSurfaceDescription()
@@ -15,7 +15,6 @@ import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
@@ -25,10 +24,6 @@ public abstract class UpdateApiSurfaceTask extends DefaultTask {
@InputFiles
public abstract ConfigurableFileCollection getSourceRoots();
/** The extension's additional roots, also in {@link #getSourceRoots()}; each must exist. */
@Internal
public abstract ConfigurableFileCollection getAdditionalSourceRoots();
@OutputFile
public abstract RegularFileProperty getBaseline();
@@ -43,8 +38,6 @@ public abstract class UpdateApiSurfaceTask extends DefaultTask {
@TaskAction
public void updateSurface() {
AdditionalSourceRoots.requireExisting(
getOwningProjectPath().get(), getAdditionalSourceRoots().getFiles());
if (!getApproved().get()) {
throw new GradleException(
getName()
@@ -25,10 +25,6 @@ public abstract class VerifyApiSurfaceTask extends DefaultTask {
@InputFiles
public abstract ConfigurableFileCollection getSourceRoots();
/** The extension's additional roots, also in {@link #getSourceRoots()}; each must exist. */
@Internal
public abstract ConfigurableFileCollection getAdditionalSourceRoots();
@Internal
public abstract RegularFileProperty getBaseline();
@@ -56,8 +52,6 @@ public abstract class VerifyApiSurfaceTask extends DefaultTask {
@TaskAction
public void verifySurface() {
AdditionalSourceRoots.requireExisting(
getOwningProjectPath().get(), getAdditionalSourceRoots().getFiles());
if (getUpdateApproved().get()) {
throw new GradleException(
getName()
@@ -75,17 +75,32 @@ class ApiSurfaceConventionTest {
}
@Test
void emptyOrUnparseableSurfaceFailsClosed() throws Exception {
writeConfiguredBuild("src/main/moved-away");
BuildResult empty = runner("verifyFixtureApiSurface").buildAndFail();
assertTrue(empty.getOutput().contains("found no public types"), empty.getOutput());
void aRootWithNoPublicTypeFailsClosed() throws Exception {
// given
Path hidden = projectDir.resolve("src/hidden/java/app");
Files.createDirectories(hidden);
Files.writeString(hidden.resolve("Hidden.java"), "package app;\nfinal class Hidden {}\n");
writeConfiguredBuild("src/hidden/java");
writeConfiguredBuild("src/main/java");
// when
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
// then
assertTrue(result.getOutput().contains("found no public types"), result.getOutput());
}
@Test
void anUnparseableSourceFailsClosed() throws Exception {
// given
Files.writeString(
projectDir.resolve("src/main/java/app/Broken.java"),
"package app;\npublic class Broken {\n");
BuildResult broken = runner("verifyFixtureApiSurface").buildAndFail();
assertTrue(broken.getOutput().contains("could not be parsed"), broken.getOutput());
// when
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
// then
assertTrue(result.getOutput().contains("could not be parsed"), result.getOutput());
}
@Test
@@ -194,7 +209,81 @@ class ApiSurfaceConventionTest {
// then
assertTrue(
result.getOutput().contains("additionalSourceRoots names a folder that does not exist"),
result
.getOutput()
.contains("source roots that do not exist: " + rootList("../moved/src/main/java")),
result.getOutput());
}
@ParameterizedTest
@ValueSource(
strings = {
"verifyFixtureApiSurface",
"updateFixtureApiSurface -PapproveFixtureApiSurfaceChange"
})
@org.junit.jupiter.api.DisplayName(
"주 source root가 옮겨 가면 추가 root의 type만으로 surface를 만들지 않고 그 경로를 짚어 실패한다")
void aMovedMainSourceRootFailsInsteadOfShrinkingTheSurface(String arguments) throws Exception {
// given
recordASurfaceWithAnAdditionalSourceRoot();
Files.move(projectDir.resolve("src/main/java"), projectDir.resolve("src/main/moved"));
// when
BuildResult result = runner(arguments.split(" ")).buildAndFail();
// then
assertTrue(
result
.getOutput()
.contains("source roots that do not exist: " + rootList("src/main/java")),
result.getOutput());
}
@ParameterizedTest
@ValueSource(
strings = {
"verifyFixtureApiSurface",
"updateFixtureApiSurface -PapproveFixtureApiSurfaceChange"
})
@org.junit.jupiter.api.DisplayName(
"Java 파일이 없는 추가 source root는 폴더가 있어도 건너뛰지 않고 그 경로를 짚어 실패한다")
void anEmptyAdditionalSourceRootFailsInsteadOfShrinkingTheSurface(String arguments)
throws Exception {
// given
recordASurfaceWithAnAdditionalSourceRoot();
Files.delete(projectDir.resolve("extra/src/main/java/extra/Other.java"));
// when
BuildResult result = runner(arguments.split(" ")).buildAndFail();
// then
assertTrue(
result
.getOutput()
.contains("source roots with no .java file: " + rootList("extra/src/main/java")),
result.getOutput());
}
@Test
@org.junit.jupiter.api.DisplayName("없는 root와 빈 root가 함께 있으면 두 목록을 모두 짚어 실패한다")
void aMissingAndAnEmptyRootAreBothNamed() throws Exception {
// given
recordASurfaceWithAnAdditionalSourceRoot();
Files.move(projectDir.resolve("src/main/java"), projectDir.resolve("src/main/moved"));
Files.delete(projectDir.resolve("extra/src/main/java/extra/Other.java"));
// when
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
// then
assertTrue(
result
.getOutput()
.contains(
"source roots that do not exist: "
+ rootList("src/main/java")
+ "; source roots with no .java file: "
+ rootList("extra/src/main/java")),
result.getOutput());
}
@@ -213,12 +302,30 @@ class ApiSurfaceConventionTest {
}
private void declareAMissingAdditionalSourceRoot() throws Exception {
declareAdditionalSourceRoot("../moved/src/main/java");
}
/** A surface recorded from both roots: {@code app.Visible} and {@code extra.Other}. */
private void recordASurfaceWithAnAdditionalSourceRoot() throws Exception {
Path extra = projectDir.resolve("extra/src/main/java/extra");
Files.createDirectories(extra);
Files.writeString(extra.resolve("Other.java"), "package extra;\npublic final class Other {}\n");
declareAdditionalSourceRoot("extra/src/main/java");
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
}
/** How the surface tasks print a one-root list: the absolute, normalized project path. */
private String rootList(String relative) throws Exception {
return "[" + projectDir.toRealPath().resolve(relative).normalize() + "]";
}
private void declareAdditionalSourceRoot(String root) throws Exception {
Files.writeString(
projectDir.resolve("build.gradle"),
Files.readString(projectDir.resolve("build.gradle"))
.replace(
"baseline = file('surface.txt')",
"baseline = file('surface.txt')\n additionalSourceRoots = ['../moved/src/main/java']"));
"baseline = file('surface.txt')\n additionalSourceRoots = ['" + root + "']"));
}
private void writeConfiguredBuild(String sourceRoot) throws Exception {
+1
View File
@@ -18,6 +18,7 @@
| 4 | version catalog에서 지운 칸을 쓰던 빌드 스크립트는 자기 칸을 둔다. 지운 라이브러리 칸: `errorprone-core`, `findsecbugs-plugin`, `jackson3-core`, `jmh-core`, `jmh-generator-annprocess`, `junit-platform-launcher`, `protobuf-java-legacy`, `spock-core-groovy4`, `spock-core-groovy5`. 지운 플러그인 칸: `spring-dependency-management`, `spotless`, `spotbugs`, `errorprone`(규약 플러그인이 쓰는 버전은 그대로다) | 빌드 스크립트 컴파일이 실패한다 | 그 alias를 쓰던 서비스 |
| 5 | `apiSurface`의 추가 source root가 실제로 있는 폴더를 가리키는지 본다. 상대 경로 대신 `project(':x').file('src/main/java').path`를 쓴다 | 설정 단계에서 실패한다. 전에는 말없이 건너뛰어 줄어든 표면을 승인할 수 있었다 | API surface에 추가 root를 둔 leaf |
| 6 | graphql의 `GraphQlDeploymentModeRegistryParityTest`는 `test`가 아니라 main 단계 lane `:adapter:inbound:graphql:graphqlDocumentContractTest`에서 돈다. 손으로 돌릴 때 그 lane을 부른다 | `test`만 돌리면 registry 대조를 보지 않는다 | graphql을 실은 서비스 |
| 7 | `apiSurface`의 주 source root(`sourceRoot`, 기본 `src/main/java`)와 추가 root가 모두 `.java` 파일을 가진 폴더인지 본다. 자기 Java 소스 없이 추가 root만 읽는 leaf는 `sourceRoot = ''`로 주 root를 뺀다. 5번의 실패도 설정 단계가 아니라 surface 태스크를 돌 때 난다 | surface 태스크(`verify<이름>ApiSurface`·`update<이름>ApiSurface`)가 경로를 짚어 실패한다(`source roots that do not exist`, `source roots with no .java file`). 전에는 없는 주 root와 빈 root를 말없이 건너뛰어, 다른 root가 남으면 줄어든 표면을 승인할 수 있었다 | API surface를 선언한 leaf |
## 3. 확인