build: 템플릿 밖에서 혼자 빌드·배포되는 Gradle 루트를 만든다

옮겨 온 메시징 19개 모듈은 템플릿의 src/settings.gradle·build-logic·
카탈로그·registry에 기대고 있어 이 repo만으로는 빌드되지 않는다.
repo 루트를 Gradle 루트로 하는 단독 빌드를 만든다.

- build-logic/: grpc-library main 2e880c7의 줄인 사본(템플릿
  22df3525에서 복사, 템플릿 2959eff0까지의 변경도 같은 내용)에서
  gRPC BOM 규칙(ca.grpc-platform-module)만 뺐다. 배포 플러그인
  ca.library-publishing과 서명 키 해석(SigningKeys)은 그대로다.
  출처·뺀 것·고친 것은 build-logic/UPSTREAM.md.
- settings.gradle·build.gradle·gradle.properties: group
  dev.cakit.messaging, 단계 태스크 ci·mainCheck·releaseCheck와
  배포(release·releaseRehearsal·verifySigningKey)는 grpc-library와
  같은 모양이다. 메시징만 다른 점: Buf가 없고, 성능 lane이 없고,
  mainCheck와 releaseCheck가 브로커 인증 증거 게이트
  (verifyMessagingCertificationEvidence)를 부른다. 템플릿은 이 게이트를
  따로 messaging-certification.yml로 돌렸다. 그 workflow는 지운다.
- config/: registry 19행(source_path만 messaging/<leaf>로), 메시징
  클래스만 남긴 SpotBugs 제외 목록, 이미지 셋(postgres-16, kafka,
  toxiproxy, 모두 digest 고정), checkstyle 사본.
- gradle/libs.versions.toml: 메시징이 쓰는 항목만(avro, cloudevents,
  protobuf 4.33.2, toxiproxy, jmh)과 kafka-clients가 끌고 오는 취약
  버전을 덮는 pinned-lz4-java·pinned-snappy-java.
- 저장소 계약 테스트: MessagingPublicSurfaceContractTest(템플릿
  app-bootstrap에서 이력째 옮김)와 새 MessagingSettingsOwnerContractTest
  (app.messaging 주인은 starter 하나)를 messaging-testkit의
  repositoryContractTest lane에 둔다. check에 들어가 PR 단계에서 돈다.
- messaging-kafka: 인증 manifest 경로를 새 배치로 고친다.

버린 대안: 계약 테스트를 build-logic 테스트로 두는 안. 빌드 플러그인
시험과 모듈 계약이 섞이고, 소스·build.gradle을 입력으로 선언하는
기존 lane 장치를 쓸 수 없다.

위험: 이 커밋 단독으로는 lockfile을 다시 쓰지 않았다(뒤 커밋에서
desktop에서 쓴다). 패키지는 아직 dev.caskeleton.messaging이다.

검증: desktop ./gradlew projects rc=0(19개 모듈 포함).

Refs: design-docs repo-structure/05-library-repos.md 4·10.3·13.1절
This commit is contained in:
DongHyeonka
2026-11-08 16:11:52 +09:00
parent f593229fda
commit 2e9298ec33
87 changed files with 13862 additions and 78 deletions
+23
View File
@@ -0,0 +1,23 @@
## 무엇을, 왜
<!-- 지금 무엇이 문제인가. 이 PR이 무엇을 바꾸는가. -->
## 고른 방법과 버린 대안
<!-- 왜 이 방법인가. 검토하고 버린 방법과 그 이유. -->
## 위험과 영향
<!-- 호환성(공개 타입·proto·설정 키면 MAJOR인지), 운영, 보안. 검증하지 못한 것과 일부러 미룬 것. 없으면 "없음"이라고 쓰지 말고 왜 없는지 한 줄. -->
## 검증
<!-- 실행한 명령과 결과(scripts/verify.sh pr 등). 실행하지 않은 검증은 안 했다고 쓴다. 공개 API를 바꿨으면 템플릿 쪽 영향(docs/work/README.md 3절). -->
## 리뷰어가 볼 곳
<!-- 특히 봐야 할 파일. 기계적으로 만든 부분은 만든 방법(명령, 기준 커밋). -->
## 관련
<!-- 이슈, 설계 문서, 결정 기록. -->
@@ -1,51 +0,0 @@
# The messaging platform's broker certification lane.
#
# Separate from ci-quality-gates.yml because it needs a container runtime and several minutes of it.
# The lane deliberately carries no Docker guard: every other container suite in the messaging tree
# skips with a stated reason when Docker is absent, and a certification lane that skipped would
# report success for a broker nobody started — which is the exact claim the evidence exists to rule
# out.
#
# The job runs the evidence gate rather than the lane, and the gate depends on the lane. What it
# proves is not only that the scenarios pass but that the committed manifest
# (messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl) is what this
# run produced, so "certified against a live broker" cannot be restored by editing a file.
name: messaging-certification
on:
pull_request:
paths:
- "src/platforms/messaging/**"
- ".github/workflows/messaging-certification.yml"
# Every Gradle job here installs its toolchain through this composite action, so a change to
# it changes what this gate runs.
- ".github/actions/setup-gradle-java/action.yml"
schedule:
- cron: "41 4 * * 3"
workflow_dispatch:
permissions:
contents: read
env:
# Reuse would hand one scenario the broker another scenario had already faulted.
TESTCONTAINERS_REUSE_ENABLE: "false"
jobs:
broker-certification:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
- uses: ./.github/actions/setup-gradle-java
- name: Certify the Kafka adapter against a real broker
working-directory: src
# GITHUB_SHA is read by the lane and written into every evidence line, because "certified"
# is a claim about one source tree.
run: ./gradlew :messaging:messaging-kafka:verifyMessagingCertificationEvidence --stacktrace
- name: Publish the certification evidence
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2
with:
name: messaging-broker-certification-evidence
path: src/platforms/messaging/messaging-kafka/build/messaging-certification/
if-no-files-found: warn
+8
View File
@@ -6,3 +6,11 @@
.env.production
__pycache__/
# Gradle and IDE output
.gradle/
build/
**/bin/
.idea/
*.iml
.vscode/
+15
View File
@@ -0,0 +1,15 @@
# Structured Trivy suppression baseline.
#
# This repository-root file is the only CI suppression source. Every Trivy invocation must name it
# with `--ignorefile .trivyignore.yaml`; ad-hoc ignore files and inline bypasses are not allowed.
#
# Every entry must carry:
# id: advisory, license, misconfiguration, or secret identifier
# statement: non-empty accepted-risk or false-positive rationale
# expired_at: future YYYY-MM-DD, no more than 90 days from review
#
vulnerabilities: []
licenses: []
misconfigurations: []
secrets: []
+8
View File
@@ -0,0 +1,8 @@
# build-logic — 이 repo의 Gradle convention 플러그인
백엔드 템플릿 `src/build-logic/`의 사본이다. 출처와 뺀 것·고친 것은 `UPSTREAM.md`가 정본이다. 루트 `AGENTS.md`가 먼저다.
- 모듈은 `ca.platform-module`(Java 라이브러리 + 배포)을 쓴다. Spring 설정 메타데이터가 있는 모듈은 `ca.spring-config`를 더한다.
- `ca.architecture`는 registry(`config/architecture/modules.json`)의 허용 의존과 실제 project edge를 대조한다. registry에 없는 `build.gradle`이 있으면 실패한다.
- `ca.strict-test-lane`의 lane은 아무것도 실행하지 않거나 skip이 있으면 실패한다. lane마다 단계(`ci`·`mainCheck`·`releaseCheck`) 하나에 들어 있어야 한다(`verifyStrictLaneStages --dry-run`, `.gitea/workflows`를 읽는다).
- 이 폴더를 고치면 `./gradlew buildLogicTest`(루트 `ci`에 들어 있다). 템플릿 쪽 수정을 옮길 때는 `UPSTREAM.md` 「템플릿 수정을 옮기는 법」을 따른다.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+39
View File
@@ -0,0 +1,39 @@
# build-logic의 출처 — 백엔드 템플릿에서 복사해 줄였다
- 복사한 곳: `grpc-library` main `2e880c7`의 `build-logic/`(2026-11-08). 그 사본은 `clean-architecture-backend-template` main `22df3525`의 `src/build-logic/`을 줄인 것이다. 템플릿 main `2959eff0`까지의 `src/build-logic` 변경(`57988c2e` registry `build` 칸 거절, `5e204e6a` optional build 지원 삭제)은 그 사본에 이미 같은 내용으로 들어 있다(주석 문장만 다르다).
- 함께 복사: 템플릿 `src/gradle/libs.versions.toml`(이 repo가 쓰는 항목만), `src/gradle/wrapper/`, `src/gradlew*`, `src/config/checkstyle/`, `src/config/spotbugs/`(메시징 클래스와 일반 규칙만), `src/config/testing/container-images.properties`(`postgres-16`·`kafka`·`toxiproxy`만)
- 근거: design-docs `repo-structure/05-library-repos.md` 10.3절 L1(복사 후 줄이기). 다시 열 조건: 라이브러리 repo가 셋 이상이 되거나, 6개월 안에 템플릿에서 이 사본으로 옮긴 수정이 3번을 넘으면 공통 빌드 규칙 repo(L3)를 본다. 사본은 이제 셋이다(템플릿, grpc-library, 이 repo). 앞의 조건 「라이브러리 repo가 셋 이상」은 아직 아니다.
## 뺀 것
| 무엇 | 이유 |
| --- | --- |
| `ca.bootrun-dotenv`, `ca.redis-topology-lane`, `ca.config-contract`, `ca.spring-library` | 이 repo 모듈이 쓰지 않는다(grpc-library 사본에서 이미 뺐다) |
| `ca.optional-architecture-registry`, `MainBuild` | 템플릿 안 두 번째 빌드(optional build)를 위한 것. 여기서는 repo 루트가 곧 Gradle 루트다 |
| `VerifyApplicationCoreDependencyPurityTask`(`ca.architecture` 안) | 템플릿 계층 이름(`domain-core`·`application-*`·`shared-contract`)에만 걸린다 |
| `ca.grpc-platform-module`과 그 테스트 | grpc-library 사본에만 있던 gRPC BOM 규칙. 이 repo에는 gRPC 모듈이 없다 |
| `README.md`, 템플릿 `AGENTS.md` | 템플릿 빌드 설명이다. 이 폴더 `AGENTS.md`로 바꿨다 |
`ca.api-surface`는 남겼다. 설계 10.1절은 라이브러리 모듈에 켜기를 권하지만, 공개 타입 기준선 파일과 정책은 새 결정이라 아직 어느 모듈에도 켜지 않았다(grpc-library와 같다).
## 고친 것(템플릿과 다른 점)
| 파일 | 바뀐 점 |
| --- | --- |
| `settings/ArchitectureRegistrySettingsPlugin` | repo 루트 = Gradle 루트. registry의 `source_path`는 Gradle 루트 기준이다(템플릿은 `src/`의 부모 기준) |
| `architecture/ArchitecturePlugin` | 위와 같은 기준, optional build 분기와 purity 태스크를 뺐다 |
| `java/JavaConventionsPlugin` | `group`을 `gradle.properties`의 `libraryGroup`에서 읽는다(템플릿은 `dev.caskeleton` 고정). 버전은 `RELEASE_TAG`/`-PreleaseTag`(`vX.Y.Z`)에서도 읽는다. 이미지 목록·도구 설정은 루트의 `config/`만 본다 |
| `quality/QualityConventionsPlugin` | 도구 설정은 루트의 `config/`만 본다 |
| `convention/PlatformModuleConventionPlugin` | `ca.library-publishing`을 함께 켠다 |
| `strictlane/StrictLaneStagesPlugin` | 단계의 계획을 따라갈 때 included build 태스크(`ci`가 부르는 build-logic `test`)는 묻지 않는다 |
| 새 `publishing/LibraryPublishingPlugin`(`ca.library-publishing`) | 모듈마다 Maven publication(sources·javadoc jar, 해석된 버전), 저장소 `gitea`·`staging`, `SIGNING_KEY`가 있으면 PGP 서명. test fixtures는 배포하지 않는다 |
| 새 `publishing/SigningKeys` | base64로 감싼 armored 키를 푼다(grpc-library v1.0.0 서명 실패에서 나온 수정) |
| 테스트 fixture | `source_path`를 Gradle 루트 기준으로, `PlatformModuleConventionTest`에 `libraryGroup` |
Java 패키지 `dev.caskeleton.buildlogic`은 그대로 두었다. 배포하지 않는 빌드 도구이고, 템플릿 파일과 나란히 비교하기 쉽게 하려는 것이다.
## 템플릿 수정을 옮기는 법
1. 템플릿에서 `git log --oneline 2959eff0..main -- src/build-logic`으로 이후 변경을 본다. grpc-library의 `build-logic/`에 먼저 옮겨졌으면 그 커밋을 따라 해도 된다.
2. 위 「뺀 것」에 해당하지 않는 변경만 같은 파일에 옮긴다. 옮긴 커밋은 본문에 템플릿 커밋 SHA를 적는다.
3. 옮긴 뒤 이 파일의 「복사한 곳」 커밋을 그 템플릿 커밋으로 바꾸고, 옮긴 횟수를 세어 다시 열 조건과 비교한다.
+91
View File
@@ -0,0 +1,91 @@
plugins {
id 'java-gradle-plugin'
}
// The plugins below come from the Gradle Plugin Portal, so their resolved graph is locked like every
// leaf's (gradle.lockfile beside this file). STRICT: a configuration with no lock state fails rather
// than resolving whatever the portal serves. Regenerate with
// `./gradlew -p build-logic dependencies --write-locks` after a catalog version change.
dependencyLocking {
lockAllConfigurations()
lockMode = LockMode.STRICT
}
dependencies {
implementation libs.jackson3.databind
// The third-party Gradle plugins the convention plugins apply.
//
// The root build used to apply these to every leaf from `configure(subprojects)`, and the
// recorded reason for keeping them there (D8) was that build-logic would have to re-declare
// their versions, giving each one a second home that could drift. That objection no longer
// holds: build-logic/settings.gradle reads the main build's `gradle/libs.versions.toml`, so the
// versions below and the ones the root `plugins {}` block declares are the same table entries.
implementation "com.diffplug.spotless:spotless-plugin-gradle:${libs.versions.spotless.get()}"
implementation "com.github.spotbugs.snom:spotbugs-gradle-plugin:${libs.versions.spotbugsPlugin.get()}"
implementation "net.ltgt.gradle:gradle-errorprone-plugin:${libs.versions.errorpronePlugin.get()}"
implementation "io.spring.gradle:dependency-management-plugin:${libs.versions.springDependencyManagement.get()}"
// TestKit verifies the binary plugins against the running Gradle distribution.
testImplementation gradleTestKit()
testImplementation libs.junit.jupiter
testImplementation libs.assertj.core
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
gradlePlugin {
plugins {
apiSurface {
id = 'ca.api-surface'
implementationClass = 'dev.caskeleton.buildlogic.apisurface.ApiSurfacePlugin'
}
architecture {
id = 'ca.architecture'
implementationClass = 'dev.caskeleton.buildlogic.architecture.ArchitecturePlugin'
}
javaConventions {
id = 'ca.java-conventions'
implementationClass = 'dev.caskeleton.buildlogic.java.JavaConventionsPlugin'
}
qualityConventions {
id = 'ca.quality-conventions'
implementationClass = 'dev.caskeleton.buildlogic.quality.QualityConventionsPlugin'
}
strictTestLane {
id = 'ca.strict-test-lane'
implementationClass = 'dev.caskeleton.buildlogic.strictlane.StrictTestLanePlugin'
}
strictLaneStages {
id = 'ca.strict-lane-stages'
implementationClass = 'dev.caskeleton.buildlogic.strictlane.StrictLaneStagesPlugin'
}
architectureRegistrySettings {
id = 'ca.architecture-registry'
implementationClass = 'dev.caskeleton.buildlogic.settings.ArchitectureRegistrySettingsPlugin'
}
javaLibraryConvention {
id = 'ca.java-library'
implementationClass = 'dev.caskeleton.buildlogic.convention.JavaLibraryConventionPlugin'
}
springConfigConvention {
id = 'ca.spring-config'
implementationClass = 'dev.caskeleton.buildlogic.convention.SpringConfigConventionPlugin'
}
platformModuleConvention {
id = 'ca.platform-module'
implementationClass = 'dev.caskeleton.buildlogic.convention.PlatformModuleConventionPlugin'
}
libraryPublishing {
id = 'ca.library-publishing'
implementationClass = 'dev.caskeleton.buildlogic.publishing.LibraryPublishingPlugin'
}
}
}
tasks.named('test') {
useJUnitPlatform()
// GradleCommandLineTest runs the launcher of the Gradle that runs this build — the distribution
// the workflows' ./gradlew starts — and holds the workflow reader's copy of its command-line
// options to it (review 2026-11-05 RR6-04-02).
systemProperty 'ca.gradle.home', gradle.gradleHomeDir.absolutePath
}
+46
View File
@@ -0,0 +1,46 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
com.diffplug.durian:durian-collect:1.2.0=runtimeClasspath,testRuntimeClasspath
com.diffplug.durian:durian-core:1.2.0=runtimeClasspath,testRuntimeClasspath
com.diffplug.durian:durian-io:1.2.0=runtimeClasspath,testRuntimeClasspath
com.diffplug.durian:durian-swt.os:4.3.0=runtimeClasspath,testRuntimeClasspath
com.diffplug.spotless:spotless-lib-extra:4.6.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.diffplug.spotless:spotless-lib:4.6.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.diffplug.spotless:spotless-plugin-gradle:8.6.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.spotbugs.snom:spotbugs-gradle-plugin:6.5.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.googlecode.concurrent-trees:concurrent-trees:2.6.1=runtimeClasspath,testRuntimeClasspath
com.googlecode.javaewah:JavaEWAH:1.2.3=runtimeClasspath,testRuntimeClasspath
com.squareup.okhttp3:okhttp:4.12.0=runtimeClasspath,testRuntimeClasspath
com.squareup.okio:okio-jvm:3.6.0=runtimeClasspath,testRuntimeClasspath
com.squareup.okio:okio:3.6.0=runtimeClasspath,testRuntimeClasspath
commons-codec:commons-codec:1.21.0=runtimeClasspath,testRuntimeClasspath
dev.equo.ide:solstice:1.8.1=runtimeClasspath,testRuntimeClasspath
io.spring.gradle:dependency-management-plugin:1.1.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.18.3=testCompileClasspath,testRuntimeClasspath
net.ltgt.gradle:gradle-errorprone-plugin:5.1.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.eclipse.jgit:org.eclipse.jgit:7.6.0.202603022253-r=runtimeClasspath,testRuntimeClasspath
org.eclipse.platform:org.eclipse.osgi:3.24.100=runtimeClasspath,testRuntimeClasspath
org.jetbrains.kotlin:kotlin-stdlib-common:2.0.21=runtimeClasspath,testRuntimeClasspath
org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.10=runtimeClasspath,testRuntimeClasspath
org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.10=runtimeClasspath,testRuntimeClasspath
org.jetbrains.kotlin:kotlin-stdlib:2.0.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.jetbrains:annotations:13.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:5.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:5.11.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:5.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:5.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:1.11.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:1.11.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:1.11.3=testRuntimeClasspath
org.junit:junit-bom:5.11.3=testCompileClasspath,testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.17=runtimeClasspath,testRuntimeClasspath
org.tukaani:xz:1.9=runtimeClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.1.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.1.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
empty=annotationProcessor,testAnnotationProcessor
+4
View File
@@ -0,0 +1,4 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
empty=incomingCatalogForLibs0
+26
View File
@@ -0,0 +1,26 @@
// The included build that holds this repository's convention plugins.
//
// Its own settings are deliberately tiny: an included build for build logic should not need the
// registry validation, toolchain resolution or plugin management the main build does, and giving it
// any of those would make the thing that validates the build depend on the build it validates.
dependencyResolutionManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
// The main build's version catalog, read as a file rather than inherited — an included build
// does not see its parent's catalog.
//
// This is not the dependency the note above warns against. It reads a table of versions, not the
// build those versions configure: nothing here is evaluated and no project is resolved.
// Keeping Java/JUnit/plugin coordinates in the shared catalog prevents included-build versions
// from drifting away from the leaf modules they configure.
versionCatalogs {
libs {
from(files('../gradle/libs.versions.toml'))
}
}
}
rootProject.name = 'build-logic'
@@ -0,0 +1,45 @@
package dev.caskeleton.buildlogic;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/** Declarative configuration for one committed public API surface. */
public class ApiSurfaceExtension {
private String label;
private File baseline;
private String description;
private List<String> rationale = new ArrayList<>();
private String sourceRoot = "src/main/java";
private List<String> additionalSourceRoots = new ArrayList<>();
private File adopterBaseline;
private Object adopterSources;
public String getLabel() { return label; }
public void setLabel(String label) { this.label = label; }
public File getBaseline() { return baseline; }
public void setBaseline(File baseline) { this.baseline = baseline; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public List<String> getRationale() { return rationale; }
public void setRationale(List<String> rationale) {
this.rationale = rationale == null ? new ArrayList<>() : new ArrayList<>(rationale);
}
public String getSourceRoot() { return sourceRoot; }
public void setSourceRoot(String sourceRoot) { this.sourceRoot = sourceRoot; }
public List<String> getAdditionalSourceRoots() { return additionalSourceRoots; }
public void setAdditionalSourceRoots(List<String> additionalSourceRoots) {
this.additionalSourceRoots =
additionalSourceRoots == null ? new ArrayList<>() : new ArrayList<>(additionalSourceRoots);
}
/**
* The reviewed subset of the surface other leaves' production code may import. Optional: without
* it, every public type is fair game to an adopter, which is what the surface alone says.
*/
public File getAdopterBaseline() { return adopterBaseline; }
public void setAdopterBaseline(File adopterBaseline) { this.adopterBaseline = adopterBaseline; }
/** The adopter sources whose imports are held to {@link #getAdopterBaseline()}; any {@code files()} notation. */
public Object getAdopterSources() { return adopterSources; }
public void setAdopterSources(Object adopterSources) { this.adopterSources = adopterSources; }
}
@@ -0,0 +1,197 @@
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.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** Policy and rendering semantics for committed public Java API surfaces. */
public final class ApiSurfacePolicy {
private ApiSurfacePolicy() {}
public static String render(
Collection<File> roots,
String label,
String description,
Collection<String> rationale,
String owningProjectPath,
String updateTaskName,
String approvalProperty) {
List<String> types;
try {
types = JavaPublicTypes.render(roots);
} catch (IllegalStateException unparseable) {
throw new IllegalStateException(
owningProjectPath + " " + label + " API surface: " + unparseable.getMessage(),
unparseable);
}
if (types.isEmpty()) {
throw new IllegalStateException(
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.");
}
StringBuilder header = new StringBuilder();
header.append("# ").append(description).append('\n');
if (rationale != null) {
rationale.forEach(line -> header.append("# ").append(line).append('\n'));
}
header.append("# Update only after review with:\n");
header
.append("# ./gradlew ")
.append(owningProjectPath)
.append(':')
.append(updateTaskName)
.append(" -P")
.append(approvalProperty)
.append('\n');
header.append("# types: ").append(types.size()).append('\n');
return header + String.join("\n", types) + "\n";
}
public static void verify(
String verifyTaskName,
String updateTaskName,
String owningProjectPath,
String approvalProperty,
File baseline,
String rendered) {
if (!baseline.isFile()) {
throw new IllegalStateException(
verifyTaskName + ": missing committed baseline " + baseline);
}
String committed = read(baseline);
if (committed.equals(rendered)) {
return;
}
List<String> committedTypes = surfaceLines(committed);
List<String> renderedTypes = surfaceLines(rendered);
List<String> added = difference(renderedTypes, committedTypes);
List<String> removed = difference(committedTypes, renderedTypes);
throw new IllegalStateException(
verifyTaskName
+ ": the public API surface changed.\n"
+ (added.isEmpty() ? "" : " added:\n " + String.join("\n ", added) + "\n")
+ (removed.isEmpty() ? "" : " removed:\n " + String.join("\n ", removed) + "\n")
+ "Review the change, then record it with:\n"
+ " ./gradlew "
+ owningProjectPath
+ ":"
+ updateTaskName
+ " -P"
+ approvalProperty);
}
/**
* Holds other leaves' imports of this surface to the reviewed adopter subset.
*
* <p>The surface says what is public; the adopter baseline says which of those public types other
* leaves' production code may depend on. An import of a surface type the adopter baseline does not
* list fails, and so does an adopter entry the surface no longer has.
*/
public static void verifyAdopters(
String verifyTaskName, String rendered, File adopterBaseline, List<String> adopterImports) {
if (!adopterBaseline.isFile()) {
throw new IllegalStateException(
verifyTaskName + ": missing committed adopter baseline " + adopterBaseline);
}
java.util.Set<String> surface = new java.util.HashSet<>(surfaceLines(rendered));
java.util.Set<String> allowed = new java.util.TreeSet<>();
for (String line : read(adopterBaseline).lines().toList()) {
if (!line.isBlank() && !line.startsWith("#")) {
allowed.add(line.trim());
}
}
List<String> stale = allowed.stream().filter(type -> !surface.contains(type)).toList();
List<String> unreviewed =
adopterImports.stream()
.filter(entry -> {
String type = entry.substring(entry.indexOf(": ") + 2);
return surface.contains(type) && !allowed.contains(type);
})
.toList();
if (stale.isEmpty() && unreviewed.isEmpty()) {
return;
}
throw new IllegalStateException(
verifyTaskName
+ ": the adopter surface ("
+ adopterBaseline.getName()
+ ") does not match what other leaves import.\n"
+ (unreviewed.isEmpty()
? ""
: " imported but not in the adopter baseline:\n "
+ String.join("\n ", unreviewed)
+ "\n")
+ (stale.isEmpty()
? ""
: " in the adopter baseline but not in the public surface:\n "
+ String.join("\n ", stale)
+ "\n")
+ "Add a reviewed type to the adopter baseline, or stop importing it.");
}
public static void requireNoUnapprovedGrowth(
String updateTaskName,
String owningProjectPath,
String approvalProperty,
String ceilingProperty,
int committedCount,
String rendered,
boolean ceilingRaiseApproved) {
if (ceilingRaiseApproved) {
return;
}
int renderedCount = countTypes(rendered);
if (renderedCount > committedCount) {
throw new IllegalStateException(
updateTaskName
+ ": the public surface would grow from "
+ committedCount
+ " to "
+ renderedCount
+ " types.\n"
+ "Approving additions one at a time is how this leaf got too big to split without anybody deciding to make it so.\n"
+ "Either land the addition together with a removal that pays for it, or raise the ceiling deliberately:\n"
+ " ./gradlew "
+ owningProjectPath
+ ":"
+ updateTaskName
+ " -P"
+ approvalProperty
+ " -P"
+ ceilingProperty);
}
}
public static int countTypes(String surface) {
return (int)
surface.lines()
.filter(line -> !line.startsWith("#") && !line.trim().isEmpty())
.count();
}
private static List<String> surfaceLines(String surface) {
return surface.lines().filter(line -> !line.startsWith("#")).toList();
}
private static List<String> difference(List<String> left, List<String> right) {
ArrayList<String> result = new ArrayList<>(left);
result.removeAll(right);
result.sort(String::compareTo);
return List.copyOf(result);
}
private static String read(File file) {
try {
return Files.readString(file.toPath(), StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + file, exception);
}
}
}
@@ -0,0 +1,131 @@
package dev.caskeleton.buildlogic;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.lang.model.element.Modifier;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
/** Public top-level Java types parsed with javac rather than regular expressions. */
public final class JavaPublicTypes {
private JavaPublicTypes() {}
public static List<String> render(Collection<File> sourceRoots) {
List<File> sources = new ArrayList<>();
if (sourceRoots != null) {
for (File root : sourceRoots) {
if (root == null || !root.isDirectory()) {
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);
}
}
}
Set<String> types = new TreeSet<>();
for (CompilationUnitTree unit : parse(sources, "The public API surface")) {
if (unit.getPackageName() == null) {
continue;
}
String packageName = unit.getPackageName().toString();
for (Tree declaration : unit.getTypeDecls()) {
if (declaration instanceof ClassTree type
&& type.getModifiers().getFlags().contains(Modifier.PUBLIC)) {
types.add(packageName + "." + type.getSimpleName());
}
}
}
return List.copyOf(types);
}
/**
* Every single-type, non-static import in {@code sources}, as {@code "<file name>: <import>"}.
* Wildcard and static imports are not listed; a leaf whose adopters need them is declaring a
* surface this check does not model.
*/
public static List<String> imports(Collection<File> sources) {
List<File> files =
sources == null
? List.of()
: sources.stream().filter(file -> file.getName().endsWith(".java")).toList();
Set<String> imports = new TreeSet<>();
for (CompilationUnitTree unit : parse(files, "The adopter sources")) {
String file = new File(unit.getSourceFile().toUri()).getName();
for (ImportTree declaration : unit.getImports()) {
String name = declaration.getQualifiedIdentifier().toString();
if (!declaration.isStatic() && !name.endsWith(".*")) {
imports.add(file + ": " + name);
}
}
}
return List.copyOf(imports);
}
private static List<CompilationUnitTree> parse(Collection<File> files, String subject) {
List<File> sources = new ArrayList<>(files);
if (sources.isEmpty()) {
return List.of();
}
sources.sort(Comparator.comparing(File::getPath));
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new IllegalStateException(
"No Java compiler on this JVM, so the public API surface cannot be parsed. "
+ "Run the build on a JDK rather than a JRE — rendering an empty surface "
+ "instead would report every public type as removed.");
}
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
try (StandardJavaFileManager fileManager =
compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) {
JavacTask task =
(JavacTask)
compiler.getTask(
new StringWriter(),
fileManager,
diagnostics,
List.of("-proc:none"),
null,
fileManager.getJavaFileObjectsFromFiles(sources));
List<CompilationUnitTree> units = new ArrayList<>();
task.parse().forEach(units::add);
List<Diagnostic<? extends JavaFileObject>> errors =
diagnostics.getDiagnostics().stream()
.filter(diagnostic -> diagnostic.getKind() == Diagnostic.Kind.ERROR)
.toList();
if (!errors.isEmpty()) {
String first =
errors.stream().limit(5).map(Object::toString).reduce((a, b) -> a + "\n " + b).orElse("");
String more = errors.size() > 5 ? "\n (" + (errors.size() - 5) + " more)" : "";
throw new IllegalStateException(subject + " could not be parsed:\n " + first + more);
}
return units;
} catch (IOException exception) {
throw new IllegalStateException("Could not parse Java source files", exception);
}
}
}
@@ -0,0 +1,307 @@
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<Module> modules, File source) {
private static final ObjectMapper JSON = JsonMapper.builder().build();
private static final Set<String> REQUIRED_MODULE_FIELDS =
Set.of("id", "gradle_path", "source_path", "allowed_dependencies");
private static final Set<String> 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<String> 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<String> rootKeys = keys(root);
Set<String> 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<String> ids = new LinkedHashSet<>();
Set<String> gradlePaths = new LinkedHashSet<>();
Set<String> sourceDirectories = new LinkedHashSet<>();
List<Module> 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<String> 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<String> 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.
*
* <p>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<String> unregisteredBuildScripts(File gradleRoot) {
Path root = canonical(gradleRoot).toPath();
Set<Path> owned = new HashSet<>();
for (Module module : modules) {
owned.add(canonical(module.sourceDirectory()).toPath());
}
List<String> 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<Module> modulesForBuild(String buildName) {
return modules.stream().filter(module -> module.buildName().equals(buildName)).toList();
}
private static Set<String> keys(JsonNode node) {
Set<String> 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<String> requireStringList(JsonNode raw, String id, String field) {
if (raw == null || !raw.isArray()) {
throw new IllegalStateException(
"Module registry entry '" + id + "' needs a '" + field + "' list.");
}
List<String> 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);
}
}
@@ -0,0 +1,63 @@
package dev.caskeleton.buildlogic;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gradle.api.GradleException;
import org.gradle.api.initialization.Settings;
/** Settings-time adapter mapping one logical build from the shared module registry into Gradle. */
public final class ModuleRegistrySettingsInstaller {
private ModuleRegistrySettingsInstaller() {}
public static ModuleRegistry install(
Settings settings, File registryFile, File repositoryRoot, String buildName) {
ModuleRegistry registry;
try {
registry = ModuleRegistry.read(registryFile, repositoryRoot);
} catch (IllegalStateException invalid) {
throw new GradleException(invalid.getMessage(), invalid);
}
List<ModuleRegistry.Module> selected = registry.modulesForBuild(buildName);
if (selected.isEmpty()) {
throw new GradleException(
"Module registry declares no modules for build '" + buildName + "': " + registryFile);
}
Map<String, File> namespaceDirectories = new HashMap<>();
for (ModuleRegistry.Module module : selected) {
settings.include(module.gradlePath());
settings.project(module.gradlePath()).setProjectDir(module.sourceDirectory());
String[] segments = module.gradlePath().substring(1).split(":");
File directory = module.sourceDirectory();
for (int size = segments.length - 1; size >= 1; size--) {
directory = directory.getParentFile();
String parentPath = ":" + String.join(":", java.util.Arrays.copyOf(segments, size));
File canonical;
try {
canonical = directory.getCanonicalFile();
} catch (IOException exception) {
throw new UncheckedIOException("failed to canonicalize " + directory, exception);
}
File existing = namespaceDirectories.putIfAbsent(parentPath, canonical);
if (existing != null && !existing.equals(canonical)) {
throw new GradleException(
"Module registry maps namespace '"
+ parentPath
+ "' to both "
+ existing
+ " and "
+ canonical
+ ".");
}
settings.project(parentPath).setProjectDir(canonical);
}
}
return registry;
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.buildlogic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** One rule for proving that a named test selector actually executed. */
public final class RequiredTestExecution {
private static final List<String> SUB_IDENTITY_SEPARATORS = List.of("$", "(", "[");
private RequiredTestExecution() {}
public static boolean satisfies(String executed, String required) {
if (executed == null || required == null) {
return false;
}
if (executed.equals(required)) {
return true;
}
return SUB_IDENTITY_SEPARATORS.stream()
.anyMatch(separator -> executed.startsWith(required + separator));
}
public static List<String> absent(
Collection<String> required, Collection<String> executed) {
if (required == null || required.isEmpty()) {
return List.of();
}
Collection<String> observed = executed == null ? List.of() : executed;
List<String> absent = new ArrayList<>();
for (String requiredSelector : required) {
boolean satisfied =
observed.stream().anyMatch(executedSelector -> satisfies(executedSelector, requiredSelector));
if (!satisfied) {
absent.add(requiredSelector);
}
}
return List.copyOf(absent);
}
}
@@ -0,0 +1,47 @@
package dev.caskeleton.buildlogic;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.Set;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.artifacts.result.ResolvedDependencyResult;
/**
* Walks a resolution result from its root component.
*
* <p>The architecture tasks used to hold a {@link org.gradle.api.artifacts.Configuration} and call
* {@code getIncoming().getResolutionResult().getAllComponents()} inside the task action. That is
* live build state: Gradle cannot serialise it, so the configuration cache refused to store the
* task, and it resolves a configuration at execution time from whatever project happens to run the
* action. A {@code Provider<ResolvedComponentResult>} taken from {@code getRootComponent()} is the
* supported carrier — it is resolved while the owning project is still configuring, and what the
* task keeps is a value.
*
* <p>This walk therefore replaces {@code getAllComponents()}, which has no equivalent on the root
* component. The visited set is not an optimisation: a dependency graph is a DAG only in intent,
* and a cycle here would be an infinite loop rather than a diagnosis.
*/
public final class ResolvedComponents {
private ResolvedComponents() {}
/** Every component reachable from {@code root}, including {@code root} itself. */
public static Set<ResolvedComponentResult> reachableFrom(ResolvedComponentResult root) {
Set<ResolvedComponentResult> visited = new LinkedHashSet<>();
Deque<ResolvedComponentResult> pending = new ArrayDeque<>();
pending.add(root);
while (!pending.isEmpty()) {
ResolvedComponentResult component = pending.removeFirst();
if (!visited.add(component)) {
continue;
}
for (var dependency : component.getDependencies()) {
if (dependency instanceof ResolvedDependencyResult resolved) {
pending.add(resolved.getSelected());
}
}
}
return visited;
}
}
@@ -0,0 +1,111 @@
package dev.caskeleton.buildlogic.apisurface;
import dev.caskeleton.buildlogic.ApiSurfaceExtension;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
public final class ApiSurfacePlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
ApiSurfaceExtension extension =
project.getExtensions().create("apiSurface", ApiSurfaceExtension.class);
project.afterEvaluate(
ignored -> {
String label = extension.getLabel();
File baseline = extension.getBaseline();
if ((label == null || label.isBlank()) && baseline == null) {
return;
}
if (label == null || label.isBlank()) {
throw new GradleException(
project.getPath() + " declares an apiSurface baseline without a label");
}
if (baseline == null) {
throw new GradleException(
project.getPath() + " declares an apiSurface label without a baseline");
}
List<String> sourcePaths = new ArrayList<>();
if (extension.getSourceRoot() != null && !extension.getSourceRoot().isBlank()) {
sourcePaths.add(extension.getSourceRoot());
}
extension.getAdditionalSourceRoots().stream()
.filter(path -> path != null && !path.isBlank())
.forEach(sourcePaths::add);
List<File> roots = sourcePaths.stream().map(project::file).toList();
String verifyTaskName = "verify" + label + "ApiSurface";
String updateTaskName = "update" + label + "ApiSurface";
String approvalProperty = "approve" + label + "ApiSurfaceChange";
String ceilingProperty = "raise" + label + "ApiSurfaceCeiling";
boolean approved = project.hasProperty(approvalProperty);
boolean ceilingApproved = project.hasProperty(ceilingProperty);
var verify =
project
.getTasks()
.register(
verifyTaskName,
VerifyApiSurfaceTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Fails without mutation when the committed "
+ label
+ " public API surface drifts.");
task.getSourceRoots().from(roots);
task.getBaseline().fileValue(baseline);
task.getLabel().set(label);
task.getSurfaceDescription()
.set(extension.getDescription() == null ? "" : extension.getDescription());
task.getRationale().set(extension.getRationale());
task.getOwningProjectPath().set(project.getPath());
task.getUpdateTaskName().set(updateTaskName);
task.getApprovalProperty().set(approvalProperty);
task.getUpdateApproved().set(approved);
if (extension.getAdopterBaseline() != null) {
task.getAdopterBaseline().fileValue(extension.getAdopterBaseline());
if (extension.getAdopterSources() != null) {
task.getAdopterSources().from(extension.getAdopterSources());
}
}
});
project
.getTasks()
.register(
updateTaskName,
UpdateApiSurfaceTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Rewrites the committed "
+ label
+ " public API surface baseline after review.");
task.getSourceRoots().from(roots);
task.getBaseline().fileValue(baseline);
task.getLabel().set(label);
task.getSurfaceDescription()
.set(extension.getDescription() == null ? "" : extension.getDescription());
task.getRationale().set(extension.getRationale());
task.getOwningProjectPath().set(project.getPath());
task.getApprovalProperty().set(approvalProperty);
task.getCeilingProperty().set(ceilingProperty);
task.getApproved().set(approved);
task.getCeilingRaiseApproved().set(ceilingApproved);
});
// The leaf's `check`, so a pull request that changes a public type fails there (owner
// decision 20, 2026-09-25). It used to run only in `mainCheck`, which reported the change
// after it had merged.
project
.getTasks()
.matching(task -> task.getName().equals("check"))
.configureEach(task -> task.dependsOn(verify));
});
}
}
@@ -0,0 +1,89 @@
package dev.caskeleton.buildlogic.apisurface;
import dev.caskeleton.buildlogic.ApiSurfacePolicy;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.RegularFileProperty;
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.OutputFile;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
@DisableCachingByDefault(because = "This task intentionally updates a committed review baseline")
public abstract class UpdateApiSurfaceTask extends DefaultTask {
@InputFiles
public abstract ConfigurableFileCollection getSourceRoots();
@OutputFile
public abstract RegularFileProperty getBaseline();
@Input public abstract Property<String> getLabel();
@Input public abstract Property<String> getSurfaceDescription();
@Input public abstract ListProperty<String> getRationale();
@Input public abstract Property<String> getOwningProjectPath();
@Input public abstract Property<String> getApprovalProperty();
@Input public abstract Property<String> getCeilingProperty();
@Input public abstract Property<Boolean> getApproved();
@Input public abstract Property<Boolean> getCeilingRaiseApproved();
@TaskAction
public void updateSurface() {
if (!getApproved().get()) {
throw new GradleException(
getName()
+ " requires -P"
+ getApprovalProperty().get()
+ ": growing the public surface is a review decision, not a build step.");
}
List<File> roots = getSourceRoots().getFiles().stream().sorted().toList();
String rendered;
File baseline = getBaseline().get().getAsFile();
try {
rendered =
ApiSurfacePolicy.render(
roots,
getLabel().get(),
getSurfaceDescription().get(),
getRationale().get(),
getOwningProjectPath().get(),
getName(),
getApprovalProperty().get());
if (baseline.isFile()) {
ApiSurfacePolicy.requireNoUnapprovedGrowth(
getName(),
getOwningProjectPath().get(),
getApprovalProperty().get(),
getCeilingProperty().get(),
ApiSurfacePolicy.countTypes(
Files.readString(baseline.toPath(), StandardCharsets.UTF_8)),
rendered,
getCeilingRaiseApproved().get());
}
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + baseline, exception);
} catch (IllegalStateException invalidSurface) {
throw new GradleException(invalidSurface.getMessage(), invalidSurface);
}
File parent = baseline.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new GradleException("Could not create API surface baseline directory " + parent);
}
try {
Files.writeString(baseline.toPath(), rendered, StandardCharsets.UTF_8);
} catch (IOException exception) {
throw new UncheckedIOException("failed to write " + baseline, exception);
}
getLogger().lifecycle("{}: wrote {}", getName(), baseline);
}
}
@@ -0,0 +1,92 @@
package dev.caskeleton.buildlogic.apisurface;
import dev.caskeleton.buildlogic.ApiSurfacePolicy;
import dev.caskeleton.buildlogic.JavaPublicTypes;
import java.io.File;
import java.util.List;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
@DisableCachingByDefault(because = "Verification task has no reusable outputs")
public abstract class VerifyApiSurfaceTask extends DefaultTask {
@InputFiles
public abstract ConfigurableFileCollection getSourceRoots();
@Internal
public abstract RegularFileProperty getBaseline();
@Input
public String getBaselinePath() {
return getBaseline().get().getAsFile().getAbsolutePath();
}
@Input public abstract Property<String> getLabel();
@Input public abstract Property<String> getSurfaceDescription();
@Input public abstract ListProperty<String> getRationale();
@Input public abstract Property<String> getOwningProjectPath();
@Input public abstract Property<String> getUpdateTaskName();
@Input public abstract Property<String> getApprovalProperty();
@Input public abstract Property<Boolean> getUpdateApproved();
/** Other leaves' production sources, held to the adopter baseline when one is declared. */
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
public abstract ConfigurableFileCollection getAdopterSources();
@Optional
@InputFile
public abstract RegularFileProperty getAdopterBaseline();
@TaskAction
public void verifySurface() {
if (getUpdateApproved().get()) {
throw new GradleException(
getName()
+ " is read-only; use "
+ getUpdateTaskName().get()
+ " to record an approved change.");
}
List<File> roots = getSourceRoots().getFiles().stream().sorted().toList();
try {
String rendered =
ApiSurfacePolicy.render(
roots,
getLabel().get(),
getSurfaceDescription().get(),
getRationale().get(),
getOwningProjectPath().get(),
getUpdateTaskName().get(),
getApprovalProperty().get());
ApiSurfacePolicy.verify(
getName(),
getUpdateTaskName().get(),
getOwningProjectPath().get(),
getApprovalProperty().get(),
getBaseline().get().getAsFile(),
rendered);
if (getAdopterBaseline().isPresent()) {
ApiSurfacePolicy.verifyAdopters(
getName(),
rendered,
getAdopterBaseline().get().getAsFile(),
JavaPublicTypes.imports(getAdopterSources().getFiles()));
}
} catch (IllegalStateException invalidSurface) {
throw new GradleException(invalidSurface.getMessage(), invalidSurface);
}
getLogger().lifecycle("{}: OK — the committed public API surface is unchanged.", getName());
}
}
@@ -0,0 +1,201 @@
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.List;
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.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<Project> {
private static final List<String> PRODUCTION_DECLARATIONS =
List.of("api", "implementation", "compileOnly", "runtimeOnly");
/** The registry, relative to the repository root. */
public static final String REGISTRY = "config/architecture/modules.json";
@Override
public void apply(Project project) {
// One build, rooted at the repository root: the registry is the root's, and every source_path
// is relative to it (the template's main build sits in src/, which is why its copy reads the
// registry relative to the parent).
Project root = project.getRootProject();
File repositoryRoot = root.getProjectDir();
File registryFile = new File(repositoryRoot, REGISTRY);
ModuleRegistry registry = ModuleRegistry.read(registryFile, repositoryRoot);
List<ModuleRegistry.Module> modules = registry.modulesForBuild("main");
List<String> 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 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<String> 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<String> moduleTaskPaths = new ArrayList<>();
for (ModuleRegistry.Module module : modules) {
Project owner = root.project(module.gradlePath());
Set<String> allowed = new HashSet<>();
for (String dependencyId : module.allowedDependencies()) {
ModuleRegistry.Module dependency = registry.byId(dependencyId);
if (dependency != null) {
allowed.add(dependency.gradlePath().replaceFirst("^:", ""));
}
}
Set<String> declaredEdges = declaredProjectEdges(owner);
Provider<ResolvedComponentResult> 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.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);
});
// 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<File> 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, ignoredSources);
});
}
/**
* This module's declared {@code project(...)} edges, read while the owning project is configured.
*
* <p>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<String> declaredProjectEdges(Project owner) {
Set<String> 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;
}
private static List<String> registryViolations(
ModuleRegistry registry, List<ModuleRegistry.Module> modules) {
List<String> violations = new ArrayList<>();
for (ModuleRegistry.Module module : modules) {
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);
}
}
@@ -0,0 +1,96 @@
package dev.caskeleton.buildlogic.architecture;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.SetProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
/**
* The repository-wide half of the dependency contract.
*
* <p>Two questions only, and both are answered from the registry rather than from any project's
* configurations: is the registry internally consistent, and does the set of modules it governs
* match the set of leaves the build actually declares. A leaf that exists and is ungoverned is the
* failure this catches — a new module cannot be added and quietly escape the direction rules.
*
* <p>Whether a given module's edges are allowed is {@link VerifyModuleDependencyDirectionTask}'s
* job, one task per module, in the project that owns the configurations. That split is the whole
* point: this task used to resolve every other project's {@code compileClasspath} itself, which
* needs a lock it does not hold, and made {@code org.gradle.parallel=true} fail rather than merely
* be unused.
*/
@DisableCachingByDefault(because = "Verification of live build structure emits no reusable output")
public abstract class VerifyCleanArchitectureDependenciesTask extends DefaultTask {
@InputFile
public abstract RegularFileProperty getRegistryFile();
@Input
public abstract ListProperty<String> getRegistryViolations();
/** Every leaf the build declares. */
@Input
public abstract SetProperty<String> getDeclaredModules();
/** Every module the registry governs. */
@Input
public abstract ListProperty<String> getGovernedModules();
/**
* Build scripts under the Gradle root that no registry entry owns. The settings plugin includes
* registered modules only, so such a leaf never reaches {@link #getDeclaredModules()} and the
* comparison below cannot see it (review 2026-11-01 08-05).
*/
@Input
public abstract ListProperty<String> getUnregisteredBuildScripts();
@TaskAction
public void verifyDependencies() {
List<String> registryViolations = getRegistryViolations().get();
if (!registryViolations.isEmpty()) {
throw new GradleException(
"config/architecture/modules.json declares impossible edges:\n "
+ String.join("\n ", registryViolations));
}
List<String> unregistered = getUnregisteredBuildScripts().get();
if (!unregistered.isEmpty()) {
throw new GradleException(
"These build scripts have no registry entry, so the build does not include them and no"
+ " gate compiles or tests them. Register each in config/architecture/modules.json"
+ " or delete it:\n "
+ String.join("\n ", unregistered));
}
Set<String> declared = getDeclaredModules().get();
Set<String> governed = new HashSet<>(getGovernedModules().get());
Set<String> missingFromBuild = new TreeSet<>(governed);
missingFromBuild.removeAll(declared);
Set<String> missingFromPolicy = new TreeSet<>(declared);
missingFromPolicy.removeAll(governed);
if (!missingFromBuild.isEmpty()) {
throw new GradleException(
"Clean Architecture dependency policy references missing Gradle modules "
+ missingFromBuild
+ ". Declared modules are "
+ new TreeSet<>(declared)
+ ".");
}
if (!missingFromPolicy.isEmpty()) {
throw new GradleException(
"Gradle modules "
+ missingFromPolicy
+ " are not covered by verifyCleanArchitectureDependencies. Add an explicit dependency"
+ " policy before using them.");
}
}
}
@@ -0,0 +1,89 @@
package dev.caskeleton.buildlogic.architecture;
import dev.caskeleton.buildlogic.ResolvedComponents;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.SetProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
/**
* One module's own dependency-direction check, run by the project that owns the configurations.
*
* <p>This used to be a loop inside the root task, which reached into every other project and
* resolved its {@code compileClasspath}. That is the one thing a task must not do: a configuration
* belongs to its project, and resolving it from somewhere else asks Gradle for state it holds under
* another project's lock. With {@code org.gradle.parallel=true} that is not a style objection — the
* root task failed outright, which is why the flag was turned back off rather than the verification
* moved. Here the task and the configurations are in the same project, so the check costs the build
* nothing to parallelise.
*
* <p>The task keeps no {@code Configuration}. It keeps the declared project edges as strings and the
* compile classpath's resolved root component, both established while the owning project is
* configuring. Holding the configurations themselves is what made this task unstorable in the
* configuration cache.
*
* <p>The root task keeps what is genuinely repository-wide — the registry's own consistency, and
* whether the set of governed modules matches the set of declared ones — and depends on every one of
* these.
*/
@DisableCachingByDefault(because = "Verification inspects live declarations and a resolved classpath")
public abstract class VerifyModuleDependencyDirectionTask extends DefaultTask {
/** The registry name of the module this task governs. */
@Input
public abstract Property<String> getModuleName();
/** The module ids this module's registry entry permits. */
@Input
public abstract SetProperty<String> getAllowedDependencies();
/** Project paths this module declares in {@code api/implementation/compileOnly/runtimeOnly}. */
@Input
public abstract SetProperty<String> getDeclaredProjectEdges();
/** Root of this module's resolved {@code compileClasspath}. */
@Internal
public abstract Property<ResolvedComponentResult> getCompileClasspathRoot();
@TaskAction
public void verify() {
String moduleName = getModuleName().get();
Set<String> allowed = getAllowedDependencies().get();
Set<String> actual = new HashSet<>(getDeclaredProjectEdges().get());
// Declared edges are not the whole story: an `api(project(...))` two leaves away is visible to
// this module's compiler and is therefore a real edge, whatever this build file says.
for (ResolvedComponentResult component :
ResolvedComponents.reachableFrom(getCompileClasspathRoot().get())) {
if (component.getId() instanceof ProjectComponentIdentifier project) {
String projectPath = project.getProjectPath().replaceFirst("^:", "");
if (!projectPath.equals(moduleName)) {
actual.add(projectPath);
}
}
}
Set<String> forbidden = new TreeSet<>(actual);
forbidden.removeAll(allowed);
if (!forbidden.isEmpty()) {
throw new GradleException(
"Module ':"
+ moduleName
+ "' has forbidden project dependencies "
+ forbidden
+ ". Allowed dependencies are "
+ new TreeSet<>(allowed)
+ ".\nDirect and compile-visible production project edges must be explicitly"
+ " registered.");
}
}
}
@@ -0,0 +1,157 @@
package dev.caskeleton.buildlogic.architecture;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
@DisableCachingByDefault(because = "Verification consults Git ignore rules")
public abstract class VerifyNoIgnoredSourcePackagesTask extends DefaultTask {
private static final Set<String> OUTPUT_DIRECTORY_NAMES =
Set.of("build", "out", "target", "bin", "classes");
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
public abstract ConfigurableFileCollection getSourceRoots();
@Internal
public abstract DirectoryProperty getBuildRoot();
@TaskAction
public void verifySourcePackages() {
List<String> violations = new ArrayList<>();
List<File> sourceFiles = new ArrayList<>();
for (File sourceRoot : getSourceRoots().getFiles()) {
if (!sourceRoot.isDirectory()) {
continue;
}
try (var paths = Files.walk(sourceRoot.toPath())) {
paths
.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".java"))
.forEach(
path -> {
File candidate = path.toFile();
sourceFiles.add(candidate);
var relative = sourceRoot.toPath().relativize(path);
for (int index = 0; index < relative.getNameCount() - 1; index++) {
String segment = relative.getName(index).toString();
if (OUTPUT_DIRECTORY_NAMES.contains(segment)) {
violations.add(
candidate
+ ": package segment '"
+ segment
+ "' collides with a build output directory name");
}
}
});
} catch (IOException exception) {
throw new GradleException("verifyNoIgnoredSourcePackages: cannot scan " + sourceRoot, exception);
}
}
if (sourceFiles.isEmpty()) {
throw new GradleException(
"verifyNoIgnoredSourcePackages: found no Java sources at all; the gate would pass vacuously.");
}
File repositoryRoot = checkoutRoot(getBuildRoot().get().getAsFile());
if (repositoryRoot == null) {
getLogger().lifecycle("verifyNoIgnoredSourcePackages: not a Git checkout; naming rule only.");
} else {
String stdin = sourceFiles.stream().map(File::getPath).collect(java.util.stream.Collectors.joining("\n"));
String output = checkIgnore(repositoryRoot, stdin);
for (String line : output.lines().filter(value -> !value.isBlank()).toList()) {
String[] parts = line.split("\\t", -1);
String rule = parts.length > 1 ? parts[0] : "(unknown rule)";
String path = parts.length > 1 ? String.join("\t", java.util.Arrays.copyOfRange(parts, 1, parts.length)) : line;
violations.add(path + ": ignored by " + rule + "; it will not survive a fresh checkout");
}
}
if (!violations.isEmpty()) {
throw new GradleException(
"verifyNoIgnoredSourcePackages: "
+ violations.size()
+ " source file(s) Git cannot carry:\n "
+ String.join("\n ", violations));
}
getLogger()
.lifecycle(
"verifyNoIgnoredSourcePackages: OK — {} Java sources are all committable.",
sourceFiles.size());
}
/**
* The nearest directory at or above {@code start} holding {@code .git} (a directory, or the file
* a worktree has), or {@code null} for an exported source tree. Decided on the file system rather
* than by asking Git, so that Git failing inside a checkout cannot read as "not a checkout".
*/
private static File checkoutRoot(File start) {
for (File directory = start.getAbsoluteFile(); directory != null; directory = directory.getParentFile()) {
if (new File(directory, ".git").exists()) {
return directory;
}
}
return null;
}
/**
* Git's ignore verdicts for the paths on {@code stdin}. Fails closed: inside a checkout, a git that
* cannot run or exits with anything but 0 (some path ignored) or 1 (none ignored) is an error, not
* an empty answer — an empty answer is how the gate used to pass without asking.
*/
private String checkIgnore(File repositoryRoot, String stdin) {
List<String> command =
List.of("git", "-C", repositoryRoot.getPath(), "check-ignore", "--no-index", "-v", "--stdin");
Process process;
try {
process = new ProcessBuilder(command).start();
} catch (IOException unavailable) {
throw new GradleException(
"verifyNoIgnoredSourcePackages: "
+ repositoryRoot
+ " is a Git checkout but git could not run: "
+ unavailable.getMessage(),
unavailable);
}
try {
try (var input = process.getOutputStream()) {
input.write(stdin.getBytes(StandardCharsets.UTF_8));
} catch (IOException exitedEarly) {
// git stopped reading, which it does when it fails; its exit code below says why.
}
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
String error = new String(process.getErrorStream().readAllBytes(), StandardCharsets.UTF_8);
int exitCode = process.waitFor();
if (exitCode != 0 && exitCode != 1) {
throw new GradleException(
"verifyNoIgnoredSourcePackages: `git check-ignore` exited "
+ exitCode
+ " inside the Git checkout at "
+ repositoryRoot
+ ": "
+ error.strip());
}
return output;
} catch (IOException unreadable) {
throw new GradleException(
"verifyNoIgnoredSourcePackages: could not read `git check-ignore` output", unreadable);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new GradleException("verifyNoIgnoredSourcePackages: git command interrupted", interrupted);
}
}
}
@@ -0,0 +1,13 @@
package dev.caskeleton.buildlogic.convention;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
public final class JavaLibraryConventionPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPluginManager().apply("ca.quality-conventions");
project.getDependencies().add("testImplementation", "org.junit.jupiter:junit-jupiter");
project.getDependencies().add("testImplementation", "org.assertj:assertj-core");
}
}
@@ -0,0 +1,14 @@
package dev.caskeleton.buildlogic.convention;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
public final class PlatformModuleConventionPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPluginManager().apply("ca.java-library");
project.getPluginManager().apply("java-library");
// Every module of this repository is a published library artifact.
project.getPluginManager().apply("ca.library-publishing");
}
}
@@ -0,0 +1,44 @@
package dev.caskeleton.buildlogic.convention;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.PathSensitivity;
public final class SpringConfigConventionPlugin implements Plugin<Project> {
/**
* How a module declares a property the processor cannot see — a switch read only by
* {@code @ConditionalOnProperty} — so the environment contract finds it in the metadata.
*/
private static final String ADDITIONAL_METADATA =
"src/main/resources/META-INF/additional-spring-configuration-metadata.json";
@Override
public void apply(Project project) {
project
.getDependencies()
.add("annotationProcessor", "org.springframework.boot:spring-boot-configuration-processor");
// The processor merges the additional metadata from the processed resources, so compileJava
// runs after processResources and reruns when that one file changes. Without this it could run
// first, or stay up to date when only that file changed, and the declared switch was missing
// from the metadata verifyEnvKeys reads (review 2026-11-04 RR2-04-05). Only that file is an
// input: every other resource leaves compileJava's cache key alone.
project
.getPluginManager()
.withPlugin(
"java",
ignored ->
project
.getTasks()
.named(
"compileJava",
compile -> {
compile.dependsOn(project.getTasks().named("processResources"));
// files(), not file(): most modules have no such file.
compile
.getInputs()
.files(project.file(ADDITIONAL_METADATA))
.withPropertyName("additionalConfigurationMetadata")
.withPathSensitivity(PathSensitivity.RELATIVE);
}));
}
}
@@ -0,0 +1,358 @@
package dev.caskeleton.buildlogic.java;
import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.VersionCatalogsExtension;
import org.gradle.api.artifacts.dsl.LockMode;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.plugins.jvm.JvmTestSuite;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.bundling.AbstractArchiveTask;
import org.gradle.api.tasks.bundling.Jar;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.testing.Test;
import org.gradle.jvm.toolchain.JavaLanguageVersion;
import org.gradle.testing.base.TestingExtension;
public final class JavaConventionsPlugin implements Plugin<Project> {
private static final List<String> COMPILER_ARGS =
List.of("-parameters", "-Werror", "-Xlint:deprecation", "-Xlint:unchecked");
/** What {@link #sourceRevision} returns when the build was given no commit id. */
public static final String UNKNOWN_REVISION = "unknown";
/**
* The commit this build names: {@code -PgitRevision}, {@code GIT_SHA} or {@code GITHUB_SHA}, cut
* to twelve lowercase hex characters, or {@link #UNKNOWN_REVISION} when none of them is a commit
* id. The root {@code verifyReleaseProvenance} fails on the latter.
*/
public static String sourceRevision(ProviderFactory providers) {
String declared =
providers
.gradleProperty("gitRevision")
.orElse(providers.environmentVariable("GIT_SHA"))
.orElse(providers.environmentVariable("GITHUB_SHA"))
.getOrElse("");
return declared.matches("(?i)[0-9a-f]{7,40}")
? declared.toLowerCase(Locale.ROOT).substring(0, Math.min(12, declared.length()))
: UNKNOWN_REVISION;
}
/**
* The version this build names: the release tag ({@code -PreleaseTag} or {@code RELEASE_TAG},
* {@code vMAJOR.MINOR.PATCH}) without its {@code v}, else {@code -PreleaseVersion} or {@code
* RELEASE_VERSION}, else {@code 0.0.1}. A tag is how release.yml says which version it publishes,
* so a tag of any other shape fails here, before a single module is built.
*/
public static String releaseVersion(ProviderFactory providers) {
String declared =
providers
.gradleProperty("releaseVersion")
.orElse(providers.environmentVariable("RELEASE_VERSION"))
.getOrElse("");
String tag =
providers
.gradleProperty("releaseTag")
.orElse(providers.environmentVariable("RELEASE_TAG"))
.getOrElse("");
if (tag.isEmpty()) {
return declared.isEmpty() ? "0.0.1" : declared;
}
if (!tag.matches("v\\d+\\.\\d+\\.\\d+")) {
throw new GradleException(
"release tag must be vMAJOR.MINOR.PATCH with no suffix; got '" + tag + "'.");
}
String fromTag = tag.substring(1);
if (!declared.isEmpty() && !declared.equals(fromTag)) {
throw new GradleException(
"release tag " + tag + " and releaseVersion " + declared + " name different versions.");
}
return fromTag;
}
@Override
public void apply(Project project) {
project.getPluginManager().apply("java");
project.getPluginManager().apply("io.spring.dependency-management");
// `ca.strict-test-lane` supplies the per-leaf `*TestLaneCheck` aggregates that the root's
// repository-wide tasks depend on by path, so every Java leaf has to have them or the root task
// graph cannot be built. `ca.api-surface` is opt-in: a leaf that wants it says so.
project.getPluginManager().apply("ca.strict-test-lane");
var catalog = project.getExtensions().getByType(VersionCatalogsExtension.class).named("libs");
String springBootVersion = catalog.findVersion("springBoot").orElseThrow().getRequiredVersion();
ProviderFactory providers = project.getProviders();
// The Maven group every module publishes under. A property, not a constant, so this copy of the
// template's convention reads the same in every library repository (gradle.properties).
String libraryGroup = providers.gradleProperty("libraryGroup").getOrElse("");
if (libraryGroup.isBlank()) {
throw new GradleException("gradle.properties must set libraryGroup (the Maven group).");
}
project.setGroup(libraryGroup);
String releaseVersion = releaseVersion(providers);
if (!releaseVersion.matches("\\d+\\.\\d+\\.\\d+")) {
throw new GradleException(
"releaseVersion must be MAJOR.MINOR.PATCH without a leading 'v', pre-release or build"
+ " metadata; got '"
+ releaseVersion
+ "'.");
}
// The release version alone, never the revision: a revision in the version put a new jar name in
// every leaf's build/libs on every commit, which is what the deleted archive-hygiene plugin
// existed to clean up (review BUILD-O3-5). The revision stays in each jar's manifest
// (Build-Revision) and in app-bootstrap's build-info.properties, which reads the `sourceRevision`
// extra property set here. This replaced the root `ca.release-provenance` plugin.
String buildRevision = sourceRevision(providers);
project.setVersion(releaseVersion + (buildRevision.equals(UNKNOWN_REVISION) ? "-SNAPSHOT" : ""));
project.getExtensions().getExtraProperties().set("sourceRevision", buildRevision);
JavaPluginExtension javaExtension = project.getExtensions().getByType(JavaPluginExtension.class);
javaExtension.getToolchain().getLanguageVersion().set(JavaLanguageVersion.of(21));
project.getDependencyLocking().lockAllConfigurations();
project.getDependencyLocking().getLockMode().set(LockMode.STRICT);
project
.getTasks()
.withType(AbstractArchiveTask.class)
.configureEach(
archive -> {
archive.setPreserveFileTimestamps(false);
archive.setReproducibleFileOrder(true);
archive.dirPermissions(permissions -> permissions.unix("755"));
archive.filePermissions(permissions -> permissions.unix("644"));
});
project
.getTasks()
.withType(Jar.class)
.configureEach(
jar ->
jar.getManifest()
.attributes(
java.util.Map.of(
"Implementation-Version", project.getVersion().toString(),
"Build-Revision", buildRevision)));
// Both attributes change on every commit, and every test and SpotBugs task has this jar on its
// runtime classpath: without the normalization a CI build never reuses a cached test result
// (review O-4c). They describe the build, not the classes, so a runtime classpath ignores them.
project
.getNormalization()
.getRuntimeClasspath()
.metaInf(
metaInf -> {
metaInf.ignoreAttribute("Implementation-Version");
metaInf.ignoreAttribute("Build-Revision");
});
project
.getTasks()
.withType(JavaCompile.class)
.configureEach(
compile -> {
compile.getOptions().setEncoding("UTF-8");
for (String argument : COMPILER_ARGS) {
if (!compile.getOptions().getCompilerArgs().contains(argument)) {
compile.getOptions().getCompilerArgs().add(argument);
}
}
});
// Spring dependency-management reads Maven BOM property overrides from project extra properties.
// commons-lang3: the Boot BOM manages 3.19.0, and the SpotBugs worker (which shares the
// buildscript's commons-lang3) fails with NoClassDefFoundError on it; 3.20.0 is what it needs.
// Delete the override once the BOM manages 3.20.0 or later. (A `netty.version` override sat
// here too and was removed: it pinned the version the BOM already manages, review 2026-11-01
// O-11c.)
project.getExtensions().getExtraProperties().set("commons-lang3.version", "3.20.0");
// httpcore5: the Boot BOM manages 5.3.6, and the 5.3 line has no fix for two High advisories
// (CVE-2026-54399, unbounded HTTP/1 header parsing; CVE-2026-54428, unbounded HPACK header
// list). 5.4.3 is the first fixed core. httpclient5 moves with it because each client release
// is built against one core line (5.5 on 5.3, 5.6 on 5.4); 5.6.3 declares 5.4.3 and also
// carries the Content-Encoding connection-leak fix 5.5.2 lacks. Delete both once the BOM
// manages httpcore5 5.4.3 or later.
project.getExtensions().getExtraProperties().set("httpcore5.version", "5.4.3");
project.getExtensions().getExtraProperties().set("httpclient5.version", "5.6.3");
DependencyManagementExtension dependencyManagement =
project.getExtensions().getByType(DependencyManagementExtension.class);
dependencyManagement.imports(
imports ->
imports.mavenBom(
"org.springframework.boot:spring-boot-dependencies:" + springBootVersion));
// The catalog's `pinned-*` libraries: no leaf declares them, and their upstream still brings a
// version with a High or Critical advisory (the catalog says which and from where). Dependency
// management rather than a Gradle constraint because it reaches every configuration, so the
// Checkstyle and Error Prone classpaths get the fixed version too. A leaf that declares one of
// these itself, with a version, still wins.
for (String alias : catalog.getLibraryAliases()) {
if (alias.startsWith("pinned.")) {
var library = catalog.findLibrary(alias).orElseThrow().get();
String coordinates =
library.getModule() + ":" + library.getVersionConstraint().getRequiredVersion();
dependencyManagement.dependencies(dependencies -> dependencies.dependency(coordinates));
}
}
project
.getDependencies()
.add("testRuntimeOnly", "org.junit.platform:junit-platform-launcher");
project.getTasks().named("test", Test.class).configure(Test::useJUnitPlatform);
// A leaf's extra test source sets are JVM test suites (review BUILD-O3-5 replaced the
// ca.auxiliary-source-set plugin). A suite adds its framework dependency with Gradle's default
// JUnit version, and a version written into a dependency outranks the Spring Boot BOM — so the
// suites would run a different JUnit from `test`. They get the BOM's version instead.
project
.getExtensions()
.getByType(TestingExtension.class)
.getSuites()
.withType(JvmTestSuite.class)
.matching(suite -> !suite.getName().equals("test"))
.configureEach(
suite ->
suite.useJUnitJupiter(
project.provider(
() ->
dependencyManagement
.getManagedVersions()
.get("org.junit.jupiter:junit-jupiter"))));
// The main-branch stage of this leaf (the root `mainCheck` aggregates every leaf's). Empty unless
// a convention or the leaf attaches a gate that is not worth a pull request's wait.
project
.getTasks()
.register(
"mainCheck",
task -> {
task.setGroup("verification");
task.setDescription("Runs this leaf's main-branch-stage gates.");
});
boolean writeLocksRequested = project.getGradle().getStartParameter().isWriteDependencyLocks();
var resolveAndLockAll =
project
.getTasks()
.register(
"resolveAndLockAll",
ResolveConfigurationsTask.class,
task -> {
task.setGroup("build setup");
task.setDescription(
"Resolves every configuration and writes this project's dependency lock state.");
task.getRequireWriteLocks().set(true);
task.getWriteLocksRequested().set(writeLocksRequested);
task.notCompatibleWithConfigurationCache(
"Resolves configurations captured from the owning project");
});
var verifyDependencyLocks =
project
.getTasks()
.register(
"verifyDependencyLocks",
ResolveConfigurationsTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Resolves every configuration and fails when strict dependency locks drift.");
task.getRequireWriteLocks().set(false);
task.getWriteLocksRequested().set(writeLocksRequested);
task.notCompatibleWithConfigurationCache(
"Resolves configurations captured from the owning project");
});
project.afterEvaluate(
ignored -> {
List<Configuration> resolvable =
project.getConfigurations().stream().filter(Configuration::isCanBeResolved).toList();
resolveAndLockAll.configure(task -> task.setConfigurationsToResolve(resolvable));
verifyDependencyLocks.configure(task -> task.setConfigurationsToResolve(resolvable));
});
// The Mockito agent on every Test JVM, attached at startup rather than self-attached. The agent
// is the mockito-core jar alone, hence non-transitive.
Configuration agentDependencies =
project.getConfigurations().dependencyScope("mockitoAgentDependencies").get();
Configuration agent =
project
.getConfigurations()
.resolvable(
"mockitoAgent",
configuration -> {
configuration.extendsFrom(agentDependencies);
configuration.setTransitive(false);
})
.get();
project.getDependencies().add(agentDependencies.getName(), "org.mockito:mockito-core");
// Every Test JVM runs in UTC, so a timestamp test does not depend on the host's zone. A system
// property rather than a JVM argument: a strict lane's own `jvmArgs` replace the argument list,
// and this used to be repeated in 28 lanes for that reason (review 2026-11-01 O-10b).
//
// The container images the lanes start come from config/testing/container-images.properties,
// each as `ca.test.image.<key>`, with the file as an input (review 2026-11-01 08-04).
File images = containerImageCatalog(project);
Map<String, String> containerImages = containerImages(images);
project.getExtensions().getExtraProperties().set("testContainerImages", containerImages);
project
.getTasks()
.withType(Test.class)
.configureEach(
test -> {
test.systemProperty("user.timezone", "UTC");
containerImages.forEach(
(key, image) -> test.systemProperty(CONTAINER_IMAGE_PROPERTY_PREFIX + key, image));
test.getInputs()
.file(images)
.withPathSensitivity(PathSensitivity.NONE)
.withPropertyName("containerImageCatalog");
});
project
.getTasks()
.withType(Test.class)
.configureEach(
test -> {
MockitoAgentArgumentProvider provider =
project.getObjects().newInstance(MockitoAgentArgumentProvider.class);
provider.getMockitoCoreClasspath().from(agent);
provider.getOwner().set(project.getPath() + ":" + test.getName());
test.getJvmArgumentProviders().add(provider);
});
}
/** The system property prefix under which every Test JVM receives the catalog's images. */
public static final String CONTAINER_IMAGE_PROPERTY_PREFIX = "ca.test.image.";
private static File containerImageCatalog(Project project) {
File catalog = project.getRootProject().file("config/testing/container-images.properties");
if (!catalog.isFile()) {
throw new GradleException("Missing test container image catalog: " + catalog);
}
return catalog;
}
private static Map<String, String> containerImages(File catalog) {
Properties properties = new Properties();
try (var in = Files.newInputStream(catalog.toPath())) {
properties.load(in);
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + catalog, exception);
}
Map<String, String> images = new TreeMap<>();
properties.stringPropertyNames().forEach(key -> images.put(key, properties.getProperty(key)));
return Map.copyOf(images);
}
}
@@ -0,0 +1,38 @@
package dev.caskeleton.buildlogic.java;
import java.io.File;
import java.util.Comparator;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.Input;
import org.gradle.process.CommandLineArgumentProvider;
public abstract class MockitoAgentArgumentProvider implements CommandLineArgumentProvider {
@Classpath
public abstract ConfigurableFileCollection getMockitoCoreClasspath();
@Input
public abstract Property<String> getOwner();
@Override
public Iterable<String> asArguments() {
List<File> candidates =
getMockitoCoreClasspath().getFiles().stream()
.filter(File::isFile)
.filter(file -> file.getName().matches("mockito-core-[^/]+\\.jar"))
.sorted(Comparator.comparing(File::getAbsolutePath))
.toList();
if (candidates.size() != 1) {
throw new GradleException(
getOwner().get()
+ ": expected exactly one mockito-core JAR for the test JVM, found "
+ candidates.size()
+ ": "
+ candidates.stream().map(File::getAbsolutePath).toList());
}
return List.of("-javaagent:" + candidates.getFirst().getAbsolutePath(), "-Xshare:off");
}
}
@@ -0,0 +1,39 @@
package dev.caskeleton.buildlogic.java;
import java.util.List;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
import org.gradle.work.DisableCachingByDefault;
@DisableCachingByDefault(because = "Dependency resolution verifies or writes external lock state")
public abstract class ResolveConfigurationsTask extends DefaultTask {
private List<Configuration> configurations = List.of();
@Internal
public List<Configuration> getConfigurationsToResolve() {
return configurations;
}
public void setConfigurationsToResolve(List<Configuration> configurations) {
this.configurations = List.copyOf(configurations);
}
@Input
public abstract Property<Boolean> getRequireWriteLocks();
@Input
public abstract Property<Boolean> getWriteLocksRequested();
@TaskAction
public void resolveConfigurations() {
if (getRequireWriteLocks().get() && !getWriteLocksRequested().get()) {
throw new GradleException(getPath() + " requires the --write-locks command-line flag.");
}
configurations.forEach(Configuration::resolve);
}
}
@@ -0,0 +1,185 @@
package dev.caskeleton.buildlogic.publishing;
import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.component.AdhocComponentWithVariants;
import org.gradle.api.credentials.HttpHeaderCredentials;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.provider.Provider;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.MavenPublication;
import org.gradle.api.publish.maven.tasks.PublishToMavenRepository;
import org.gradle.authentication.http.HttpHeaderAuthentication;
import org.gradle.plugins.signing.Sign;
import org.gradle.plugins.signing.SigningExtension;
/**
* Publishes one library module to the owner's Gitea Maven registry, or to a staging directory.
*
* <p>Every module publishes one Maven publication, {@code maven}, built from the {@code java}
* component with its sources and javadoc jars. Two repositories:
*
* <ul>
* <li>{@code gitea}: {@code packagesUrl} from gradle.properties, authenticated with the {@code
* Authorization: token <PACKAGE_TOKEN>} header. Gitea's job token cannot publish packages,
* so the token is a package-scoped personal access token in a repository secret; it is read
* from the environment and never written to a file.
* <li>{@code staging}: {@code build/staging-repository} under the root project. {@code
* releaseRehearsal} publishes there, so everything up to the upload runs without a secret.
* </ul>
*
* <p>Versions: the leaves declare most dependencies without a version and let Spring dependency
* management fill it from a BOM. A published POM or Gradle module file written from the
* declarations would carry no version, so the publication maps every variant's dependencies to
* the versions its own resolution chose ({@code versionMapping}), and the plugin's POM
* customization, which would add the BOM imports a consumer never inherits, is off.
*
* <p>Signing: with {@code SIGNING_KEY} (an ASCII-armoured PGP secret key, or the base64 of one;
* {@link SigningKeys}) and {@code
* SIGNING_PASSWORD} in the environment, every published file gets an {@code .asc}. Without them
* nothing is signed, and a task that uploads to {@code gitea} fails before it starts: an unsigned
* release is not a release.
*/
public final class LibraryPublishingPlugin implements Plugin<Project> {
public static final String PUBLICATION = "maven";
public static final String GITEA_REPOSITORY = "gitea";
public static final String STAGING_REPOSITORY = "staging";
@Override
public void apply(Project project) {
project.getPluginManager().apply("maven-publish");
project.getPluginManager().apply("signing");
JavaPluginExtension java = project.getExtensions().getByType(JavaPluginExtension.class);
java.withSourcesJar();
java.withJavadocJar();
project
.getExtensions()
.getByType(DependencyManagementExtension.class)
.generatedPomCustomization(customization -> customization.setEnabled(false));
// Test fixtures are this repository's own test support (messaging-kafka's, shared by its
// integration lanes); the published testkit is messaging-testkit. They stay out of the
// publication, which also keeps a capability Maven cannot express out of the POM.
project
.getPlugins()
.withId(
"java-test-fixtures",
ignored -> {
AdhocComponentWithVariants component =
(AdhocComponentWithVariants) project.getComponents().getByName("java");
for (String variant : List.of("testFixturesApiElements", "testFixturesRuntimeElements")) {
component.withVariantsFromConfiguration(
project.getConfigurations().getByName(variant), details -> details.skip());
}
});
Provider<String> packagesUrl = project.getProviders().gradleProperty("packagesUrl");
Provider<String> repositoryUrl = project.getProviders().gradleProperty("repositoryUrl");
Provider<String> token = project.getProviders().environmentVariable("PACKAGE_TOKEN");
PublishingExtension publishing = project.getExtensions().getByType(PublishingExtension.class);
MavenPublication publication =
publishing
.getPublications()
.create(
PUBLICATION,
MavenPublication.class,
maven -> {
maven.from(project.getComponents().getByName("java"));
maven.versionMapping(
mapping -> mapping.allVariants(variant -> variant.fromResolutionResult()));
maven.pom(
pom -> {
pom.getName().set(project.getName());
pom.getDescription()
.set(
project.provider(
() ->
project.getDescription() == null
? project.getName()
: project.getDescription()));
pom.getUrl().set(repositoryUrl);
pom.scm(
scm -> {
scm.getUrl().set(repositoryUrl);
scm.getConnection().set(repositoryUrl.map(url -> "scm:git:" + url + ".git"));
});
});
});
publishing
.getRepositories()
.maven(
repository -> {
repository.setName(GITEA_REPOSITORY);
repository.setUrl(packagesUrl);
repository.credentials(
HttpHeaderCredentials.class,
credentials -> {
credentials.setName("Authorization");
credentials.setValue("token " + token.getOrElse(""));
});
repository.getAuthentication().create("header", HttpHeaderAuthentication.class);
});
publishing
.getRepositories()
.maven(
repository -> {
repository.setName(STAGING_REPOSITORY);
repository.setUrl(
project
.getRootProject()
.getLayout()
.getBuildDirectory()
.dir("staging-repository"));
});
String signingKey =
SigningKeys.armoured(project.getProviders().environmentVariable("SIGNING_KEY").getOrElse(""));
String signingPassword =
project.getProviders().environmentVariable("SIGNING_PASSWORD").getOrElse("");
boolean signed = !signingKey.isBlank();
if (signed) {
SigningExtension signing = project.getExtensions().getByType(SigningExtension.class);
signing.useInMemoryPgpKeys(signingKey, signingPassword);
signing.sign(publication);
// The root's verifySigningKey says what is wrong with a key before Gradle's signing reports
// it only as "Could not read PGP secret key".
project.getTasks().withType(Sign.class).configureEach(task -> task.mustRunAfter(":verifySigningKey"));
}
// Nothing leaves the machine before the release checks have passed, and nothing reaches Gitea
// unsigned or without a token. Gitea refuses a second upload of a version, so a half-published
// version cannot be repaired by publishing it again; the checks run first (design 05, 7.2).
project
.getTasks()
.withType(PublishToMavenRepository.class)
.configureEach(
task -> {
task.mustRunAfter(":releaseCheck");
if (task.getName().endsWith("To" + capitalized(GITEA_REPOSITORY) + "Repository")) {
task.doFirst(
"requireReleaseCredentials",
ignored -> {
if (!signed) {
throw new GradleException(
"SIGNING_KEY is not set; refusing to publish unsigned files to Gitea.");
}
if (token.getOrElse("").isBlank()) {
throw new GradleException(
"PACKAGE_TOKEN is not set; Gitea's job token cannot publish packages.");
}
});
}
});
}
private static String capitalized(String name) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
}
@@ -0,0 +1,42 @@
package dev.caskeleton.buildlogic.publishing;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* The ASCII-armoured key Gradle's in-memory signatory reads, from what a CI secret holds.
*
* <p>A secret store keeps a multi-line value badly or not at all, so the common practice is to put
* the armoured key file in base64 on one line ({@code base64 -w0 signing-key.asc}). Gradle's {@code
* useInMemoryPgpKeys} reads only the armoured text and reports the base64 form as "Could not read
* PGP secret key" (v1.0.0 release run 9 and the secret put in after it). Both forms are accepted:
* a value that decodes to an armoured private key block is unwrapped, anything else is passed on
* unchanged, so a wrong value still fails, and {@code verifySigningKey} says why.
*/
public final class SigningKeys {
private static final String BEGIN = "-----BEGIN PGP PRIVATE KEY BLOCK-----";
private SigningKeys() {}
/**
* The armoured key: {@code value} itself, or the armoured block it is the base64 of.
*
* @param value the secret as given (armoured, base64 of the armoured file, or anything else)
* @return the armoured key, or {@code value} unchanged when it is neither form
*/
public static String armoured(String value) {
if (value == null || value.isBlank() || value.contains(BEGIN)) {
return value;
}
String compact = value.replaceAll("\\s", "");
if (!compact.matches("[A-Za-z0-9+/]+={0,2}")) {
return value;
}
try {
String decoded = new String(Base64.getDecoder().decode(compact), StandardCharsets.UTF_8);
return decoded.strip().startsWith(BEGIN) ? decoded : value;
} catch (IllegalArgumentException notBase64) {
return value;
}
}
}
@@ -0,0 +1,284 @@
package dev.caskeleton.buildlogic.quality;
import com.diffplug.gradle.spotless.SpotlessExtension;
import com.github.spotbugs.snom.Confidence;
import com.github.spotbugs.snom.SpotBugsExtension;
import com.github.spotbugs.snom.SpotBugsReport;
import com.github.spotbugs.snom.SpotBugsTask;
import java.io.File;
import java.util.List;
import net.ltgt.gradle.errorprone.ErrorProneOptions;
import net.ltgt.gradle.errorprone.ErrorProneOptionsKt;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.VersionCatalog;
import org.gradle.api.artifacts.VersionCatalogsExtension;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.plugins.quality.Checkstyle;
import org.gradle.api.plugins.quality.CheckstyleExtension;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.compile.JavaCompile;
public final class QualityConventionsPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPluginManager().apply("ca.java-conventions");
project.getPluginManager().apply("com.diffplug.spotless");
project.getPluginManager().apply("checkstyle");
project.getPluginManager().apply("com.github.spotbugs");
project.getPluginManager().apply("net.ltgt.errorprone");
VersionCatalog catalog =
project.getExtensions().getByType(VersionCatalogsExtension.class).named("libs");
JavaPluginExtension javaExtension =
project.getExtensions().getByType(JavaPluginExtension.class);
SourceSet main = javaExtension.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);
SourceSet test = javaExtension.getSourceSets().getByName(SourceSet.TEST_SOURCE_SET_NAME);
File repositoryConfigDirectory = project.getRootProject().file("config");
SpotlessExtension spotless = project.getExtensions().getByType(SpotlessExtension.class);
spotless.java(
java -> {
java.googleJavaFormat(version(catalog, "googleJavaFormat"));
java.importOrder();
java.removeUnusedImports();
});
CheckstyleExtension checkstyle =
project.getExtensions().getByType(CheckstyleExtension.class);
checkstyle.setToolVersion(version(catalog, "checkstyle"));
checkstyle.setConfigFile(new File(repositoryConfigDirectory, "checkstyle/checkstyle.xml"));
checkstyle.getConfigDirectory().set(new File(repositoryConfigDirectory, "checkstyle"));
checkstyle.setIgnoreFailures(false);
checkstyle.setMaxWarnings(Integer.MAX_VALUE);
checkstyle.setSourceSets(List.of(main, test));
SpotBugsExtension spotBugs = project.getExtensions().getByType(SpotBugsExtension.class);
spotBugs.getToolVersion().set(version(catalog, "spotbugs"));
// MEDIUM (review 2026-11-01 08-07, decided 2026-11-03). HIGH reported 0 findings and left out
// FindSecBugs' injection, ReDoS and weak-crypto rules, which report at MEDIUM. The first MEDIUM
// run over every analysed leaf reported 307 findings, all priority 2, and each was judged
// against the code it names: "fixed" changed the code, "excluded" is a Match in
// config/spotbugs/exclude.xml that carries its reason.
//
// pattern / group found fixed excluded
// EI_EXPOSE_REP, EI_EXPOSE_REP2 196 11 185
// non-collection references (collaborators) 97 - 97 pattern
// settings binding carriers 43 - 43 by class
// transport DTOs under adapter.inbound 23 - 23 pattern
// collection already copied at construction 20 - 20 class+field
// value type exposing mutable state 13 11 2 per site
// CT_CONSTRUCTOR_THROW 63 24 39
// made final (21 classes) 24 24 -
// CGLIB-proxied (@RequiresPermission, @Configuration) 30 - 30 annotation
// designed for extension (exception roots, bases) 9 - 9 by class
// SECURITY: REDOS 11, UNSAFE_HASH_EQUALS 7, 25 0 25 per site
// SQL_INJECTION_* 3, PREDICTABLE_RANDOM 2, XSS 1, WEAK_MESSAGE_DIGEST_SHA1 1
// others 23 11 12 per site
// NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE 13 (6 fixed), AT_NONATOMIC 2 (fixed),
// NP_NULL_ON_SOME_PATH 1 (fixed), BC_IMPOSSIBLE_INSTANCEOF 1 (fixed), BX_UNBOXING 1
// (fixed), RV_RETURN_VALUE_IGNORED 2, MS_EXPOSE_REP 2, DLS_DEAD_LOCAL_STORE 1
// total 307 46 261
//
// Found afterwards and judged the same way (review 15절, r3-L): the optional-platforms (gRPC)
// build reads this same exclude file and had not been analysed at MEDIUM (13), and the
// httpclient retry jitter source r3-J added (1).
// USO_UNSAFE_METHOD_SYNCHRONIZATION 6 6 -
// GrpcAdmissionController: private lock object
// SECURITY: REDOS 4, UNSAFE_HASH_EQUALS 1, 7 0 7 per site
// COMMAND_INJECTION 1, PREDICTABLE_RANDOM 1
// CT_CONSTRUCTOR_THROW (GrpcPlatformException root) 1 0 1 by class
// total 14 6 8
//
// A new finding fails qualityCheck. Fix it, or add a Match scoped to the class and method (or
// field) with the reason it is not a defect. A pattern-wide Match needs a reason that holds for
// every class it can ever match, as the EI reference and DTO patterns state theirs.
spotBugs.getReportLevel().set(Confidence.MEDIUM);
spotBugs.getExcludeFilter().set(new File(repositoryConfigDirectory, "spotbugs/exclude.xml"));
// Keep local check fast; qualityCheck is the explicit bytecode-analysis lane.
spotBugs.getRunOnCheck().set(false);
// Test code (every source set but main) is analysed too, by testQualityCheck, against its own
// filter: config/spotbugs/exclude-test.xml says which rules do not apply to code that never
// runs in production, and why. Until 2026-11-04 these tasks existed, ran in no gate, and 53 of
// them failed (300 findings) without anyone seeing it.
File testExcludeFilter = new File(repositoryConfigDirectory, "spotbugs/exclude-test.xml");
// Registered after evaluation on purpose. The SpotBugs plugin registers a task per source set
// and, in that registration, sets the task's auxiliary classpath to the compile classpath. A
// configureEach added before a task is registered runs before that registration action, so
// for every source set created after this plugin (testFixtures, the test suites) an earlier
// configureEach was overwritten and the runtime classpath below never arrived.
project.afterEvaluate(
evaluated ->
evaluated
.getTasks()
.withType(SpotBugsTask.class)
.configureEach(
task -> {
SourceSet analysed = analysedSourceSet(javaExtension, task);
if (analysed == null) {
return;
}
if (!analysed.getName().equals(SourceSet.MAIN_SOURCE_SET_NAME)) {
task.getExcludeFilter().set(testExcludeFilter);
}
// The compile classpath alone leaves out runtime-only types a class still
// links against (org.jboss.logging.BasicLogger, a Resilience4j supertype a
// fixture implements), and the analysis of everything that touches them is
// then incomplete.
task.getAuxClassPaths()
.from(analysed.getRuntimeClasspath().minus(analysed.getOutput()));
}));
project
.getTasks()
.withType(SpotBugsTask.class)
.configureEach(
task -> {
if (analysedSourceSet(javaExtension, task) == null) {
return;
}
// The SpotBugs Gradle plugin rewrites this file without truncating it. A classpath
// shorter than the previous run's (the version drops from `0.0.1+<revision>` to
// `0.0.1-SNAPSHOT` once the tree is dirty) keeps the old tail, the last entry reads
// `...-SNAPSHOT.jar.jar`, and SpotBugs reports its classes as missing.
File auxClasspathFile =
project
.getLayout()
.getBuildDirectory()
.file("spotbugs/auxclasspath/" + task.getName())
.get()
.getAsFile();
task.doFirst(ignored -> auxClasspathFile.delete());
SpotBugsReport xml = task.getReports().maybeCreate("xml");
xml.getRequired().set(true);
task.doLast(
ignored -> {
List<String> failures =
SpotBugsAnalysisReport.failures(xml.getOutputLocation().get().getAsFile());
if (!failures.isEmpty()) {
throw new GradleException(
task.getPath()
+ ": SpotBugs analysis incomplete:\n "
+ String.join("\n ", failures));
}
});
});
project
.getTasks()
.withType(JavaCompile.class)
.configureEach(
compile -> {
ErrorProneOptions options =
ErrorProneOptionsKt.getErrorprone(compile.getOptions());
options.getDisableWarningsInGeneratedCode().set(true);
});
// JMH (me.champeau.jmh) compiles benchmarks and the code it generates from them; neither is
// shipped, and generated code does not answer to the repository's lint or bug patterns.
project
.getPluginManager()
.withPlugin(
"me.champeau.jmh",
ignored -> {
project
.getTasks()
.withType(JavaCompile.class)
.matching(
compile ->
compile.getName().equals("compileJmhJava")
|| compile.getName().equals("jmhCompileGeneratedClasses"))
.configureEach(
compile -> {
ErrorProneOptionsKt.getErrorprone(compile.getOptions())
.getEnabled()
.set(false);
compile.getOptions().getCompilerArgs().removeIf("-Werror"::equals);
});
project
.getTasks()
.matching(
task ->
task.getName().equals("spotbugsJmh")
|| task.getName().equals("checkstyleJmh"))
.configureEach(task -> task.setEnabled(false));
});
project
.getDependencies()
.add(
"spotbugsPlugins",
"com.h3xstream.findsecbugs:findsecbugs-plugin:" + version(catalog, "findsecbugs"));
project
.getDependencies()
.add(
"errorprone",
"com.google.errorprone:error_prone_core:" + version(catalog, "errorprone"));
project
.getTasks()
.register(
"auxiliaryStyleCheck",
task -> {
task.setGroup("verification");
task.setDescription(
"Runs Checkstyle for non-default source sets outside the fast local check lane.");
task.dependsOn(
project
.getTasks()
.withType(Checkstyle.class)
.matching(
check ->
!check.getName().equals("checkstyleMain")
&& !check.getName().equals("checkstyleTest")));
});
project
.getTasks()
.register(
"qualityCheck",
task -> {
task.setGroup("verification");
task.setDescription("Runs this leaf's SpotBugs and FindSecBugs bytecode analysis.");
task.dependsOn(project.getTasks().named("spotbugsMain"));
});
project
.getTasks()
.register(
"testQualityCheck",
task -> {
task.setGroup("verification");
task.setDescription(
"Runs SpotBugs and FindSecBugs over this leaf's test source sets"
+ " (config/spotbugs/exclude-test.xml).");
task.dependsOn(
project
.getTasks()
.withType(SpotBugsTask.class)
.matching(
spotbugs ->
!spotbugs.getName().equals("spotbugsMain")
&& !spotbugs.getName().equals("spotbugsJmh")));
});
}
/** The source set a {@code spotbugs<SourceSet>} task analyses, or null for any other name. */
private static SourceSet analysedSourceSet(JavaPluginExtension javaExtension, SpotBugsTask task) {
String suffix = task.getName().substring("spotbugs".length());
if (suffix.isEmpty()) {
return null;
}
return javaExtension
.getSourceSets()
.findByName(Character.toLowerCase(suffix.charAt(0)) + suffix.substring(1));
}
private static String version(VersionCatalog catalog, String alias) {
return catalog
.findVersion(alias)
.orElseThrow(
() -> new GradleException("Version catalog 'libs' must define version '" + alias + "'"))
.getRequiredVersion();
}
}
@@ -0,0 +1,63 @@
package dev.caskeleton.buildlogic.quality;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
final class SpotBugsAnalysisReport {
private SpotBugsAnalysisReport() {}
static List<String> failures(File reportFile) {
List<String> failures = new ArrayList<>();
if (!reportFile.isFile()) {
return List.of("missing XML report " + reportFile);
}
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setExpandEntityReferences(false);
factory.setXIncludeAware(false);
var document = factory.newDocumentBuilder().parse(reportFile);
NodeList errorsNodes = document.getElementsByTagName("Errors");
if (errorsNodes.getLength() != 1) {
return List.of("expected one Errors element in " + reportFile.getName());
}
Element errors = (Element) errorsNodes.item(0);
NodeList missingClasses = errors.getElementsByTagName("MissingClass");
for (int index = 0; index < missingClasses.getLength(); index++) {
String className = missingClasses.item(index).getTextContent().trim();
failures.add("missing analysis class " + (className.isBlank() ? "<unnamed>" : className));
}
NodeList errorNodes = errors.getElementsByTagName("Error");
for (int index = 0; index < errorNodes.getLength(); index++) {
Element error = (Element) errorNodes.item(index);
NodeList messages = error.getElementsByTagName("ErrorMessage");
String message =
messages.getLength() == 0 ? "" : messages.item(0).getTextContent().trim();
failures.add("analysis error " + (message.isBlank() ? "<no message>" : message));
}
validateDeclaredCount(failures, errors, "missingClasses", missingClasses.getLength());
validateDeclaredCount(failures, errors, "errors", errorNodes.getLength());
return List.copyOf(failures);
} catch (Exception exception) {
return List.of("unreadable XML report: " + exception.getMessage());
}
}
private static void validateDeclaredCount(
List<String> failures, Element errors, String attribute, int observed) {
String declared = errors.getAttribute(attribute);
if (!declared.matches("\\d+")) {
failures.add("invalid " + attribute + " count '" + declared + "'");
return;
}
if (Integer.parseInt(declared) > observed) {
failures.add(declared + " " + attribute + " reported but only " + observed + " detailed");
}
}
}
@@ -0,0 +1,22 @@
package dev.caskeleton.buildlogic.settings;
import dev.caskeleton.buildlogic.ModuleRegistrySettingsInstaller;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.gradle.api.Plugin;
import org.gradle.api.initialization.Settings;
public final class ArchitectureRegistrySettingsPlugin implements Plugin<Settings> {
@Override
public void apply(Settings settings) {
try {
// The Gradle root is the repository root here; source_path in the registry is relative to it.
File repositoryRoot = settings.getSettingsDir().getCanonicalFile();
File registryFile = new File(settings.getSettingsDir(), "config/architecture/modules.json");
ModuleRegistrySettingsInstaller.install(settings, registryFile, repositoryRoot, "main");
} catch (IOException exception) {
throw new UncheckedIOException("failed to resolve architecture registry paths", exception);
}
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.buildlogic.strictlane;
import org.gradle.api.services.BuildService;
import org.gradle.api.services.BuildServiceParameters;
/**
* One slot, shared by every lane that starts a real server or container.
*
* <p>Turning on {@code org.gradle.parallel} made three web throttle IT cases and a WebSocket
* shutdown contract fail on socket timeouts, and pass when run alone. Those lanes start an embedded
* server and then assert on timing — a permit released at the wrong
* moment, a capacity refusal that has to arrive inside a five-second read timeout, connections
* closed rather than dropped during shutdown. Several of them at once means the machine decides the
* result, not the code, and a gate whose result depends on the machine is the kind this repository's
* own review says gets switched off within a quarter.
*
* <p>Ordering them inside one leaf was not enough: the contention is across leaves. A build service
* with {@code maxParallelUsages = 1} is Gradle's answer to "these tasks must not overlap", and it
* scopes to exactly the lanes that need it — every strict lane whose category is not {@code TEST}.
* The hermetic unit lanes, which are the bulk of the build and the reason to run in parallel at all,
* are untouched.
*/
public abstract class ExclusiveRealServerLaneService
implements BuildService<BuildServiceParameters.None> {}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,60 @@
package dev.caskeleton.buildlogic.strictlane;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.gradle.api.tasks.testing.TestDescriptor;
import org.gradle.api.tasks.testing.TestListener;
import org.gradle.api.tasks.testing.TestResult;
final class StrictLaneExecutionTracker implements TestListener {
private final boolean collectSelectors;
private final AtomicLong executed = new AtomicLong();
private final AtomicLong skipped = new AtomicLong();
private final Set<String> executedSelectors =
Collections.synchronizedSet(new LinkedHashSet<>());
StrictLaneExecutionTracker(boolean collectSelectors) {
this.collectSelectors = collectSelectors;
}
long executedCount() {
return executed.get();
}
long skippedCount() {
return skipped.get();
}
Set<String> executedSelectors() {
synchronized (executedSelectors) {
return Set.copyOf(executedSelectors);
}
}
@Override
public void beforeSuite(TestDescriptor suite) {}
@Override
public void afterSuite(TestDescriptor suite, TestResult result) {}
@Override
public void beforeTest(TestDescriptor testDescriptor) {}
@Override
public void afterTest(TestDescriptor descriptor, TestResult result) {
if (result.getResultType() == TestResult.ResultType.SKIPPED) {
skipped.incrementAndGet();
return;
}
executed.incrementAndGet();
if (collectSelectors) {
String className = descriptor.getClassName();
if (className != null) {
executedSelectors.add(className);
executedSelectors.add(className + "." + descriptor.getName());
}
}
}
}
@@ -0,0 +1,28 @@
package dev.caskeleton.buildlogic.strictlane;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.provider.ListProperty;
/**
* The stages a strict lane may belong to, and where the workflows that run them live.
*
* <p>A stage is a task path a workflow executes ({@code :ci}, {@code :mainCheck}, ...). Every strict
* lane that is not {@code explicitOnly} must be in the plan of at least one stage, and every stage
* must be executed — not merely planned with {@code --dry-run} — by at least one workflow.
*/
public abstract class StrictLaneStagesExtension {
public abstract ListProperty<String> getStages();
/**
* The repository's {@code .github/workflows}. Its grandparent is the repository root, and a
* command executes this build's stages only when it starts in this build's directory from there
* — its step's {@code working-directory} joined with its {@code -p}. The directory is read from
* where the build is, so no build states it (review 2026-11-04 RR2-04-04: a {@code -p} value
* alone missed {@code working-directory: src/platforms/optional-build} with {@code ../gradlew}).
*/
public abstract DirectoryProperty getWorkflowDirectory();
public void stage(String... taskPaths) {
getStages().addAll(taskPaths);
}
}
@@ -0,0 +1,322 @@
package dev.caskeleton.buildlogic.strictlane;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.execution.TaskExecutionGraph;
/**
* Fails when a strict lane belongs to no stage a workflow executes.
*
* <p>A strict lane fails closed when it runs, but nothing makes it run: a lane that no workflow
* reaches is a file that looks like coverage (review 2026-11-01 08-01 found fourteen). The rule is
* stated once, here, instead of as one workflow line per lane:
*
* <ol>
* <li>every strict lane that is not {@code explicitOnly} is in the task plan of a declared stage
* as a workflow runs it — a lane the command removes with {@code -x} is not covered, matched
* the way Gradle matches it, abbreviations included ({@link TaskSelectors});
* <li>every declared stage is executed by a workflow. Not counted ({@code NOT_COUNTED}; review
* 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04, RR5-02-02, 2026-11-05 RR6-04-01..06, 2026-11-06
* RR7-05-01, owner decision 2026-11-07 on the release flow): a command
* after which Gradle runs no task ({@code --dry-run}, {@code -v}, {@code --help}, …) or that
* Gradle rejects (a short-option bundle such as {@code -mx}), one for another build, and one
* that does not gate for one of three reasons — its failure may not fail its step, it may not
* run, or this check does not read it although its failure would fail the step ({@code
* WorkflowGradleInvocations} and {@code ShellScript} name the shapes).
* </ol>
*
* <p>Each build that holds strict lanes applies it at its own root: the main build, and the
* optional-platforms build. A command executes this build when it starts in this build's directory
* — its step's {@code working-directory}, moved by the {@code cd} commands the same shell surely
* ran before it, joined with its {@code -p}, from the repository root, which is where GitHub keeps
* {@code .github/workflows} ({@code ShellScript} says which {@code cd} it follows).
* A stage named only by commands that do not count is reported with each command's reason. Applied
* to the main build only, it said "every strict lane" while the optional build's performance lane
* ran nowhere (RR-06-03).</p>
*
* <p>The task plan is Gradle's own: {@code verifyStrictLaneStages} depends on the stages, so a
* {@code --dry-run} of it builds the real plan, and the check reads it when the graph is ready. It
* refuses to run without {@code --dry-run}, which would execute every stage.
*/
public final class StrictLaneStagesPlugin implements Plugin<Project> {
public static final String TASK_NAME = "verifyStrictLaneStages";
/** What a failure names as not counted, in the three reasons the readers give, and what to do. */
static final String NOT_COUNTED =
"Not counted: a command after which Gradle runs no task (--dry-run, -m, -v, --help,"
+ " --status, ...) or that Gradle rejects (a short-option bundle such as -mx), and one"
+ " for another build; one whose failure may not fail its step (|| true, a pipe without"
+ " pipefail, !, &, an if/while condition, the part before && of a list that is not the"
+ " script's last command, after set +e or a trap that exits 0, continue-on-error); one"
+ " that may not run (after ||, inside if/while/for/case or a function, after an exit 0,"
+ " exec or set -n, under an if: other than always()/success()/!cancelled(), in a"
+ " workflow that starts only on a request, or on changes only through a paths or"
+ " paths-ignore filter, or a reusable one no counted job calls, in a"
+ " job that needs a job that may be skipped, and for any stage but :releaseCheck in a"
+ " workflow that starts only on a tag push or a release); and one this check does not"
+ " read although"
+ " its failure"
+ " would fail the step (|| exit 1, inside { } or ( ), $( ), bash -c, gradlew as"
+ " another command's argument, after a cd it does not follow, a shell other than bash"
+ " or sh, a runner that may be Windows). Run the stage as ./gradlew on a line of its"
+ " own, in a step and job that run on every push, pull request or schedule, with no"
+ " paths or paths-ignore filter (:releaseCheck may run on a tag push or a release)";
@Override
public void apply(Project project) {
if (project != project.getRootProject()) {
throw new GradleException("ca.strict-lane-stages is applied to the root project only.");
}
StrictLaneStagesExtension extension =
project.getExtensions().create("strictLaneStages", StrictLaneStagesExtension.class);
var verify =
project
.getTasks()
.register(
TASK_NAME,
task -> {
task.setGroup("verification");
task.setDescription(
"Fails when a strict lane is in no stage a workflow executes. Run with --dry-run.");
task.notCompatibleWithConfigurationCache(
"the check reads the task graph itself, which a cached entry does not rebuild");
});
project.afterEvaluate(
ignored -> verify.configure(task -> task.dependsOn(extension.getStages().get().toArray())));
project
.getGradle()
.getTaskGraph()
.whenReady(
graph -> {
Task task = verify.get();
if (!graph.hasTask(task)) {
return;
}
if (!project.getGradle().getStartParameter().isDryRun()) {
throw new GradleException(
TASK_NAME
+ " checks the plan of "
+ extension.getStages().get()
+ " and would execute all of them; run it with --dry-run.");
}
File workflowDirectory = extension.getWorkflowDirectory().get().getAsFile();
List<String> problems =
problems(
project,
graph,
extension.getStages().get(),
workflowDirectory,
buildDirectory(project, workflowDirectory));
if (!problems.isEmpty()) {
throw new GradleException(
TASK_NAME
+ ": "
+ problems.size()
+ " problem(s). A lane no executed stage reaches runs nowhere; put it in a"
+ " stage, or declare explicitOnly(\"reason\") if it needs an input no stage"
+ " has.\n - "
+ String.join("\n - ", problems));
}
project
.getLogger()
.lifecycle(
TASK_NAME + ": every strict lane is in an executed stage.");
});
}
private static List<String> problems(
Project root,
TaskExecutionGraph graph,
List<String> stages,
File workflowDirectory,
String buildDirectory) {
List<String> problems = new ArrayList<>(foldedCommandBreaks(workflowDirectory));
Map<String, List<WorkflowGradleInvocations.Invocation>> invocationsByWorkflow =
invocations(workflowDirectory);
List<WorkflowGradleInvocations.Invocation> invocations =
invocationsByWorkflow.values().stream().flatMap(List::stream).toList();
// Only an executed stage covers a lane — a stage no workflow runs is the same gap one level
// up — and only as the command runs it: what its -x removes is not covered.
Map<String, Set<String>> tasksByProject = new LinkedHashMap<>();
root.getAllprojects()
.forEach(
project -> tasksByProject.put(project.getPath(), Set.copyOf(project.getTasks().getNames())));
Map<String, Set<String>> plans = new LinkedHashMap<>();
for (String stage : stages) {
List<WorkflowGradleInvocations.Invocation> executions =
invocations.stream()
.filter(invocation -> invocation.executes(stage, buildDirectory))
.toList();
if (executions.isEmpty()) {
problems.add(
"stage "
+ stage
+ " is executed by no workflow in "
+ workflowDirectory.getName()
+ " for the build in "
+ buildDirectory
+ ". "
+ NOT_COUNTED
+ notCounted(invocationsByWorkflow, stage, buildDirectory));
continue;
}
Task stageTask = root.getTasks().findByPath(stage);
int run = 0;
for (WorkflowGradleInvocations.Invocation execution : executions) {
Set<String> excluded =
TaskSelectors.excludedPaths(execution.excludedTasks(), tasksByProject);
plans.put(
stage + "#" + run++, stageTask == null ? Set.of() : plan(graph, stageTask, excluded));
}
}
List<String> lanes = new ArrayList<>();
root.getAllprojects().stream()
.sorted(Comparator.comparing(Project::getPath))
.forEach(
project -> {
StrictTestLaneExtension lanesOf =
project.getExtensions().findByType(StrictTestLaneExtension.class);
if (lanesOf == null) {
return;
}
lanesOf.getLanes().stream()
.filter(lane -> lane.getExplicitOnlyReason() == null)
.map(lane -> taskPath(project, lane.getName()))
.sorted()
.forEach(lanes::add);
});
for (String lane : lanes) {
if (plans.values().stream().noneMatch(plan -> plan.contains(lane))) {
problems.add("strict lane " + lane + " is in no executed stage of " + stages);
}
}
return problems;
}
/**
* The commands that name {@code stage} but do not execute it for this build, each with why — its
* uncounted reason, the other build it starts (review 2026-11-04 RR5-02-03: a typo in a {@code cd}
* or a {@code cd src} under {@code working-directory: src} is named, not hidden), or a dry run: a
* workflow that calls the stage in a way this check does not count is told so, instead of failing
* as if it never did.
*/
private static String notCounted(
Map<String, List<WorkflowGradleInvocations.Invocation>> invocationsByWorkflow,
String stage,
String buildDirectory) {
List<String> lines = new ArrayList<>();
invocationsByWorkflow.forEach(
(workflow, invocations) ->
invocations.stream()
.filter(invocation -> invocation.requests(stage))
.forEach(
invocation ->
lines.add(
workflow
+ ": gradlew "
+ String.join(" ", invocation.tasks())
+ " — "
+ invocation.whyNotExecuting(stage, buildDirectory))));
return lines.isEmpty()
? ""
: "; commands that name it but do not count:\n " + String.join("\n ", lines);
}
/**
* The tasks {@code stage} reaches as a command runs it: what its -x removes is cut off. A task of
* an included build (a stage that runs build-logic's tests) is not in this build's plan and holds
* none of its lanes, so the walk does not ask the graph about it — the graph would refuse.
*/
private static Set<String> plan(TaskExecutionGraph graph, Task stage, Set<String> excluded) {
Set<String> seen = new HashSet<>();
Deque<Task> pending = new ArrayDeque<>(List.of(stage));
while (!pending.isEmpty()) {
Task task = pending.pop();
if (!excluded.contains(task.getPath()) && seen.add(task.getPath()) && graph.hasTask(task)) {
pending.addAll(graph.getDependencies(task));
}
}
return seen;
}
/** A folded run block broken by a blank line runs its options as commands; see the reader. */
private static List<String> foldedCommandBreaks(File workflowDirectory) {
List<String> problems = new ArrayList<>();
for (File file : workflowFiles(workflowDirectory)) {
try {
WorkflowGradleInvocations.foldedCommandBreaks(
Files.readString(file.toPath(), StandardCharsets.UTF_8))
.forEach(problem -> problems.add(file.getName() + " " + problem));
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + file, exception);
}
}
return problems;
}
private static File[] workflowFiles(File workflowDirectory) {
File[] files =
workflowDirectory.listFiles(
file -> file.getName().endsWith(".yml") || file.getName().endsWith(".yaml"));
if (files == null || files.length == 0) {
throw new GradleException(
TASK_NAME + ": no workflow files in " + workflowDirectory + "; nothing could run a stage.");
}
Arrays.sort(files);
return files;
}
/**
* Each workflow file's Gradle commands, by file name, in file order — read together, because a
* reusable workflow runs only through the workflows that call it (RR6-04-06).
*/
private static Map<String, List<WorkflowGradleInvocations.Invocation>> invocations(
File workflowDirectory) {
Map<String, String> workflows = new LinkedHashMap<>();
for (File file : workflowFiles(workflowDirectory)) {
try {
workflows.put(file.getName(), Files.readString(file.toPath(), StandardCharsets.UTF_8));
} catch (IOException exception) {
throw new UncheckedIOException("failed to read " + file, exception);
}
}
return WorkflowGradleInvocations.readAll(workflows);
}
/**
* This build's directory from the repository root, which holds {@code .github/workflows}: {@code
* src} for the main build, {@code src/platforms/optional-build} for the optional one.
*/
private static String buildDirectory(Project root, File workflowDirectory) {
File repository = workflowDirectory.getAbsoluteFile().getParentFile().getParentFile();
String relative =
repository
.toPath()
.normalize()
.relativize(root.getRootDir().getAbsoluteFile().toPath().normalize())
.toString()
.replace(File.separatorChar, '/');
return WorkflowGradleInvocations.Invocation.normalized(relative);
}
private static String taskPath(Project project, String name) {
return project == project.getRootProject() ? ":" + name : project.getPath() + ":" + name;
}
}
@@ -0,0 +1,28 @@
package dev.caskeleton.buildlogic.strictlane;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.NamedDomainObjectContainer;
public class StrictTestLaneExtension {
private final NamedDomainObjectContainer<StrictTestLaneSpec> lanes;
public StrictTestLaneExtension(NamedDomainObjectContainer<StrictTestLaneSpec> lanes) {
this.lanes = lanes;
}
public NamedDomainObjectContainer<StrictTestLaneSpec> getLanes() {
return lanes;
}
public void lane(String name, Action<? super StrictTestLaneSpec> configuration) {
// Configured before it is added, so the plugin's `lanes.all` action sees the declared source
// set (it decides whether the lane is its JVM test suite's own task).
if (lanes.findByName(name) != null) {
throw new GradleException("strict test lane '" + name + "' is declared twice");
}
StrictTestLaneSpec lane = new StrictTestLaneSpec(name);
configuration.execute(lane);
lanes.add(lane);
}
}
@@ -0,0 +1,473 @@
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()
+ "'.");
}
}
}
@@ -0,0 +1,209 @@
package dev.caskeleton.buildlogic.strictlane;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.gradle.api.Action;
import org.gradle.api.Named;
import org.gradle.api.tasks.testing.Test;
public class StrictTestLaneSpec implements Named {
private final String name;
private String tag;
private String description;
private String group;
private String sourceSet = "test";
private String maxHeapSize;
private boolean rejectSkipped;
private boolean mainStage;
private String explicitOnlyReason;
private TestLaneCategory category = TestLaneCategory.TEST;
private final List<String> requiredTests = new ArrayList<>();
private final List<String> jvmArgs = new ArrayList<>();
private final List<String> shouldRunAfter = new ArrayList<>();
private final List<String> dependsOn = new ArrayList<>();
private final List<File> inputDirectories = new ArrayList<>();
private final Map<String, String> systemProperties = new LinkedHashMap<>();
private Action<? super Test> customize;
public StrictTestLaneSpec(String name) {
this.name = Objects.requireNonNull(name, "name");
}
@Override
public String getName() {
return name;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getSourceSet() {
return sourceSet;
}
public void setSourceSet(String sourceSet) {
this.sourceSet = sourceSet;
}
public String getMaxHeapSize() {
return maxHeapSize;
}
public void setMaxHeapSize(String maxHeapSize) {
this.maxHeapSize = maxHeapSize;
}
public boolean isRejectSkipped() {
return rejectSkipped;
}
public void setRejectSkipped(boolean rejectSkipped) {
this.rejectSkipped = rejectSkipped;
}
public boolean isMainStage() {
return mainStage;
}
/**
* Runs this lane in the leaf's {@code mainCheck} instead of its {@code test}: the lane's tag is
* excluded from {@code test}. For checks that compare a leaf with documents or registries, which
* are not worth a pull request's wait (review 2026-09-24 BUILD-계획-B4-27).
*/
public void mainStage() {
mainStage = true;
}
public String getExplicitOnlyReason() {
return explicitOnlyReason;
}
/**
* Keeps this lane out of every aggregate ({@code strictTestLaneCheck}, {@code
* integrationTestLaneCheck}, ...): it runs only when named. For a lane that cannot pass without
* an input the aggregate's caller does not have — protected credentials, an external topology —
* so that the aggregate states the gap instead of failing on it (review NEW-16).
*/
public void explicitOnly(String reason) {
explicitOnlyReason = Objects.requireNonNull(reason, "reason");
}
public TestLaneCategory getCategory() {
return category;
}
public void setCategory(TestLaneCategory category) {
this.category = Objects.requireNonNull(category, "category");
}
public void test() {
category = TestLaneCategory.TEST;
}
public void integration() {
category = TestLaneCategory.INTEGRATION;
}
public void system() {
category = TestLaneCategory.SYSTEM;
}
public void architecture() {
category = TestLaneCategory.ARCHITECTURE;
}
/**
* A lane whose tests are resource or latency bounds. Besides rerunning every time and taking the
* build-wide real-server slot, it rejects skipped tests and always runs with its bounds asserted:
* the convention sets {@code performance.assertions.enabled=true}, and a build or lane that sets
* it to anything else fails before a test runs.
*/
public void performance() {
category = TestLaneCategory.PERFORMANCE;
}
public List<String> getRequiredTests() {
return List.copyOf(requiredTests);
}
public void requires(String... selectors) {
requiredTests.addAll(List.of(selectors));
}
public List<String> getJvmArgs() {
return List.copyOf(jvmArgs);
}
public void jvmArgs(String... arguments) {
jvmArgs.addAll(List.of(arguments));
}
public List<String> getShouldRunAfter() {
return List.copyOf(shouldRunAfter);
}
public void shouldRunAfter(String... taskNames) {
shouldRunAfter.addAll(List.of(taskNames));
}
public List<String> getDependsOn() {
return List.copyOf(dependsOn);
}
public void dependsOn(String... taskNames) {
dependsOn.addAll(List.of(taskNames));
}
public Map<String, String> getSystemProperties() {
return Map.copyOf(systemProperties);
}
public void systemProperty(String name, String value) {
systemProperties.put(Objects.requireNonNull(name, "name"), Objects.requireNonNull(value, "value"));
}
public List<File> getInputDirectories() {
return List.copyOf(inputDirectories);
}
public void inputDirectory(File directory) {
inputDirectories.add(Objects.requireNonNull(directory, "directory"));
}
public Action<? super Test> getCustomize() {
return customize;
}
public void setCustomize(Action<? super Test> customize) {
this.customize = customize;
}
public void customize(Action<? super Test> customize) {
this.customize = customize;
}
}
@@ -0,0 +1,214 @@
package dev.caskeleton.buildlogic.strictlane;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Which tasks a command line's {@code -x} selectors remove, matched the way Gradle matches them.
*
* <p>Gradle accepts an abbreviation wherever it accepts a task or project name: {@code -x
* grpcPerformanceT} removes {@code grpcPerformanceTest}, and {@code :g-t:gPT} a task of {@code
* :grpc-testkit}. The workflow reader compared names exactly, so an abbreviated {@code -x} — the
* form people type in a terminal and paste into a workflow — removed a lane from Gradle's plan while
* the stage check still counted it (review 2026-11-04 RR2-04-04).
*
* <p>The matching is a copy of Gradle's {@code org.gradle.util.internal.NameMatcher} (9.0): exact,
* then case-insensitive, then camel-case, then kebab-case abbreviation. It is copied rather than
* called because that class is internal API. Where Gradle would refuse the selector as ambiguous,
* every candidate counts as removed: the command cannot run, so it covers none of them.
*/
final class TaskSelectors {
private static final Pattern CAMEL_CASE_BOUNDARY =
Pattern.compile(
"((^|\\p{Punct})\\p{javaLowerCase}+)|((\\p{javaUpperCase}|\\p{Digit})\\p{javaLowerCase}*)");
private static final Pattern KEBAB_BOUNDARY =
Pattern.compile("((^|\\p{Punct})\\p{javaLowerCase}+)|(\\p{javaUpperCase}\\p{javaLowerCase}*)");
private TaskSelectors() {}
/**
* The paths of the tasks the selectors remove from a command started at the root project.
*
* @param selectors the {@code -x} values, as written
* @param tasksByProject each project's path ({@code :} for the root) and its task names
* @return the removed task paths
*/
static Set<String> excludedPaths(
List<String> selectors, Map<String, ? extends Collection<String>> tasksByProject) {
Set<String> excluded = new LinkedHashSet<>();
for (String selector : selectors) {
excluded.addAll(selected(selector, tasksByProject));
}
return excluded;
}
private static Set<String> selected(
String selector, Map<String, ? extends Collection<String>> tasksByProject) {
Set<String> paths = new LinkedHashSet<>();
if (!selector.contains(":")) {
// A bare name is matched against every task name in the build and removes the task of that
// name in every project.
Set<String> names = new TreeSet<>();
tasksByProject.values().forEach(names::addAll);
for (String name : matches(selector, names)) {
tasksByProject.forEach(
(project, tasks) -> {
if (tasks.contains(name)) {
paths.add(taskPath(project, name));
}
});
}
return paths;
}
String relative = selector.startsWith(":") ? selector.substring(1) : selector;
String[] segments = relative.split(":", -1);
Set<String> projects = Set.of(":");
for (int index = 0; index < segments.length - 1; index++) {
Set<String> next = new LinkedHashSet<>();
for (String project : projects) {
for (String child : matches(segments[index], children(project, tasksByProject.keySet()))) {
next.add(project.equals(":") ? ":" + child : project + ":" + child);
}
}
projects = next;
}
String taskName = segments[segments.length - 1];
for (String project : projects) {
Collection<String> tasks = tasksByProject.get(project);
for (String name : matches(taskName, tasks == null ? List.of() : tasks)) {
paths.add(taskPath(project, name));
}
}
return paths;
}
private static Set<String> children(String project, Set<String> projects) {
String prefix = project.equals(":") ? ":" : project + ":";
Set<String> children = new TreeSet<>();
for (String candidate : projects) {
if (candidate.startsWith(prefix) && candidate.length() > prefix.length()) {
String rest = candidate.substring(prefix.length());
if (!rest.contains(":")) {
children.add(rest);
}
}
}
return children;
}
private static String taskPath(String project, String name) {
return project.equals(":") ? ":" + name : project + ":" + name;
}
/**
* The names {@code pattern} selects among {@code items}: one when Gradle would accept it, several
* when Gradle would refuse it as ambiguous, none when nothing matches.
*/
static Set<String> matches(String pattern, Collection<String> items) {
if (items.contains(pattern)) {
return Set.of(pattern);
}
if (pattern.isEmpty()) {
return Set.of();
}
Pattern camelCase = Pattern.compile(camelCasePattern(pattern));
Pattern camelCaseIgnoringCase =
Pattern.compile(camelCasePattern(pattern), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
String kebabCasePattern = kebabCasePattern(pattern);
Pattern kebabCase = Pattern.compile(kebabCasePattern);
Pattern kebabCasePrefix = Pattern.compile(kebabCasePattern + "[\\p{javaLowerCase}\\p{Digit}-]*");
Set<String> ignoringCase = new TreeSet<>();
Set<String> camelCaseWhole = new TreeSet<>();
Set<String> camelCaseStart = new TreeSet<>();
Set<String> camelCaseStartIgnoringCase = new TreeSet<>();
Set<String> kebabCaseWhole = new TreeSet<>();
Set<String> kebabCaseStart = new TreeSet<>();
for (String candidate : items) {
if (candidate.equalsIgnoreCase(pattern)) {
ignoringCase.add(candidate);
}
if (camelCase.matcher(candidate).matches()) {
camelCaseWhole.add(candidate);
}
if (camelCase.matcher(candidate).lookingAt()) {
camelCaseStart.add(candidate);
}
if (camelCaseIgnoringCase.matcher(candidate).lookingAt()) {
camelCaseStartIgnoringCase.add(candidate);
}
if (kebabCase.matcher(candidate).matches()) {
kebabCaseWhole.add(candidate);
}
if (kebabCasePrefix.matcher(candidate).matches()) {
kebabCaseStart.add(candidate);
}
}
Set<String> matches = new TreeSet<>();
if (!ignoringCase.isEmpty()) {
matches.addAll(ignoringCase);
} else if (!camelCaseWhole.isEmpty()) {
matches.addAll(camelCaseWhole);
} else if (!camelCaseStart.isEmpty()) {
matches.addAll(camelCaseStart);
} else if (kebabCaseWhole.isEmpty() && kebabCaseStart.isEmpty()) {
matches.addAll(camelCaseStartIgnoringCase);
}
if (!kebabCaseWhole.isEmpty()) {
matches.addAll(kebabCaseWhole);
} else if (!kebabCaseStart.isEmpty()) {
matches.addAll(kebabCaseStart);
}
return matches;
}
private static String camelCasePattern(String name) {
return pattern(
name,
CAMEL_CASE_BOUNDARY,
(builder, position, part) ->
builder.append(Pattern.quote(part)).append("[\\p{javaLowerCase}]*"));
}
private static String kebabCasePattern(String name) {
return pattern(
name,
KEBAB_BOUNDARY,
(builder, position, part) -> {
if (position > 0) {
builder.append('-');
}
builder
.append(Pattern.quote(part.toLowerCase(Locale.ROOT)))
.append("[\\p{javaLowerCase}\\p{Digit}]*");
});
}
private interface PartWriter {
void write(StringBuilder builder, int position, String part);
}
private static String pattern(String name, Pattern boundary, PartWriter writer) {
Matcher matcher = boundary.matcher(name);
int position = 0;
StringBuilder builder = new StringBuilder();
while (matcher.find()) {
String prefix = name.substring(position, matcher.start());
if (!prefix.isEmpty()) {
builder.append(Pattern.quote(prefix));
}
writer.write(builder, position, matcher.group());
position = matcher.end();
}
if (position < name.length()) {
builder.append(Pattern.quote(name.substring(position)));
}
return builder.toString();
}
}
@@ -0,0 +1,9 @@
package dev.caskeleton.buildlogic.strictlane;
public enum TestLaneCategory {
TEST,
INTEGRATION,
SYSTEM,
ARCHITECTURE,
PERFORMANCE
}
@@ -0,0 +1,48 @@
package dev.caskeleton.buildlogic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ApiSurfacePolicyTest {
@Test void renderUsesJavacTypesAndStableHeader(@TempDir Path temp) throws Exception {
Path root = temp.resolve("src/main/java/app");
Files.createDirectories(root);
Files.writeString(root.resolve("Visible.java"), "package app; public strictfp class Visible {}\n");
String rendered = ApiSurfacePolicy.render(
List.of(temp.resolve("src/main/java").toFile()),
"Fixture", "Fixture public surface", List.of("Reviewed API only"),
":fixture", "updateFixtureApiSurface", "approveFixtureApiSurfaceChange");
assertTrue(rendered.contains("# Fixture public surface"));
assertTrue(rendered.contains("# Reviewed API only"));
assertTrue(rendered.contains("app.Visible"));
assertEquals(1, ApiSurfacePolicy.countTypes(rendered));
}
@Test void verifyReportsAddedAndRemovedTypes(@TempDir Path temp) throws Exception {
File baseline = temp.resolve("surface.txt").toFile();
Files.writeString(baseline.toPath(), "# baseline\napp.Old\n");
IllegalStateException failure = assertThrows(IllegalStateException.class, () ->
ApiSurfacePolicy.verify("verifyFixtureApiSurface", "updateFixtureApiSurface", ":fixture",
"approveFixtureApiSurfaceChange", baseline, "# rendered\napp.New\n"));
assertTrue(failure.getMessage().contains("added:"));
assertTrue(failure.getMessage().contains("app.New"));
assertTrue(failure.getMessage().contains("removed:"));
assertTrue(failure.getMessage().contains("app.Old"));
}
@Test void growthRequiresSeparateCeilingApproval() {
IllegalStateException failure = assertThrows(IllegalStateException.class, () ->
ApiSurfacePolicy.requireNoUnapprovedGrowth(
"updateFixtureApiSurface", ":fixture", "approveFixtureApiSurfaceChange",
"raiseFixtureApiSurfaceCeiling", 1, "# rendered\napp.One\napp.Two\n", false));
assertTrue(failure.getMessage().contains("grow from 1 to 2 types"));
}
}
@@ -0,0 +1,191 @@
package dev.caskeleton.buildlogic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ModuleRegistryTest {
@TempDir Path root;
@BeforeEach
void setUp() throws Exception {
Files.createDirectories(root.resolve("src/alpha"));
Files.createDirectories(root.resolve("src/beta"));
}
@Test
void wellFormedRegistryParses() {
ModuleRegistry parsed = read(valid());
assertEquals(2, parsed.modules().size());
assertTrue(parsed.byId("app-bootstrap").sourceDirectory().isDirectory());
}
@Test
void duplicateIdIsRefused() {
IllegalStateException failure =
assertThrows(
IllegalStateException.class,
() ->
read(
registry(
entry("app-bootstrap", ":app-bootstrap", "src/alpha"),
entry("example-app", ":example-app", "src/beta"),
entry("app-bootstrap", ":other", "src/alpha"))));
assertTrue(failure.getMessage().contains("duplicate module id"), failure.getMessage());
}
@Test
void aliasedSourceDirectoryIsRefused() {
IllegalStateException failure =
assertThrows(
IllegalStateException.class,
() ->
read(
registry(
entry("app-bootstrap", ":app-bootstrap", "src/alpha"),
entry("example-app", ":example-app", "src/beta"),
entry("aliased", ":aliased", "src/beta/../alpha"))));
assertTrue(failure.getMessage().contains("duplicate or aliased"), failure.getMessage());
}
@Test
void architectureEdgesRemainData() {
ModuleRegistry parsed =
read(
registry(
entry(
"app-bootstrap",
":app-bootstrap",
"src/alpha",
"[\"example-app\",\"unknown\",\"app-bootstrap\"]"),
entry("example-app", ":example-app", "src/beta")));
assertEquals(
List.of("example-app", "unknown", "app-bootstrap"),
parsed.byId("app-bootstrap").allowedDependencies());
}
@Test
void missingRequiredFieldIsRefused() {
String json =
"""
{"modules":[
{"id":"app-bootstrap","gradle_path":":app-bootstrap","source_path":"src/alpha"},
%s]}
"""
.formatted(entry("example-app", ":example-app", "src/beta"));
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json));
assertTrue(failure.getMessage().contains("allowed_dependencies"), failure.getMessage());
}
@Test
void everyModuleBelongsToTheMainBuild() throws Exception {
ModuleRegistry parsed = read(registry(entry("app-bootstrap", ":app-bootstrap", "src/alpha")));
assertEquals("main", parsed.byId("app-bootstrap").buildName());
assertEquals(List.of("app-bootstrap"), parsed.modulesForBuild("main").stream().map(ModuleRegistry.Module::id).toList());
}
@Test
void aBuildFieldIsRejectedBecauseNoOtherBuildIncludesOrChecksTheModule() throws Exception {
// The optional gRPC build was the only other build; it moved to its own repository on
// 2026-11-08. 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.
Files.createDirectories(root.resolve("src/grpc/grpc-client"));
String json =
registry(
entry("app-bootstrap", ":app-bootstrap", "src/alpha"),
"""
{"id":"grpc-client","gradle_path":":grpc:grpc-client","source_path":"src/grpc/grpc-client",
"allowed_dependencies":[],"build":"optional-grpc"}
""");
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json));
assertTrue(failure.getMessage().contains("'grpc-client'"), failure.getMessage());
assertTrue(failure.getMessage().contains("'build'"), failure.getMessage());
}
@Test
void aBlankBuildFieldIsRefusedToo() {
String json =
"""
{"modules":[
{"id":"app-bootstrap","gradle_path":":app-bootstrap","source_path":"src/alpha",
"allowed_dependencies":[],"build":" "}]}
""";
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json));
assertTrue(failure.getMessage().contains("'build' field"), failure.getMessage());
}
@Test
@DisplayName("registry에 없는 디렉터리의 build 스크립트는 찾아내고, 등록된 leaf·루트·다른 빌드·build 산출물은 무시한다")
void buildScriptsOutsideTheRegistryAreReported() throws Exception {
// given
Path gradleRoot = root.resolve("src");
Files.writeString(gradleRoot.resolve("build.gradle"), "");
Files.writeString(gradleRoot.resolve("alpha/build.gradle"), "");
Files.writeString(gradleRoot.resolve("beta/build.gradle"), "");
Files.createDirectories(gradleRoot.resolve("adapter/gamma"));
Files.writeString(gradleRoot.resolve("adapter/gamma/build.gradle"), "");
Files.createDirectories(gradleRoot.resolve("other-build"));
Files.writeString(gradleRoot.resolve("other-build/settings.gradle"), "");
Files.writeString(gradleRoot.resolve("other-build/build.gradle"), "");
Files.createDirectories(gradleRoot.resolve("alpha/build/tmp/fixture"));
Files.writeString(gradleRoot.resolve("alpha/build/tmp/fixture/build.gradle"), "");
Files.createDirectories(gradleRoot.resolve("alpha/src/test/resources/fixture"));
Files.writeString(gradleRoot.resolve("alpha/src/test/resources/fixture/build.gradle"), "");
ModuleRegistry registry = read(valid());
// when
List<String> unregistered = registry.unregisteredBuildScripts(gradleRoot.toFile());
// then
assertEquals(List.of("adapter/gamma/build.gradle"), unregistered);
}
private File write(String json) {
try {
Path file = root.resolve("modules.json");
Files.writeString(file, json);
return file.toFile();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
private ModuleRegistry read(String json) {
return ModuleRegistry.read(write(json), root.toFile());
}
private String valid() {
return registry(
entry("app-bootstrap", ":app-bootstrap", "src/alpha"),
entry("example-app", ":example-app", "src/beta"));
}
private static String entry(String id, String path, String source) {
return entry(id, path, source, "[]");
}
private static String entry(String id, String path, String source, String deps) {
return "{\"id\":\""
+ id
+ "\",\"gradle_path\":\""
+ path
+ "\",\"source_path\":\""
+ source
+ "\",\"allowed_dependencies\":"
+ deps
+ "}";
}
private static String registry(String... entries) {
return "{\"modules\":[" + String.join(",", entries) + "]}";
}
}
@@ -0,0 +1,39 @@
package dev.caskeleton.buildlogic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
class RequiredTestExecutionTest {
@Test void exactMatchCounts() {
assertEquals(List.of(), RequiredTestExecution.absent(List.of("com.example.FooTest"), List.of("com.example.FooTest")));
}
@Test void nestedClassCountsForOuterClass() {
assertEquals(List.of(), RequiredTestExecution.absent(List.of("com.example.FooTest"), List.of("com.example.FooTest$WhenEmpty")));
}
@Test void parameterizedInvocationCountsForMethod() {
assertEquals(List.of(), RequiredTestExecution.absent(List.of("com.example.FooTest.rejects"), List.of("com.example.FooTest.rejects(String)[1]")));
assertEquals(List.of(), RequiredTestExecution.absent(List.of("com.example.FooTest.rejects"), List.of("com.example.FooTest.rejects[2]")));
}
@Test void differentPrefixNameIsNotMatch() {
assertEquals(List.of("com.example.FooTest"), RequiredTestExecution.absent(List.of("com.example.FooTest"), List.of("com.example.FooTestHelper")));
}
@Test void reportsEveryAbsentSelector() {
assertEquals(List.of("com.example.A", "com.example.C"), RequiredTestExecution.absent(List.of("com.example.A", "com.example.B", "com.example.C"), List.of("com.example.B")));
}
@Test void handlesEmptyInputs() {
assertEquals(List.of(), RequiredTestExecution.absent(List.of(), List.of("com.example.A")));
assertEquals(List.of(), RequiredTestExecution.absent(null, List.of("com.example.A")));
assertEquals(List.of("com.example.A"), RequiredTestExecution.absent(List.of("com.example.A"), List.of()));
assertEquals(List.of("com.example.A"), RequiredTestExecution.absent(List.of("com.example.A"), null));
}
@Test void satisfiesIsSinglePredicate() {
assertTrue(RequiredTestExecution.satisfies("com.example.FooTest$Inner", "com.example.FooTest"));
assertTrue(RequiredTestExecution.satisfies("com.example.FooTest.bar(int)", "com.example.FooTest.bar"));
assertFalse(RequiredTestExecution.satisfies(null, "com.example.FooTest"));
assertFalse(RequiredTestExecution.satisfies("com.example.FooTest", null));
}
}
@@ -0,0 +1,199 @@
package dev.caskeleton.buildlogic.apisurface;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Files;
import java.nio.file.Path;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ApiSurfaceConventionTest {
@TempDir Path projectDir;
@BeforeEach
void setUp() throws Exception {
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name='fixture'\n");
Path source = projectDir.resolve("src/main/java/app");
Files.createDirectories(source);
Files.writeString(source.resolve("Visible.java"), "package app;\npublic final class Visible {}\n");
writeConfiguredBuild("src/main/java");
}
@Test
void documentedFlagApprovesUpdateAndVerifyIsReadOnly() throws Exception {
BuildResult updated =
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
assertTrue(updated.getOutput().contains("wrote"), updated.getOutput());
assertTrue(Files.readString(projectDir.resolve("surface.txt")).contains("app.Visible"));
BuildResult verify =
runner("verifyFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").buildAndFail();
assertTrue(verify.getOutput().contains("read-only"), verify.getOutput());
}
@Test
void unapprovedAndMisnamedApprovalFlagsAreRefused() {
BuildResult noFlag = runner("updateFixtureApiSurface").buildAndFail();
assertTrue(noFlag.getOutput().contains("requires -PapproveFixtureApiSurfaceChange"));
BuildResult wrongFlag =
runner("updateFixtureApiSurface", "-PapprovenullApiSurfaceChange").buildAndFail();
assertTrue(wrongFlag.getOutput().contains("requires -PapproveFixtureApiSurfaceChange"));
}
@Test
void grownSurfaceFailsAndNamesAddedType() throws Exception {
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
Files.writeString(
projectDir.resolve("src/main/java/app/Added.java"),
"package app;\npublic interface Added {}\n");
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
assertTrue(result.getOutput().contains("app.Added"), result.getOutput());
}
@Test
void parserHandlesStrictfpAndIgnoresCommentedType() throws Exception {
Files.writeString(
projectDir.resolve("src/main/java/app/Strict.java"),
"package app;\npublic strictfp class Strict {}\n");
Files.writeString(
projectDir.resolve("src/main/java/app/Commented.java"),
"package app;\n/*\npublic class Ghost {}\n*/\npublic final class Commented {}\n");
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
String surface = Files.readString(projectDir.resolve("surface.txt"));
assertTrue(surface.contains("app.Strict"));
assertTrue(surface.contains("app.Commented"));
assertFalse(surface.contains("app.Ghost"));
}
@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());
writeConfiguredBuild("src/main/java");
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());
}
@Test
void undeclaredSurfaceRegistersNoApiSurfaceTasks() throws Exception {
Files.writeString(
projectDir.resolve("build.gradle"),
"""
plugins {
id 'java'
id 'ca.api-surface'
}
""");
BuildResult result = runner("tasks", "--group=verification").build();
assertFalse(result.getOutput().contains("ApiSurface"), result.getOutput());
}
@Test
void theLeafCheckRunsTheSurfaceVerification() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
// when
BuildResult result = runner("check", "--dry-run").build();
// then
assertTrue(result.getOutput().contains(":verifyFixtureApiSurface"), result.getOutput());
}
@Test
void anAdopterImportOutsideTheAdopterBaselineFailsTheVerification() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
writeAdopter("package consumer;\nimport app.Visible;\npublic final class Consumer {}\n");
Files.writeString(projectDir.resolve("adopters.txt"), "# reviewed adopter surface\n");
// when
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
// then
assertTrue(result.getOutput().contains("Consumer.java: app.Visible"), result.getOutput());
}
@Test
void anAdopterImportTheAdopterBaselineListsPasses() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
writeAdopter("package consumer;\nimport app.Visible;\npublic final class Consumer {}\n");
Files.writeString(projectDir.resolve("adopters.txt"), "app.Visible\n");
// when
BuildResult result = runner("verifyFixtureApiSurface").build();
// then
assertTrue(result.getOutput().contains("OK"), result.getOutput());
}
@Test
void anAdopterBaselineEntryTheSurfaceNoLongerHasFailsTheVerification() throws Exception {
// given
runner("updateFixtureApiSurface", "-PapproveFixtureApiSurfaceChange").build();
writeAdopter("package consumer;\npublic final class Consumer {}\n");
Files.writeString(projectDir.resolve("adopters.txt"), "app.Gone\n");
// when
BuildResult result = runner("verifyFixtureApiSurface").buildAndFail();
// then
assertTrue(result.getOutput().contains("app.Gone"), result.getOutput());
}
private void writeAdopter(String source) throws Exception {
Path adopter = projectDir.resolve("adopter/src/consumer");
Files.createDirectories(adopter);
Files.writeString(adopter.resolve("Consumer.java"), source);
Files.writeString(
projectDir.resolve("build.gradle"),
"""
plugins {
id 'java'
id 'ca.api-surface'
}
apiSurface {
label = 'Fixture'
baseline = file('surface.txt')
description = 'The fixture leaf public surface.'
adopterBaseline = file('adopters.txt')
adopterSources = fileTree('adopter/src') { include '**/*.java' }
}
""");
}
private void writeConfiguredBuild(String sourceRoot) throws Exception {
Files.writeString(
projectDir.resolve("build.gradle"),
"""
plugins {
id 'java'
id 'ca.api-surface'
}
apiSurface {
label = 'Fixture'
sourceRoot = '%s'
baseline = file('surface.txt')
description = 'The fixture leaf public surface.'
}
""".formatted(sourceRoot));
}
private GradleRunner runner(String... args) {
return GradleRunner.create()
.withProjectDir(projectDir.toFile())
.withPluginClasspath()
.withArguments(args);
}
}
@@ -0,0 +1,182 @@
package dev.caskeleton.buildlogic.architecture;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class CleanArchitectureResolvedClasspathFunctionalTest {
@Test
void transitiveApiProjectMustBeRegisteredForTheCompileVisibleConsumer(@TempDir Path temporaryRoot)
throws IOException {
Path project = fixture(temporaryRoot, false);
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail();
assertThat(result.getOutput())
.contains("Module ':c' has forbidden project dependencies [a]")
.contains(
"Direct and compile-visible production project edges must be explicitly registered");
}
@Test
void aSecondCompositionRootIsGovernedByTheSameDependencyPolicy(
@TempDir Path temporaryRoot) throws IOException {
Path repository = temporaryRoot.resolve("repository");
Path project = repository.resolve("src");
Files.createDirectories(project.resolve("config/architecture"));
Files.createDirectories(project.resolve("a"));
Files.createDirectories(project.resolve("example-app"));
Files.writeString(
project.resolve("settings.gradle"),
"""
rootProject.name = 'main'
include 'a', 'example-app'
""",
UTF_8);
Files.writeString(
project.resolve("build.gradle"),
"""
plugins { id 'ca.architecture' }
subprojects { apply plugin: 'java-library' }
project(':example-app') {
dependencies { implementation project(':a') }
}
""",
UTF_8);
Files.writeString(
project.resolve("config/architecture/modules.json"),
"""
{
"modules": [
{
"id": "a",
"gradle_path": ":a",
"source_path": "a",
"allowed_dependencies": []
},
{
"id": "example-app",
"gradle_path": ":example-app",
"source_path": "example-app",
"allowed_dependencies": []
}
]
}
""",
UTF_8);
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail();
assertThat(result.getOutput())
.contains("Module ':example-app' has forbidden project dependencies [a]");
}
@Test
void explicitlyRegisteredCompileVisibleTransitiveProjectPasses(@TempDir Path temporaryRoot)
throws IOException {
Path project = fixture(temporaryRoot, true);
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").build();
assertThat(result.getOutput()).contains("BUILD SUCCESSFUL");
}
@Test
@DisplayName("registry에 등록하지 않은 leaf 디렉터리에 build 스크립트가 있으면 방향 게이트가 그 경로로 실패한다")
void aLeafDirectoryMissingFromTheRegistryFailsTheGate(@TempDir Path temporaryRoot)
throws IOException {
// given
Path project = fixture(temporaryRoot, true);
Files.createDirectories(project.resolve("d"));
Files.writeString(project.resolve("d/build.gradle"), "plugins { id 'java' }\n", UTF_8);
// when
BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail();
// then
assertThat(result.getOutput()).contains("d/build.gradle").contains("no registry entry");
}
private static Path fixture(Path temporaryRoot, boolean allowTransitiveA) throws IOException {
Path repository = temporaryRoot.resolve("repository");
Path project = repository.resolve("src");
Files.createDirectories(project.resolve("config/architecture"));
for (String module : new String[] {"a", "b", "c"}) {
Files.createDirectories(project.resolve(module));
}
Files.writeString(
project.resolve("settings.gradle"),
"""
rootProject.name = 'main'
include 'a', 'b', 'c'
""",
UTF_8);
Files.writeString(
project.resolve("build.gradle"),
"""
plugins { id 'ca.architecture' }
subprojects { apply plugin: 'java-library' }
project(':b') {
dependencies { api project(':a') }
}
project(':c') {
dependencies { implementation project(':b') }
}
""",
UTF_8);
String cAllowed = allowTransitiveA ? "[\"b\", \"a\"]" : "[\"b\"]";
Files.writeString(
project.resolve("config/architecture/modules.json"),
"""
{
"modules": [
{
"id": "a",
"gradle_path": ":a",
"source_path": "a",
"allowed_dependencies": []
},
{
"id": "b",
"gradle_path": ":b",
"source_path": "b",
"allowed_dependencies": ["a"]
},
{
"id": "c",
"gradle_path": ":c",
"source_path": "c",
"allowed_dependencies": %s
}
]
}
"""
.formatted(cAllowed),
UTF_8);
return project;
}
private static GradleRunner runner(Path project, String... arguments) {
String[] fullArguments = new String[arguments.length + 2];
fullArguments[0] = "--console=plain";
fullArguments[1] = "--stacktrace";
System.arraycopy(arguments, 0, fullArguments, 2, arguments.length);
return GradleRunner.create()
.withProjectDir(project.toFile())
.withPluginClasspath()
.withArguments(fullArguments);
}
}
@@ -0,0 +1,122 @@
package dev.caskeleton.buildlogic.architecture;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class VerifyNoIgnoredSourcePackagesFunctionalTest {
@Test
void sourceInAnIgnoredPackageOfAnAuxiliarySourceSetFailsTheGate(@TempDir Path temporaryRoot)
throws IOException {
// given
Path project = fixture(temporaryRoot, "a");
source(project, "a/src/main/java/example/Ok.java");
source(project, "a/src/integrationTest/java/example/bin/Ignored.java");
// when
BuildResult result = runner(project).buildAndFail();
// then
assertThat(result.getOutput())
.contains("Ignored.java: package segment 'bin' collides with a build output directory name");
}
@Test
void sourceInAnIgnoredPackageOfAnyLeafFailsTheGate(@TempDir Path temporaryRoot)
throws IOException {
// given
Path project = fixture(temporaryRoot, "example-app");
source(project, "example-app/src/main/java/example/Ok.java");
source(project, "example-app/src/main/java/example/build/Ignored.java");
// when
BuildResult result = runner(project).buildAndFail();
// then
assertThat(result.getOutput())
.contains(
"Ignored.java: package segment 'build' collides with a build output directory name");
}
@Test
void gitFailingInsideACheckoutFailsTheGateInsteadOfPassing(@TempDir Path temporaryRoot)
throws IOException {
// given
Path project = fixture(temporaryRoot, "a");
source(project, "a/src/main/java/example/Ok.java");
Files.writeString(
project.getParent().resolve(".git"),
"gitdir: " + temporaryRoot.resolve("missing-git-dir") + "\n",
UTF_8);
// when
BuildResult result = runner(project).buildAndFail();
// then
assertThat(result.getOutput())
.contains("verifyNoIgnoredSourcePackages: `git check-ignore` exited 128");
}
/** One registered leaf with an extra {@code integrationTest} source set, under {@code src/}. */
private static Path fixture(Path temporaryRoot, String leaf) throws IOException {
Path project = temporaryRoot.resolve("repository").resolve("src");
Files.createDirectories(project.resolve("config/architecture"));
Files.createDirectories(project.resolve(leaf));
Files.writeString(
project.resolve("settings.gradle"),
"""
rootProject.name = 'main'
include '%s'
"""
.formatted(leaf),
UTF_8);
Files.writeString(
project.resolve("build.gradle"),
"""
plugins { id 'ca.architecture' }
subprojects {
apply plugin: 'java-library'
sourceSets { integrationTest }
}
""",
UTF_8);
Files.writeString(
project.resolve("config/architecture/modules.json"),
"""
{
"modules": [
{
"id": "%1$s",
"gradle_path": ":%1$s",
"source_path": "%1$s",
"allowed_dependencies": []
}
]
}
"""
.formatted(leaf),
UTF_8);
return project;
}
private static void source(Path project, String relativePath) throws IOException {
Path file = project.resolve(relativePath);
Files.createDirectories(file.getParent());
Files.writeString(file, "package example;\n", UTF_8);
}
private static GradleRunner runner(Path project) {
return GradleRunner.create()
.withProjectDir(project.toFile())
.withPluginClasspath()
.withArguments("--console=plain", "--stacktrace", "verifyNoIgnoredSourcePackages");
}
}
@@ -0,0 +1,158 @@
package dev.caskeleton.buildlogic.convention;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Files;
import java.nio.file.Path;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class PlatformModuleConventionTest {
@TempDir Path projectDir;
@BeforeEach
void setUp() throws Exception {
Files.createDirectories(projectDir.resolve("gradle"));
writeCatalog();
// java-conventions refuses a build without the container image catalog (review 2026-11-01
// 08-04); a fixture build that starts no container still has to carry one, even empty.
Files.createDirectories(projectDir.resolve("config/testing"));
Files.writeString(projectDir.resolve("config/testing/container-images.properties"), "");
// java-conventions takes the Maven group from this property and refuses a build without it.
Files.writeString(projectDir.resolve("gradle.properties"), "libraryGroup=org.example.fixture\n");
Files.writeString(
projectDir.resolve("settings.gradle"),
"""
dependencyResolutionManagement { repositories { mavenCentral() } }
rootProject.name = 'fixture'
""");
}
@Test
void platformModuleProvidesJavaLibrary() throws Exception {
buildFile(
"""
plugins { id 'ca.platform-module' }
tasks.register('reportApiConfiguration') {
boolean present = configurations.findByName('api') != null
doLast { logger.lifecycle('api-configuration-present=' + present) }
}
""");
BuildResult result = runner("reportApiConfiguration").build();
assertTrue(result.getOutput().contains("api-configuration-present=true"), result.getOutput());
}
@Test
void aLeafCarriesTheReleaseVersionAndNamesTheRevisionSeparately() throws Exception {
// given
buildFile(
"""
plugins { id 'ca.platform-module' }
tasks.register('reportRelease') {
String version = project.version.toString()
String revision = project.sourceRevision
doLast { logger.lifecycle("version=" + version + " revision=" + revision) }
}
""");
// when
BuildResult result =
runner(
"reportRelease",
"-PreleaseVersion=1.2.3",
"-PgitRevision=0123456789ABCDEF0123456789abcdef01234567")
.build();
// then
assertTrue(
result.getOutput().contains("version=1.2.3 revision=0123456789ab"), result.getOutput());
}
@Test
void aLeafWithoutACommitIdIsASnapshotOfAnUnknownRevision() throws Exception {
// given
buildFile(
"""
plugins { id 'ca.platform-module' }
tasks.register('reportRelease') {
String version = project.version.toString()
String revision = project.sourceRevision
doLast { logger.lifecycle("version=" + version + " revision=" + revision) }
}
""");
// when
BuildResult result = runner("reportRelease", "-PgitRevision=not-a-commit").build();
// then
assertTrue(
result.getOutput().contains("version=0.0.1-SNAPSHOT revision=unknown"), result.getOutput());
}
@Test
void aReleaseVersionWithASuffixIsRefused() throws Exception {
// given
buildFile("plugins { id 'ca.platform-module' }\n");
// when
BuildResult result = runner("tasks", "-PreleaseVersion=v1.2.3-rc1").buildAndFail();
// then
assertTrue(
result.getOutput().contains("releaseVersion must be MAJOR.MINOR.PATCH"), result.getOutput());
}
@Test
void pinnedCatalogLibrariesAreManagedAndOthersAreNot() throws Exception {
// given: the fixture catalog carries `pinned-fixture` and `unpinned-fixture`. The project-wide
// managed versions are the ones Spring dependency management applies to every configuration,
// Checkstyle's and Error Prone's included.
buildFile(
"""
plugins { id 'ca.platform-module' }
tasks.register('reportPinned') {
String pinned = dependencyManagement.managedVersions['org.example:pinned-fixture']
String unpinned = dependencyManagement.managedVersions['org.example:unpinned-fixture']
doLast { logger.lifecycle('pinned=' + pinned + ' unpinned=' + unpinned) }
}
""");
// when
BuildResult result = runner("reportPinned").build();
// then
assertTrue(result.getOutput().contains("pinned=2.0.1 unpinned=null"), result.getOutput());
}
private void writeCatalog() throws Exception {
Files.writeString(
projectDir.resolve("gradle/libs.versions.toml"),
"""
[versions]
springBoot = "4.0.8"
googleJavaFormat = "1.35.0"
checkstyle = "13.5.0"
spotbugs = "4.10.2"
findsecbugs = "1.14.0"
errorprone = "2.49.0"
[libraries]
pinned-fixture = { module = "org.example:pinned-fixture", version = "2.0.1" }
unpinned-fixture = { module = "org.example:unpinned-fixture", version = "1.0.0" }
""");
}
private void buildFile(String body) throws Exception {
Files.writeString(projectDir.resolve("build.gradle"), body);
}
private GradleRunner runner(String... args) {
return GradleRunner.create()
.withProjectDir(projectDir.toFile())
.withPluginClasspath()
.withArguments(args);
}
}
@@ -0,0 +1,41 @@
package dev.caskeleton.buildlogic.publishing;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class SigningKeysTest {
private static final String ARMOURED =
"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlQdGBGrv1SYBEADGgq8C\n=abcd\n"
+ "-----END PGP PRIVATE KEY BLOCK-----\n";
@Test
@DisplayName("armour 그대로인 키는 바꾸지 않는다")
void anArmouredKeyIsUsedAsItIs() {
assertThat(SigningKeys.armoured(ARMOURED)).isEqualTo(ARMOURED);
}
@Test
@DisplayName("armour 파일을 base64로 감싼 값은 풀어서 armour로 쓴다")
void aBase64WrappedArmouredKeyIsUnwrapped() {
String wrapped = Base64.getEncoder().encodeToString(ARMOURED.getBytes(StandardCharsets.UTF_8));
assertThat(SigningKeys.armoured(wrapped)).isEqualTo(ARMOURED);
assertThat(SigningKeys.armoured(wrapped.substring(0, 40) + "\n" + wrapped.substring(40)))
.isEqualTo(ARMOURED);
}
@Test
@DisplayName("지문이나 armour가 아닌 base64는 그대로 두어 서명이 원래 오류로 실패하게 한다")
void anythingElseIsLeftAlone() {
String fingerprint = "92646CEAFE816CF8B9C249F0A1C936D7F791F8AB";
String otherBase64 = Base64.getEncoder().encodeToString("not a key".getBytes(StandardCharsets.UTF_8));
assertThat(SigningKeys.armoured(fingerprint)).isEqualTo(fingerprint);
assertThat(SigningKeys.armoured(otherBase64)).isEqualTo(otherBase64);
assertThat(SigningKeys.armoured("")).isEmpty();
}
}
@@ -0,0 +1,162 @@
package dev.caskeleton.buildlogic.strictlane;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Holds the workflow reader's copy of Gradle's command-line options to the Gradle that runs this
* build — the distribution the workflows' {@code ./gradlew} starts (review 2026-11-05 RR6-04-01/02).
*
* <p>It runs that distribution's own launcher ({@code bin/gradle}) rather than TestKit: {@code
* --help}, {@code --version}, {@code --status} and {@code --stop} are the launcher's options, and a
* workflow step runs the launcher. An upgrade that adds an option (9.2's {@code --task-graph}) fails
* the first test until the reader is told whether the option takes a value and whether Gradle then
* runs any task.
*/
class GradleCommandLineTest {
/**
* Options the reader reads as ending without a task that this test does not run: {@code --stop}
* stops every daemon of this Gradle version in the user home it is given, and {@code --foreground}
* runs a daemon until it is idle. Gradle's {@code BuildActionsFactory} returns a daemon action, not
* a build, for both.
*/
private static final Set<String> NOT_RUN_HERE = Set.of("stop", "foreground");
@TempDir Path temp;
private Path project;
@BeforeEach
void setUp() throws IOException {
project = temp.resolve("project");
Files.createDirectories(project);
Files.writeString(project.resolve("settings.gradle"), "rootProject.name = 'probe'\n");
Files.writeString(
project.resolve("build.gradle"),
"""
tasks.register('ci') {
def marker = file('ci-ran')
doLast { marker.text = 'ran' }
}
""");
}
@Test
@DisplayName("판독기의 Gradle 옵션 표는 이 빌드를 돌리는 Gradle의 --help가 보이는 옵션과 정확히 같다")
void theReadersOptionTableNamesExactlyTheOptionsTheRunningGradleLists() throws Exception {
// when
Run help = gradle("--help");
// then
assertThat(help.exitCode()).as(help.output()).isZero();
assertThat(optionNames(help.output()))
.as("the options of the Gradle in %s", gradleHome())
.containsExactlyInAnyOrderElementsOf(WorkflowGradleInvocations.gradleOptionNames());
}
@Test
@DisplayName("판독기가 작업 없이 끝난다고 읽는 옵션을 붙이면 Gradle은 성공으로 끝나고 작업을 실행하지 않는다")
void gradleEndsWithoutRunningTheTaskWhenGivenAnOptionTheReaderReadsAsRunningNoTask()
throws Exception {
// given
List<String> options = new ArrayList<>();
for (String name : WorkflowGradleInvocations.optionsThatRunNoTask()) {
if (!NOT_RUN_HERE.contains(name)) {
options.add(name.length() == 1 ? "-" + name : "--" + name);
}
}
options.add("-qv");
// when
Map<String, Run> runs = new LinkedHashMap<>();
for (String option : options) {
runs.put(option, gradle(":ci", option));
}
// then
assertThat(options).contains("-v", "--version", "-h", "-?", "--help", "--status");
runs.forEach(
(option, run) -> {
assertThat(run.exitCode()).as(option + "\n" + run.output()).isZero();
assertThat(project.resolve("ci-ran")).as(option).doesNotExist();
});
}
@Test
@DisplayName("버전을 찍고 계속하는 -V를 붙이면 Gradle은 작업을 실행하므로, 위 검사는 실행을 알아볼 수 있다")
void gradleRunsTheTaskWhenGivenShowVersionWhichContinues() throws Exception {
// when
Run run = gradle(":ci", "-V");
// then
assertThat(run.exitCode()).as(run.output()).isZero();
assertThat(project.resolve("ci-ran")).exists();
}
/** The option names a {@code --help} lists, without dashes; {@code --} itself is not an option. */
private static Set<String> optionNames(String help) {
Set<String> names = new LinkedHashSet<>();
for (String line : help.lines().toList()) {
if (!line.startsWith("-")) {
continue;
}
for (String spelling : line.split("\\s{2,}", 2)[0].split(",\\s*")) {
String name = spelling.strip().replaceFirst("^-+", "");
if (!name.isEmpty()) {
names.add(name);
}
}
}
return names;
}
private record Run(int exitCode, String output) {}
/** Runs the launcher of this build's Gradle on the probe project, isolated from every daemon. */
private Run gradle(String... arguments) throws IOException, InterruptedException {
List<String> command = new ArrayList<>();
boolean windows = System.getProperty("os.name").startsWith("Windows");
command.add(gradleHome().resolve(windows ? "bin/gradle.bat" : "bin/gradle").toString());
command.addAll(
List.of(
"--no-daemon",
"--gradle-user-home",
temp.resolve("gradle-user-home").toString(),
"--project-dir",
project.toString()));
command.addAll(List.of(arguments));
Path output = Files.createTempFile(temp, "gradle", ".log");
ProcessBuilder builder =
new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(output.toFile());
builder.environment().put("JAVA_HOME", System.getProperty("java.home"));
builder.environment().remove("GRADLE_OPTS");
Process process = builder.start();
if (!process.waitFor(5, TimeUnit.MINUTES)) {
process.destroyForcibly();
throw new IllegalStateException("gradle " + String.join(" ", arguments) + " did not end");
}
return new Run(process.exitValue(), Files.readString(output, StandardCharsets.UTF_8));
}
private static Path gradleHome() {
String home = System.getProperty("ca.gradle.home");
assertThat(home)
.as("build-logic's test task passes the running Gradle's home as ca.gradle.home")
.isNotBlank();
return Path.of(home);
}
}
@@ -0,0 +1,783 @@
package dev.caskeleton.buildlogic.strictlane;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.nio.file.Files;
import java.nio.file.Path;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* A two-project build: a root that declares stages, and a leaf with strict lanes. The workflows
* live where the real repository keeps them, one directory above the Gradle root.
*/
class StrictLaneStagesFunctionalTest {
private static final String EXECUTING_WORKFLOW =
"""
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci --stacktrace
- working-directory: src
run: ./gradlew :integrationCheck --continue --stacktrace
""";
@TempDir Path repository;
private Path gradleRoot;
@BeforeEach
void setUp() throws Exception {
gradleRoot = repository.resolve("src");
Files.createDirectories(gradleRoot.resolve("leaf/src/test/java"));
Files.createDirectories(repository.resolve(".github/workflows"));
Files.writeString(
gradleRoot.resolve("settings.gradle"), "rootProject.name = 'fixture'\ninclude 'leaf'\n");
Files.writeString(
gradleRoot.resolve("build.gradle"),
"""
plugins { id 'ca.strict-lane-stages' }
tasks.register('ci') { dependsOn ':leaf:check' }
tasks.register('integrationCheck') { dependsOn ':leaf:integrationTestLaneCheck' }
strictLaneStages {
stage ':ci', ':integrationCheck'
workflowDirectory = layout.projectDirectory.dir('../.github/workflows')
}
""");
Files.writeString(
gradleRoot.resolve("leaf/src/test/java/LaneTest.java"),
"""
class LaneTest {}
""");
}
@Test
@DisplayName("모든 lane이 workflow가 실행하는 단계에 들어 있으면 통과한다")
void passesWhenEveryLaneIsInAnExecutedStage() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(EXECUTING_WORKFLOW);
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").build();
// then
assertThat(result.getOutput()).contains("every strict lane is in an executed stage");
}
@Test
@DisplayName("어느 단계 집계에도 들지 않는 lane이 있으면 그 lane 이름으로 실패한다")
void failsNamingALaneThatNoStageReaches() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
lane('loadLane') { performance(); tag = 'load'; description = 'Load and shutdown.' }
""");
workflow(EXECUTING_WORKFLOW);
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("strict lane :leaf:loadLane is in no executed stage")
.doesNotContain("strict lane :leaf:databaseLane");
}
@Test
@DisplayName("단계를 workflow가 --dry-run으로만 부르면 그 단계와 그 단계에만 있는 lane을 함께 보고하고 실패한다")
void failsWhenAStageIsOnlyDryRun() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: ./gradlew :ci --stacktrace
- run: |
for gate in ci integrationCheck; do
./gradlew "${gate}" --dry-run
done
./gradlew integrationCheck --dry-run
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("strict lane :leaf:databaseLane is in no executed stage");
}
@Test
@DisplayName("explicitOnly lane은 이유가 코드에 있으므로 단계 밖에 있어도 통과한다")
void explicitOnlyLaneIsExempt() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
lane('sandboxLane') {
integration(); tag = 'sandbox'; description = 'Protected sandbox.'
explicitOnly 'it needs the protected sandbox credentials'
}
""");
workflow(EXECUTING_WORKFLOW);
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").build();
// then
assertThat(result.getOutput()).contains("every strict lane is in an executed stage");
}
@Test
@DisplayName("--dry-run 없이 부르면 모든 단계를 실행하게 되므로 시작 전에 거절한다")
void refusesToRunWithoutDryRun() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(EXECUTING_WORKFLOW);
// when
BuildResult result = runner(":verifyStrictLaneStages").buildAndFail();
// then
assertThat(result.getOutput()).contains("run it with --dry-run");
}
@Test
@DisplayName("접힌 run 블록이 빈 줄 때문에 옵션을 별개 명령으로 떼어 내면 그 workflow와 줄을 보고하고 실패한다")
void failsOnAFoldedRunBlockThatABlankLineSplits() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
EXECUTING_WORKFLOW
+ """
- name: Broken
run: >-
./gradlew
:leaf:check
--stacktrace
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput()).contains("main.yml line 13: '--stacktrace' follows a blank line");
}
@Test
@DisplayName("단계를 실행해도 -x로 뺀 lane은 덮이지 않으므로 그 lane 이름으로 실패한다")
void aLaneExcludedWithDashXIsNotCoveredByTheStageThatRuns() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
lane('cacheLane') { integration(); tag = 'cache'; description = 'Real cache.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: ./gradlew :ci --stacktrace
- run: ./gradlew :integrationCheck -x :leaf:databaseLane --continue
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("strict lane :leaf:databaseLane is in no executed stage")
.doesNotContain("strict lane :leaf:cacheLane");
}
@Test
@DisplayName("continue-on-error job이나 단계가 부르는 단계는 실패해도 막지 못하므로 실행으로 세지 않는다")
void aStageRunUnderContinueOnErrorIsNotAnExecution() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
gate:
steps:
- run: ./gradlew :ci --stacktrace
advisory:
runs-on: ubuntu-latest
continue-on-error: true
steps:
- run: ./gradlew :integrationCheck
other:
steps:
- name: Advisory step
continue-on-error: true
run: ./gradlew :integrationCheck
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("strict lane :leaf:databaseLane is in no executed stage");
}
@Test
@DisplayName("상태 함수가 아닌 if 조건 아래의 단계 실행은 매번 돈다고 볼 수 없으므로 세지 않는다")
void aStageRunUnderAConditionIsNotAnExecution() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
gate:
steps:
- run: ./gradlew :ci --stacktrace
disabled:
if: ${{ false }}
steps:
- run: ./gradlew :integrationCheck
manual:
steps:
- if: github.event_name == 'workflow_dispatch'
run: ./gradlew :integrationCheck
reported:
steps:
- if: always()
run: ./gradlew :integrationCheck --dry-run
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput()).contains("stage :integrationCheck is executed by no workflow");
}
@Test
@DisplayName("다른 빌드로 실행되는 빌드는 workflow가 그 디렉터리에서 시작한 단계만 실행으로 센다")
void aBuildStartedWithDashPCountsOnlyCommandsThatStartInItsDirectory() throws Exception {
// given
Path optional = gradleRoot.resolve("optional");
Files.createDirectories(optional.resolve("leaf/src/test/java"));
Files.writeString(
optional.resolve("settings.gradle"), "rootProject.name = 'optional'\ninclude 'leaf'\n");
Files.writeString(
optional.resolve("build.gradle"),
"""
plugins { id 'ca.strict-lane-stages' }
tasks.register('ci') { dependsOn ':leaf:check' }
tasks.register('integrationCheck') { dependsOn ':leaf:integrationTestLaneCheck' }
tasks.register('performanceCheck') { dependsOn ':leaf:check' }
strictLaneStages {
stage ':ci', ':integrationCheck', ':performanceCheck'
workflowDirectory = layout.projectDirectory.dir('../../.github/workflows')
}
""");
Files.writeString(
optional.resolve("leaf/build.gradle"),
"""
plugins {
id 'java'
id 'ca.strict-test-lane'
}
strictTestLanes {
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
}
""");
Files.writeString(optional.resolve("leaf/src/test/java/LaneTest.java"), "class LaneTest {}\n");
workflow(
"""
jobs:
main:
steps:
- working-directory: src
run: ./gradlew -p optional ci --stacktrace
- working-directory: src/optional
run: ../gradlew performanceCheck
- working-directory: src
run: ./gradlew :integrationCheck
""");
// when
BuildResult result =
GradleRunner.create()
.withProjectDir(optional.toFile())
.withPluginClasspath()
.withArguments(":verifyStrictLaneStages", "--dry-run")
.buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.doesNotContain("stage :ci is executed by no workflow")
.doesNotContain("stage :performanceCheck is executed by no workflow");
}
@Test
@DisplayName("축약한 -x로 뺀 lane도 Gradle처럼 맞춰 보아 덮이지 않은 것으로 실패한다")
void aLaneExcludedWithAnAbbreviatedDashXIsNotCovered() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
lane('cacheLane') { integration(); tag = 'cache'; description = 'Real cache.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: ./gradlew :ci --stacktrace
- run: ./gradlew :integrationCheck -x databaseL --continue
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("strict lane :leaf:databaseLane is in no executed stage")
.doesNotContain("strict lane :leaf:cacheLane");
}
@Test
@DisplayName("workflow_dispatch로만 시작하는 workflow가 부르는 단계는 실행으로 세지 않는다")
void aStageRunOnlyByADispatchOnlyWorkflowIsNotAnExecution() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(EXECUTING_WORKFLOW.replace("./gradlew :integrationCheck", "./gradlew :ci"));
Files.writeString(
repository.resolve(".github/workflows/manual.yml"),
"""
on:
workflow_dispatch:
jobs:
manual:
steps:
- working-directory: src
run: ./gradlew :integrationCheck
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("strict lane :leaf:databaseLane is in no executed stage");
}
@Test
@DisplayName("다른 빌드의 디렉터리를 working-directory로 둔 gradlew는 이 빌드의 단계 실행으로 세지 않는다")
void aCommandStartedInAnotherBuildsDirectoryIsNotThisBuildsExecution() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
jobs:
main:
steps:
- working-directory: src
run: ./gradlew :ci --stacktrace
- working-directory: src/optional
run: ../gradlew :integrationCheck
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput()).contains("stage :integrationCheck is executed by no workflow");
}
@Test
@DisplayName("working-directory 없이 cd src로 옮긴 뒤 단계를 부르는 workflow도 실행으로 세어 통과한다")
void passesWhenTheWorkflowCdsIntoTheBuildBeforeCallingGradlew() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
jobs:
main:
steps:
- run: cd src && ./gradlew ci --stacktrace
- run: |
cd src
./gradlew integrationCheck --continue
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").build();
// then
assertThat(result.getOutput()).contains("every strict lane is in an executed stage");
}
@Test
@DisplayName("따라갈 수 없는 cd 뒤에 부른 단계는 세지 않고, 실패 메시지에 그 명령과 세지 않은 이유를 적는다")
void aStageCalledAfterACdThatCannotBeFollowedFailsNamingWhy() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
jobs:
main:
steps:
- run: cd src && ./gradlew ci --stacktrace
- run: cd "$GITHUB_WORKSPACE/src" && ./gradlew integrationCheck
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("main.yml: gradlew integrationCheck")
.contains("cd \"$GITHUB_WORKSPACE/src\"");
}
@Test
@DisplayName("단계를 부르지만 다른 빌드로 읽힌 명령도 실패 메시지에 그 빌드 디렉터리와 함께 적는다")
void aStageCalledForAnotherBuildIsNamedWithThatBuildInTheFailure() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
jobs:
main:
steps:
- run: cd src && ./gradlew ci --stacktrace
- run: cd scr && ./gradlew integrationCheck
- working-directory: src
run: cd src && ./gradlew integrationCheck
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("main.yml: gradlew integrationCheck — it starts the build in scr, not src")
.contains("main.yml: gradlew integrationCheck — it starts the build in src/src, not src");
}
@Test
@DisplayName("실패를 막지 못하는 모양으로만 부른 단계는 실행으로 세지 않고, 실패 메시지에 그 이유를 적는다")
void aStageCalledOnlyInShapesThatCannotFailTheStepFailsNamingWhy() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: ./gradlew :ci --stacktrace
- run: ./gradlew :integrationCheck || true
- run: ./gradlew :integrationCheck | tee integration.log
- run: |
if ./gradlew :integrationCheck; then echo passed; fi
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("strict lane :leaf:databaseLane is in no executed stage")
.contains("|| true")
.contains("pipefail")
.contains("condition of if");
}
@Test
@DisplayName("짧은 플래그 묶음 -qm은 Gradle이 계획만 하는 명령이고, 검사도 그 단계를 실행으로 세지 않는다")
void aBundledDryRunFlagOnlyPlansInGradleAndDoesNotCountAsAnExecution() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
EXECUTING_WORKFLOW.replace(
"./gradlew :integrationCheck --continue", "./gradlew -qm :integrationCheck"));
BuildResult gradle = runner("-qm", ":ci").build();
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(gradle.getOutput()).contains(":leaf:test SKIPPED").contains(":ci SKIPPED");
assertThat(result.getOutput()).contains("stage :integrationCheck is executed by no workflow");
}
@Test
@DisplayName("값을 받는 옵션이 묶음 첫 글자가 아니면 Gradle이 명령을 거부하고, 검사도 그 이유로 세지 않는다")
void aValueOptionLaterInABundleIsRejectedByGradleAndDoesNotCount() throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
EXECUTING_WORKFLOW.replace(
"./gradlew :integrationCheck --continue", "./gradlew -mx :leaf:test :integrationCheck"));
// TestKit reports a command line Gradle rejects as an exception, not as a failed build.
Throwable gradle = catchThrowable(() -> runner("-mx", ":leaf:test", ":ci").build());
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(gradle)
.hasStackTraceContaining("No argument was provided for command-line option '-x'");
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("Gradle rejects -mx");
}
@Test
@DisplayName("실패하면 단계도 실패하지만 검사가 읽지 않는 모양으로만 부른 단계는 세지 않고, 그 명령을 혼자 한 줄로 두라고 안내한다")
void aStageCalledOnlyInAShapeTheCheckDoesNotReadFailsSayingToPutItOnALineOfItsOwn()
throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
defaults:
run:
working-directory: src
jobs:
main:
steps:
- run: ./gradlew :ci --stacktrace
- run: |
./gradlew :integrationCheck || { echo "::error::integration failed"; exit 1; }
echo done
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("this check does not read")
.contains("put the stage command on a line of its own");
}
@Test
@DisplayName("재사용 workflow의 단계는 매 변경에 도는 workflow가 부를 때만 세고, 요청으로만 부르면 세지 않는다")
void aStageInAReusableWorkflowCountsOnlyThroughACallerThatRunsOnEveryChange()
throws Exception {
// given
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
on:
workflow_call:
jobs:
gate:
runs-on: ubuntu-latest
steps:
- working-directory: src
run: ./gradlew :ci --stacktrace
""");
Files.writeString(
repository.resolve(".github/workflows/integration.yml"),
"""
on:
workflow_call:
jobs:
lanes:
runs-on: ubuntu-latest
steps:
- working-directory: src
run: ./gradlew :integrationCheck --continue
""");
Files.writeString(
repository.resolve(".github/workflows/pull-request.yml"),
"""
on: pull_request
jobs:
gate:
uses: ./.github/workflows/main.yml
""");
Files.writeString(
repository.resolve(".github/workflows/on-request.yml"),
"""
on: [workflow_dispatch, repository_dispatch]
jobs:
lanes:
uses: ./.github/workflows/integration.yml
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("integration.yml: gradlew :integrationCheck")
.contains("workflow_call")
.doesNotContain("stage :ci is executed by no workflow");
}
@Test
@DisplayName("태그 push로만 도는 workflow의 단계 명령은 releaseCheck에만 세고, 다른 단계는 실행되지 않은 것으로 본다")
void aReleaseFlowWorkflowCountsOnlyForTheReleaseStage() throws Exception {
// given
Files.writeString(
gradleRoot.resolve("build.gradle"),
"""
plugins { id 'ca.strict-lane-stages' }
tasks.register('ci') { dependsOn ':leaf:check' }
tasks.register('integrationCheck') { dependsOn ':leaf:integrationTestLaneCheck' }
tasks.register('releaseCheck')
strictLaneStages {
stage ':ci', ':integrationCheck', ':releaseCheck'
workflowDirectory = layout.projectDirectory.dir('../.github/workflows')
}
""");
leafLanes(
"""
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
""");
workflow(
"""
on: pull_request
jobs:
gate:
runs-on: ubuntu-latest
steps:
- working-directory: src
run: ./gradlew :ci --stacktrace
""");
Files.writeString(
repository.resolve(".github/workflows/release.yml"),
"""
on:
push:
tags: ['v*']
jobs:
release:
runs-on: ubuntu-latest
steps:
- working-directory: src
run: ./gradlew :releaseCheck
- working-directory: src
run: ./gradlew :integrationCheck --continue
""");
// when
BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail();
// then
assertThat(result.getOutput())
.contains("stage :integrationCheck is executed by no workflow")
.contains("release.yml: gradlew :integrationCheck")
.contains("counts only for :releaseCheck")
.doesNotContain("stage :releaseCheck is executed by no workflow");
}
private void leafLanes(String lanes) throws Exception {
Files.writeString(
gradleRoot.resolve("leaf/build.gradle"),
"""
plugins {
id 'java'
id 'ca.strict-test-lane'
}
strictTestLanes {
%s
}
"""
.formatted(lanes));
}
private void workflow(String content) throws Exception {
Files.writeString(repository.resolve(".github/workflows/main.yml"), content);
}
private GradleRunner runner(String... args) {
return GradleRunner.create()
.withProjectDir(gradleRoot.toFile())
.withPluginClasspath()
.withArguments(args);
}
}
@@ -0,0 +1,817 @@
package dev.caskeleton.buildlogic.strictlane;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class StrictTestLaneConventionTest {
@TempDir Path projectDir;
@BeforeEach
void setUp() throws Exception {
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name = 'fixture'\n");
}
@Test
void declaredLaneBecomesVerificationTaskWithDescription() throws Exception {
buildFile(
"""
strictTestLanes {
lane('contractLane') {
tag = 'contract'
description = 'What this lane proves.'
}
}
""");
BuildResult result = runner("tasks", "--group=verification").build();
assertTrue(result.getOutput().contains("contractLane"), result.getOutput());
assertTrue(result.getOutput().contains("What this lane proves."), result.getOutput());
}
@Test
void laneWithNoSelectionFailsAtConfigurationTime() throws Exception {
buildFile(
"""
strictTestLanes {
lane('untagged') { description = 'Selects nothing.' }
}
""");
BuildResult result = runner("tasks").buildAndFail();
assertTrue(
result.getOutput().contains("lane 'untagged'")
&& result.getOutput().contains("selects nothing"),
result.getOutput());
}
@Test
void laneWithNoDescriptionFails() throws Exception {
buildFile(
"""
strictTestLanes {
lane('undescribed') { tag = 'contract' }
}
""");
BuildResult result = runner("tasks").buildAndFail();
assertTrue(result.getOutput().contains("declares no description"), result.getOutput());
}
@Test
void emptySourceSetFailsInsteadOfNoSourceSuccess() throws Exception {
buildFile(
"""
strictTestLanes {
lane('emptyLane') {
tag = 'nothing-carries-this-tag'
description = 'Selects a tag no test declares.'
}
}
""");
BuildResult result = runner("emptyLane").buildAndFail();
assertTrue(result.getOutput().contains("has no sources"), result.getOutput());
}
@Test
void tagMatchingNothingFailsWhenTestsExist() throws Exception {
buildFile(
junitDependencies()
+ """
strictTestLanes {
lane('mismatchedLane') {
tag = 'no-test-carries-this'
description = 'A tag nothing declares.'
}
}
""");
writeTest(
"PresentTest.java",
"""
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class PresentTest {
@Test @Tag("carried") void present() {}
}
""");
BuildResult result = runner("mismatchedLane").buildAndFail();
assertTrue(result.getOutput().toLowerCase().contains("no test"), result.getOutput());
}
@Test
void laneOfOnlySkippedTestsFails() throws Exception {
buildFile(
junitDependencies()
+ """
strictTestLanes {
lane('skippedLane') {
tag = 'carried'
description = 'Every test it selects is skipped.'
}
}
""");
writeTest(
"SkippedTest.java",
"""
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class SkippedTest {
@Test @Tag("carried") @Disabled("quarantined") void disabled() {}
@Test @Tag("carried") void assumedAway() { Assumptions.assumeTrue(false, "no docker here"); }
}
""");
BuildResult result = runner("skippedLane").buildAndFail();
assertTrue(
result.getOutput().contains("executed no test")
&& result.getOutput().contains("skipped"),
result.getOutput());
}
@Test
void oneExecutionAllowsOtherSkippedTests() throws Exception {
buildFile(
junitDependencies()
+ """
strictTestLanes {
lane('mixedLane') {
tag = 'carried'
description = 'One test runs, one is skipped.'
}
}
""");
writeTest(
"MixedTest.java",
"""
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class MixedTest {
@Test @Tag("carried") @Disabled("quarantined") void disabled() {}
@Test @Tag("carried") void ran() {}
}
""");
BuildResult result = runner("mixedLane").build();
assertTrue(result.getOutput().contains("BUILD SUCCESSFUL"), result.getOutput());
}
@Test
void exactTestSelectionRunsOnlyNamedTest() throws Exception {
buildFile(
junitDependencies()
+ """
strictTestLanes {
lane('namedLane') {
description = 'Runs exactly one named contract.'
requires 'SelectedTest.selected'
}
}
""");
writeTest(
"SelectedTest.java",
"""
import org.junit.jupiter.api.Test;
class SelectedTest {
@Test void selected() {}
@Test void notSelected() { throw new AssertionError("this test is not in the lane"); }
}
""");
BuildResult result = runner("namedLane").build();
assertTrue(result.getOutput().contains("BUILD SUCCESSFUL"), result.getOutput());
}
@Test
void missingRequiredTestFailsLane() throws Exception {
buildFile(
junitDependencies()
+ """
strictTestLanes {
lane('renamedLane') {
description = 'Names a test that was renamed away.'
requires 'SelectedTest.selected', 'SelectedTest.renamedAway'
}
}
""");
writeTest(
"SelectedTest.java",
"""
import org.junit.jupiter.api.Test;
class SelectedTest { @Test void selected() {} }
""");
BuildResult result = runner("renamedLane").buildAndFail();
assertTrue(
result.getOutput().contains("renamedAway")
|| result.getOutput().toLowerCase().contains("no tests found"),
result.getOutput());
}
@Test
void tagAndRequiredTestsCannotBothBeDeclared() throws Exception {
buildFile(
"""
strictTestLanes {
lane('doubleSelection') {
tag = 'contract'
description = 'Two selections at once.'
requires 'SomeTest.some'
}
}
""");
BuildResult result = runner("tasks").buildAndFail();
assertTrue(result.getOutput().contains("pick one selection"), result.getOutput());
}
@Test
void duplicateLaneTaskNameFails() throws Exception {
buildFile(
"""
tasks.register('contractLane') { }
strictTestLanes {
lane('contractLane') {
tag = 'contract'
description = 'Collides with an existing task.'
}
}
""");
BuildResult result = runner("tasks").buildAndFail();
assertTrue(result.getOutput().contains("contractLane"), result.getOutput());
}
@Test
void aLaneNamedAfterItsJvmTestSuiteMakesTheSuiteTaskStrict() throws Exception {
// given
buildFile(
"""
testing {
suites {
integrationTest(JvmTestSuite) {
useJUnitJupiter('5.11.3')
dependencies { implementation project() }
}
}
}
strictTestLanes {
lane('integrationTest') {
integration()
sourceSet = 'integrationTest'
description = 'The suite task under strict-lane rules.'
}
}
""");
Path suiteSource = projectDir.resolve("src/integrationTest/java");
Files.createDirectories(suiteSource);
Files.writeString(
suiteSource.resolve("QuarantinedTest.java"),
"""
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class QuarantinedTest {
@Test @Disabled("quarantined") void quarantined() {}
}
""");
// when
BuildResult result = runner("integrationTest", "integrationTestLaneCheck").buildAndFail();
// then
assertTrue(result.getOutput().contains("a skip is not a result"), result.getOutput());
}
@Test
void laneSupportsTypedRuntimeAndOrderingOptions() throws Exception {
Files.createDirectories(projectDir.resolve("contracts"));
Files.writeString(projectDir.resolve("contracts/contract.txt"), "contract");
buildFile(
"""
sourceSets { architecture }
tasks.register('fixtureProducer')
strictTestLanes {
lane('architectureLane') {
sourceSet = 'architecture'
description = 'Architecture verification.'
group = 'architecture verification'
maxHeapSize = '512m'
jvmArgs '-Duser.timezone=UTC'
shouldRunAfter 'test'
dependsOn 'fixtureProducer'
systemProperty 'lane.mode', 'strict'
inputDirectory file('contracts')
}
}
tasks.register('reportLane') {
doLast {
def lane = tasks.named('architectureLane', Test).get()
logger.lifecycle('group=' + lane.group)
logger.lifecycle('heap=' + lane.maxHeapSize)
logger.lifecycle('utc=' + lane.allJvmArgs.contains('-Duser.timezone=UTC'))
logger.lifecycle('after-test=' + lane.shouldRunAfter.getDependencies(lane)*.name.contains('test'))
logger.lifecycle('depends-producer=' + lane.taskDependencies.getDependencies(lane)*.name.contains('fixtureProducer'))
logger.lifecycle('mode=' + lane.systemProperties['lane.mode'])
logger.lifecycle('input=' + lane.inputs.files.files.any { it.name == 'contract.txt' })
}
}
""");
BuildResult result = runner("reportLane", "--console=plain").build();
assertTrue(result.getOutput().contains("group=architecture verification"), result.getOutput());
assertTrue(result.getOutput().contains("heap=512m"), result.getOutput());
assertTrue(result.getOutput().contains("utc=true"), result.getOutput());
assertTrue(result.getOutput().contains("after-test=true"), result.getOutput());
assertTrue(result.getOutput().contains("depends-producer=true"), result.getOutput());
assertTrue(result.getOutput().contains("mode=strict"), result.getOutput());
assertTrue(result.getOutput().contains("input=true"), result.getOutput());
}
@Test
void rejectSkippedFailsWhenAnySelectedTestIsSkipped() throws Exception {
buildFile(
junitDependencies()
+ """
strictTestLanes {
lane('strictNoSkip') {
tag = 'carried'
description = 'Every selected test must execute.'
rejectSkipped = true
}
}
""");
writeTest(
"StrictNoSkipTest.java",
"""
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class StrictNoSkipTest {
@Test @Tag("carried") void ran() {}
@Test @Tag("carried") @Disabled("must fail lane") void skipped() {}
}
""");
BuildResult result = runner("strictNoSkip").buildAndFail();
assertTrue(result.getOutput().contains("forbids skipped tests"), result.getOutput());
}
@Test
void categoryAggregatesFollowRepositoryTestTaxonomy() throws Exception {
buildFile(
"""
sourceSets { ordinary; integration; system; architecture; performance }
strictTestLanes {
lane('ordinaryLane') {
sourceSet = 'ordinary'
description = 'Hermetic test.'
}
lane('integrationLane') {
sourceSet = 'integration'
description = 'External-infrastructure integration.'
integration()
}
lane('systemLane') {
sourceSet = 'system'
description = 'Full application/system test.'
system()
}
lane('architectureLane') {
sourceSet = 'architecture'
description = 'Architecture.'
architecture()
}
lane('performanceLane') {
sourceSet = 'performance'
description = 'Performance.'
performance()
}
}
tasks.register('reportCategories') {
doLast {
['strictTestLaneCheck', 'testLaneCheck', 'integrationTestLaneCheck', 'systemTestLaneCheck',
'architectureTestLaneCheck', 'performanceTestLaneCheck'].each { name ->
def aggregate = tasks.named(name).get()
logger.lifecycle(name + '=' + aggregate.taskDependencies.getDependencies(aggregate)*.name.sort())
}
}
}
""");
BuildResult result = runner("reportCategories", "--console=plain").build();
assertTrue(
result.getOutput().contains(
"strictTestLaneCheck=[architectureLane, integrationLane, ordinaryLane, performanceLane, systemLane]"),
result.getOutput());
assertTrue(result.getOutput().contains("testLaneCheck=[ordinaryLane]"), result.getOutput());
assertTrue(result.getOutput().contains("integrationTestLaneCheck=[integrationLane]"), result.getOutput());
assertTrue(result.getOutput().contains("systemTestLaneCheck=[systemLane]"), result.getOutput());
assertTrue(result.getOutput().contains("architectureTestLaneCheck=[architectureLane]"), result.getOutput());
assertTrue(result.getOutput().contains("performanceTestLaneCheck=[performanceLane]"), result.getOutput());
}
@Test
void dedicatedSourceSetNeedsNoTag() throws Exception {
buildFile(
"""
sourceSets { performance }
strictTestLanes {
lane('performanceLane') {
sourceSet = 'performance'
description = 'Its own source set is the selection.'
}
}
""");
BuildResult result = runner("tasks", "--group=verification").build();
assertTrue(result.getOutput().contains("performanceLane"), result.getOutput());
}
@Test
void aMainStageLaneLeavesTheLeafTestTaskAndJoinsMainCheck() throws Exception {
// given
buildFile(
junitDependencies()
+ """
tasks.register('mainCheck')
strictTestLanes {
lane('documentContractTest') {
tag = 'document-contract'
description = 'Compares the leaf with its documents.'
rejectSkipped = true
mainStage()
}
}
""");
writeTest(
"DocumentTest.java",
"""
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class DocumentTest {
@Test @Tag("document-contract") void comparesDocuments() {
throw new AssertionError("document lane test ran in the pull-request test task");
}
@Test void ordinary() {}
}
""");
// when
BuildResult test = runner("test").build();
BuildResult mainCheck = runner("mainCheck", "--dry-run").build();
// then
assertTrue(test.getOutput().contains("BUILD SUCCESSFUL"), test.getOutput());
assertTrue(mainCheck.getOutput().contains(":documentContractTest"), mainCheck.getOutput());
}
@Test
void anExplicitOnlyLaneStaysOutOfEveryAggregate() throws Exception {
// given
buildFile(
"""
sourceSets { integration }
strictTestLanes {
lane('credentialLane') {
sourceSet = 'integration'
description = 'Needs protected credentials.'
integration()
explicitOnly 'the protected credentials are not set'
}
}
tasks.register('reportAggregates') {
doLast {
['strictTestLaneCheck', 'integrationTestLaneCheck'].each { name ->
def aggregate = tasks.named(name).get()
logger.lifecycle(name + '=' + aggregate.taskDependencies.getDependencies(aggregate)*.name.sort())
}
}
}
""");
// when
BuildResult result =
runner("reportAggregates", "integrationTestLaneCheck", "--console=plain").build();
// then
assertTrue(result.getOutput().contains("strictTestLaneCheck=[]"), result.getOutput());
assertTrue(result.getOutput().contains("integrationTestLaneCheck=[]"), result.getOutput());
assertTrue(
result.getOutput().contains("the protected credentials are not set"), result.getOutput());
}
@Test
@DisplayName("hermetic lane은 같은 입력이면 build cache에서 가져오고, 외부 상태와 문서를 보는 lane은 매번 다시 돈다")
void hermeticLanesComeFromTheBuildCacheWhileExternalAndMainStageLanesRunAgain()
throws Exception {
// given
buildFile(
junitDependencies()
+ """
tasks.register('mainCheck')
strictTestLanes {
lane('unitLane') { tag = 'unit'; description = 'Hermetic.' }
lane('rulesLane') { architecture(); tag = 'rules'; description = 'Architecture rules.' }
lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' }
lane('documentLane') { tag = 'document-contract'; description = 'Documents.'; mainStage() }
}
""");
writeTest(
"LanesTest.java",
"""
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class LanesTest {
@Test @Tag("unit") void unit() {}
@Test @Tag("rules") void rules() {}
@Test @Tag("db") void database() {}
@Test @Tag("document-contract") void document() {}
}
""");
String[] lanes = {"unitLane", "rulesLane", "databaseLane", "documentLane", "--build-cache"};
runner(lanes).build();
runner("clean").build();
// when
BuildResult second = runner(lanes).build();
// then
assertThat(
List.of(":unitLane", ":rulesLane", ":databaseLane", ":documentLane").stream()
.map(path -> second.task(path).getOutcome())
.toList())
.containsExactly(
TaskOutcome.FROM_CACHE, TaskOutcome.FROM_CACHE, TaskOutcome.SUCCESS, TaskOutcome.SUCCESS);
}
@Test
@DisplayName("lane 정책만 바꾼 다음 실행은 이전 결과를 다시 쓰지 않고 새 정책으로 판정한다")
void aLanePolicyChangeIsJudgedAgainInsteadOfReusingTheEarlierResult() throws Exception {
// given
String lane =
"""
strictTestLanes {
lane('carriedLane') {
tag = 'carried'
description = 'Selected tests.'
rejectSkipped = %s
}
}
""";
buildFile(junitDependencies() + lane.formatted("false"));
writeTest(
"CarriedTest.java",
"""
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
class CarriedTest {
@Test @Tag("carried") void ran() {}
@Test @Tag("carried") @Disabled("skipped while the policy allowed it") void skipped() {}
}
""");
runner("carriedLane", "--build-cache").build();
buildFile(junitDependencies() + lane.formatted("true"));
// when
BuildResult stricter = runner("carriedLane", "--build-cache").buildAndFail();
// then
assertThat(stricter.getOutput()).contains("forbids skipped tests");
}
@Test
@DisplayName("서버를 띄우지 않는 TEST·ARCHITECTURE lane은 실서버 lane의 단일 슬롯을 잡지 않는다")
void onlyServerLanesTakeTheExclusiveRealServerSlot() throws Exception {
// given
buildFile(
"""
sourceSets { architecture; integration }
strictTestLanes {
lane('rulesLane') { sourceSet = 'architecture'; architecture(); description = 'Architecture rules.' }
lane('databaseLane') { sourceSet = 'integration'; integration(); description = 'Real database.' }
}
tasks.register('reportSlots') {
doLast {
['rulesLane', 'databaseLane'].each { name ->
def lane = tasks.named(name).get()
def services = lane.requiredServices.elements*.name
logger.lifecycle(name + '=' + services.contains('exclusiveRealServerLane'))
}
}
}
""");
// when
BuildResult result = runner("reportSlots", "--console=plain").build();
// then
assertThat(result.getOutput()).contains("rulesLane=false").contains("databaseLane=true");
}
@Test
void aPerformanceLaneFailsOnAnExceededBoundWhenTheBuildSetsNoAssertionsProperty()
throws Exception {
// given
buildFile(performanceLane(""));
writePerformanceTest(
"BoundTest.java",
"""
import org.junit.jupiter.api.Test;
class BoundTest {
@Test void staysInsideTheBound() {
long p99Millis = 900;
// The shape the httpclient lane had: the machine-dependent bound behind the switch.
if (Boolean.parseBoolean(System.getProperty("performance.assertions.enabled", "false"))
&& p99Millis > 500) {
throw new AssertionError("p99 900ms above the 500ms bound");
}
}
}
""");
// when
BuildResult result = runner("performanceTestLaneCheck").buildAndFail();
// then
assertThat(result.getOutput()).contains("BoundTest > staysInsideTheBound() FAILED");
}
@Test
void aPerformanceLaneFailsBeforeTestingWhenTheBuildTurnsItsAssertionsOff() throws Exception {
// given
buildFile(performanceLane(""));
writePerformanceTest(
"MeasuredTest.java",
"""
import org.junit.jupiter.api.Test;
class MeasuredTest {
@Test void measured() { throw new AssertionError("the lane ran a test"); }
}
""");
// when
BuildResult result =
runner("performanceTestLaneCheck", "-Pperformance.assertions.enabled=false")
.buildAndFail();
// then
assertThat(result.getOutput())
.contains("this build sets performance.assertions.enabled=false")
.contains("set it to true")
.doesNotContain("MeasuredTest > measured() FAILED");
}
@Test
void aPerformanceLaneFailsWhenItsOwnDeclarationTurnsTheAssertionsOff() throws Exception {
// given
buildFile(
performanceLane(
"""
systemProperty 'performance.assertions.enabled',
providers.gradleProperty('performance.assertions.enabled').orElse('false').get()
"""));
writePerformanceTest(
"MeasuredTest.java",
"""
import org.junit.jupiter.api.Test;
class MeasuredTest { @Test void measured() {} }
""");
// when
BuildResult result = runner("performanceTestLaneCheck").buildAndFail();
// then
assertThat(result.getOutput())
.contains("its test JVM would get performance.assertions.enabled=false")
.contains("delete the override");
}
@Test
void aPerformanceLaneFailsWhenItsJvmArgumentsTurnTheAssertionsOff() throws Exception {
// given
buildFile(performanceLane("jvmArgs '-Dperformance.assertions.enabled=false'"));
writePerformanceTest(
"MeasuredTest.java",
"""
import org.junit.jupiter.api.Test;
class MeasuredTest { @Test void measured() {} }
""");
// when
BuildResult result = runner("performanceTestLaneCheck").buildAndFail();
// then
assertThat(result.getOutput())
.contains("its test JVM would get performance.assertions.enabled=false")
.contains("delete the override");
}
@Test
void aPerformanceLaneFailsWhenOneOfItsTestsIsSkipped() throws Exception {
// given
buildFile(performanceLane(""));
writePerformanceTest(
"PartlyMeasuredTest.java",
"""
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class PartlyMeasuredTest {
@Test void measured() {}
@Test @Disabled("too slow on this machine") void quarantined() {}
}
""");
// when
BuildResult result = runner("performanceTestLaneCheck").buildAndFail();
// then
assertThat(result.getOutput())
.contains("forbids skipped tests")
.contains("a skipped test is a bound nobody measured");
}
@Test
void aPerformanceLaneAcceptsABuildThatTurnsItsAssertionsOnExplicitly() throws Exception {
// given
buildFile(performanceLane(""));
writePerformanceTest(
"MeasuredTest.java",
"""
import org.junit.jupiter.api.Test;
class MeasuredTest { @Test void measured() {} }
""");
// when
BuildResult result =
runner("performanceTestLaneCheck", "-Pperformance.assertions.enabled=true").build();
// then
assertThat(result.task(":loadLane").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
}
private void buildFile(String laneBlock) throws Exception {
Files.writeString(
projectDir.resolve("build.gradle"),
"""
plugins {
id 'java'
id 'ca.strict-test-lane'
}
repositories { mavenCentral() }
%s
"""
.formatted(laneBlock));
}
private void writeTest(String fileName, String source) throws Exception {
Path testSource = projectDir.resolve("src/test/java");
Files.createDirectories(testSource);
Files.writeString(testSource.resolve(fileName), source);
}
private void writePerformanceTest(String fileName, String source) throws Exception {
Path performanceSource = projectDir.resolve("src/performance/java");
Files.createDirectories(performanceSource);
Files.writeString(performanceSource.resolve(fileName), source);
}
private static String performanceLane(String extraDeclarations) {
return """
sourceSets { performance }
dependencies {
performanceImplementation platform('org.junit:junit-bom:5.11.3')
performanceImplementation 'org.junit.jupiter:junit-jupiter'
performanceRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
strictTestLanes {
lane('loadLane') {
performance()
sourceSet = 'performance'
description = 'Measures a resource bound.'
%s
}
}
"""
.formatted(extraDeclarations);
}
private static String junitDependencies() {
return """
dependencies {
testImplementation platform('org.junit:junit-bom:5.11.3')
testImplementation 'org.junit.jupiter:junit-jupiter'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
""";
}
private GradleRunner runner(String... args) {
return GradleRunner.create()
.withProjectDir(projectDir.toFile())
.withPluginClasspath()
.withArguments(args);
}
}
@@ -0,0 +1,71 @@
package dev.caskeleton.buildlogic.strictlane;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class TaskSelectorsTest {
private static final Map<String, Set<String>> BUILD =
Map.of(
":", Set.of("ci", "performanceCheck", "test"),
":grpc", Set.of("test"),
":grpc:grpc-testkit",
Set.of("test", "testClasses", "grpcPerformanceTest", "grpcPerformanceTestClasses"),
":leaf", Set.of("test", "databaseLane", "databaseLoadTest"));
@Test
@DisplayName("이름이 정확히 같은 태스크가 있으면 그 이름만 모든 프로젝트에서 뺀다")
void anExactNameRemovesOnlyThatNameInEveryProject() {
// when
Set<String> excluded = TaskSelectors.excludedPaths(List.of("test"), BUILD);
// then
assertThat(excluded)
.containsExactlyInAnyOrder(":test", ":grpc:test", ":grpc:grpc-testkit:test", ":leaf:test");
}
@Test
@DisplayName("camel-case 축약 이름은 Gradle처럼 그 태스크를 뺀다")
void aCamelCaseAbbreviationRemovesTheTaskGradleWouldRemove() {
// when
Set<String> excluded = TaskSelectors.excludedPaths(List.of("grpcPerformanceT"), BUILD);
// then
assertThat(excluded).containsExactly(":grpc:grpc-testkit:grpcPerformanceTest");
}
@Test
@DisplayName("경로의 프로젝트 이름도 축약할 수 있다")
void aQualifiedSelectorMayAbbreviateItsProjectNames() {
// when
Set<String> excluded = TaskSelectors.excludedPaths(List.of(":grpc:grpcT:gPT"), BUILD);
// then
assertThat(excluded).containsExactly(":grpc:grpc-testkit:grpcPerformanceTest");
}
@Test
@DisplayName("Gradle이 모호하다고 거부할 축약은 후보 전부를 뺀 것으로 본다")
void anAmbiguousAbbreviationRemovesEveryCandidate() {
// when
Set<String> excluded = TaskSelectors.excludedPaths(List.of("database"), BUILD);
// then
assertThat(excluded).containsExactlyInAnyOrder(":leaf:databaseLane", ":leaf:databaseLoadTest");
}
@Test
@DisplayName("맞는 태스크가 없는 선택자는 아무것도 빼지 않는다")
void aSelectorThatMatchesNothingRemovesNothing() {
// when
Set<String> excluded = TaskSelectors.excludedPaths(List.of(":leaf:cacheLane"), BUILD);
// then
assertThat(excluded).isEmpty();
}
}
+315
View File
@@ -0,0 +1,315 @@
import dev.caskeleton.buildlogic.java.JavaConventionsPlugin
import dev.caskeleton.buildlogic.publishing.SigningKeys
plugins {
id 'ca.architecture'
// Every strict lane belongs to a stage a workflow executes (.gitea/workflows). Without it a lane
// that fails closed can still run nowhere (template review 2026-11-03 RR-06-03).
id 'ca.strict-lane-stages'
// The release SBOM is published as an artifact of its own, `messaging-library`, next to the modules.
id 'maven-publish'
id 'signing'
// JMH benchmarks in messaging-kafka and messaging-testkit (`./gradlew :messaging:<leaf>:jmh`);
// never part of a gate. Declared here so the modules apply it by id at the catalog's version.
alias(libs.plugins.jmh) apply false
}
// The modules: every leaf the registry includes (settings.gradle). The family project `:messaging` is
// a folder, not a module.
def leaves = subprojects.findAll { it.childProjects.isEmpty() }
def leafPaths = leaves.collect { it.path }
// The root's coordinate is the release's: the SBOM artifact carries the version the modules carry.
group = providers.gradleProperty('libraryGroup').get()
def revision = JavaConventionsPlugin.sourceRevision(providers)
version = JavaConventionsPlugin.releaseVersion(providers) +
(revision == JavaConventionsPlugin.UNKNOWN_REVISION ? '-SNAPSHOT' : '')
// Captured here: inside a task's configuration `group` and `version` are the task's own properties.
def libraryCoordinates = [project.group.toString(), project.version.toString()]
tasks.register('resolveAndLockAll') {
group = 'build setup'
description = 'Regenerates dependency locks for every module (requires --write-locks).'
dependsOn leafPaths.collect { "${it}:resolveAndLockAll" }
}
tasks.register('verifyDependencyLocks') {
group = 'verification'
description = 'Fails when a module resolves something its strict lockfile does not list.'
dependsOn leafPaths.collect { "${it}:verifyDependencyLocks" }
}
tasks.register('checkAll') {
group = 'verification'
description = 'Runs every module check.'
dependsOn leafPaths.collect { "${it}:check" }
}
tasks.register('qualityCheck') {
group = 'verification'
description = 'Runs production-bytecode static analysis for every module.'
dependsOn leafPaths.collect { "${it}:qualityCheck" }
}
// SpotBugs + FindSecBugs over the test source sets (config/spotbugs/exclude-test.xml). The modules are
// small enough for the pull-request stage to afford it, so it joins `ci`.
tasks.register('testQualityCheck') {
group = 'verification'
description = 'Runs test-code static analysis for every module.'
dependsOn leafPaths.collect { "${it}:testQualityCheck" }
}
// build-logic is a copy of the template's convention plugins (build-logic/UPSTREAM.md); its own
// TestKit and unit tests keep the copy honest when it is changed here.
tasks.register('buildLogicTest') {
group = 'verification'
description = 'Runs the included build-logic build\'s tests.'
dependsOn gradle.includedBuild('build-logic').task(':test')
}
// The pull-request stage (pr.yml). messaging-testkit's `check` includes its repository-contract lane
// (the public-surface and settings-owner contracts read every module's sources and build script), so
// a dependency-scope or ownership drift stops a merge.
tasks.register('ci') {
group = 'verification'
description = 'The pull-request stage: module checks, architecture, static analysis, locks and build-logic tests.'
dependsOn tasks.named('checkAll')
dependsOn tasks.named('qualityCheck')
dependsOn tasks.named('testQualityCheck')
dependsOn tasks.named('verifyDependencyLocks')
// architectureCheck, not only the direction gate: it also runs verifyNoIgnoredSourcePackages.
dependsOn tasks.named('architectureCheck')
dependsOn tasks.named('buildLogicTest')
}
// Every module's integration lanes, all Testcontainers: messaging-kafka's broker certification lane
// (Kafka behind Toxiproxy), messaging-reliability-jdbc-postgresql's outbox, inbox and admin-journal
// contracts against PostgreSQL, and the starter's assembled round trip (Kafka and PostgreSQL). Needs a
// container runtime.
tasks.register('integrationCheck') {
group = 'verification'
description = 'Runs every module integration test lane. Needs a container runtime.'
dependsOn leafPaths.collect { "${it}:integrationTestLaneCheck" }
}
// The certification gate: the scenarios the committed manifest claims are the ones this run of the
// certification lane proved against a live broker (messaging-kafka/build.gradle). Editing the
// manifest by hand fails it; running the lane writes the produced copy to compare.
def certificationGate = ':messaging:messaging-kafka:verifyMessagingCertificationEvidence'
// The main-branch stage (main.yml): the pull-request stage again on the merged commit, plus the lanes
// that start containers and the certification gate. The template ran the gate in a workflow of its own
// (messaging-certification.yml, weekly and on messaging paths); here every main push and the nightly
// run run it. No module has a performance lane: the JMH benchmarks are not a gate.
tasks.register('mainCheck') {
group = 'verification'
description = 'The main-branch stage: ci, integrationCheck and the broker certification gate.'
dependsOn tasks.named('ci')
dependsOn tasks.named('integrationCheck')
dependsOn certificationGate
}
// ---------------------------------------------------------------- release (release.yml)
def sbomFile = layout.buildDirectory.file("release/messaging-library-${version}-cyclonedx.json")
tasks.register('verifyReleaseVersion') {
group = 'verification'
description = 'Fails unless this build names a release version and the commit it was built from.'
def releaseVersion = libraryCoordinates[1]
doLast {
if (releaseVersion.endsWith('-SNAPSHOT')) {
throw new GradleException("No commit id (-PgitRevision, GIT_SHA or GITHUB_SHA): ${releaseVersion} is not a release.")
}
if (releaseVersion == '0.0.1') {
throw new GradleException('No release version: run with RELEASE_TAG=vX.Y.Z (release.yml) or -PreleaseVersion.')
}
}
}
tasks.register('releaseSbom', Exec) {
group = 'release'
description = 'Writes the CycloneDX SBOM of the published modules from their lockfiles (Trivy).'
outputs.file(sbomFile)
outputs.upToDateWhen { false }
commandLine 'bash', file('scripts/release/sbom.sh'), sbomFile.get().asFile
}
tasks.register('dependencyVulnerabilityScan', Exec) {
group = 'verification'
description = 'Fails on a HIGH or CRITICAL dependency vulnerability or any CISA KEV match (Trivy).'
mustRunAfter tasks.named('releaseSbom')
def reports = layout.buildDirectory.dir('release/vulnerability')
commandLine 'bash', file('scripts/release/vulnerability-scan.sh'), reports.get().asFile
}
// The tag-only stage: the hermetic lanes of every module, the integration lanes, the broker
// certification gate (a release claims what the support matrix says, so the evidence is re-proved on
// the tagged commit), the version check, the SBOM and the dependency gate.
tasks.register('releaseCheck') {
group = 'verification'
description = 'The release stage before publishing: certification gate, integration lanes, version, SBOM, dependency gate.'
dependsOn tasks.named('verifyReleaseVersion')
dependsOn leafPaths.collect { "${it}:testLaneCheck" }
dependsOn tasks.named('integrationCheck')
dependsOn certificationGate
dependsOn tasks.named('releaseSbom')
dependsOn tasks.named('dependencyVulnerabilityScan')
}
publishing {
publications {
sbom(MavenPublication) {
artifactId = 'messaging-library'
artifact(sbomFile) {
classifier = 'cyclonedx'
extension = 'json'
builtBy tasks.named('releaseSbom')
}
pom {
name = 'messaging-library'
description = 'CycloneDX SBOM of the messaging-library modules of this version.'
url = providers.gradleProperty('repositoryUrl')
packaging = 'pom'
}
}
}
repositories {
maven {
name = 'gitea'
url = providers.gradleProperty('packagesUrl')
credentials(HttpHeaderCredentials) {
name = 'Authorization'
value = "token ${providers.environmentVariable('PACKAGE_TOKEN').getOrElse('')}"
}
authentication {
header(HttpHeaderAuthentication)
}
}
maven {
name = 'staging'
url = layout.buildDirectory.dir('staging-repository')
}
}
}
// The armoured key, or the base64 of the armoured file (the usual way to keep it in a CI secret).
def signingKey = SigningKeys.armoured(providers.environmentVariable('SIGNING_KEY').getOrElse(''))
// Before anything is signed: the secret's shape, that gpg imports it as the release key and that
// SIGNING_PASSWORD signs with it, printing no part of either. Gradle's signing reports every one of
// these as "Could not read PGP secret key" (v1.0.0 release run 9); this says which. A key other
// than the release key passes with -PsigningKeyFingerprint=<its fingerprint> (a rehearsal key).
// gpg reads only a passphrase's first line and Gradle the whole value, so the task then signs a few
// bytes with Gradle's own signatory: the verdict is the one the Sign tasks would reach.
tasks.register('verifySigningKey', Exec) {
group = 'verification'
description = 'Checks SIGNING_KEY and SIGNING_PASSWORD without printing them (scripts/release/check-signing-key.sh).'
outputs.upToDateWhen { false }
ignoreExitValue = true
commandLine 'bash', file('scripts/release/check-signing-key.sh'),
providers.gradleProperty('signingKeyFingerprint').getOrElse('')
def signed = !signingKey.isBlank()
doLast {
boolean scriptPassed = executionResult.get().exitValue == 0
boolean gradlePassed = !signed
String verdict = 'skipped: no SIGNING_KEY'
if (signed) {
try {
signing.signatory.sign(new ByteArrayInputStream('signing check'.bytes), OutputStream.nullOutputStream())
gradlePassed = true
verdict = 'ok'
} catch (Exception failure) {
// Exception text only: BouncyCastle names what failed (checksum mismatch, a tag), never the key.
def cause = failure.cause ? " (${failure.cause.class.simpleName}: ${failure.cause.message})" : ''
verdict = "failed: ${failure.message}${cause}"
}
}
logger.lifecycle("signing as Gradle's Sign tasks do (in-memory key): ${verdict}")
if (!scriptPassed || !gradlePassed) {
throw new GradleException('verifySigningKey: the signing secrets would not sign; the PROBLEM lines above say why.')
}
}
}
tasks.withType(Sign).configureEach {
mustRunAfter tasks.named('verifySigningKey')
}
if (!signingKey.isBlank()) {
signing {
useInMemoryPgpKeys(signingKey, providers.environmentVariable('SIGNING_PASSWORD').getOrElse(''))
sign publishing.publications.sbom
}
}
tasks.withType(PublishToMavenRepository).configureEach {
mustRunAfter tasks.named('releaseCheck')
if (name.endsWith('ToGiteaRepository')) {
def signed = !signingKey.isBlank()
def token = providers.environmentVariable('PACKAGE_TOKEN').getOrElse('')
doFirst {
if (!signed) {
throw new GradleException('SIGNING_KEY is not set; refusing to publish unsigned files to Gitea.')
}
if (token.isBlank()) {
throw new GradleException('PACKAGE_TOKEN is not set; Gitea\'s job token cannot publish packages.')
}
}
}
}
// Everything release.yml does up to the upload, into build/staging-repository: what `release` would
// publish, checked file by file. Needs no secret; with SIGNING_KEY set it also checks every .asc.
tasks.register('releaseRehearsal') {
group = 'release'
description = 'releaseCheck, then publishes every module and the SBOM to build/staging-repository and checks the files.'
dependsOn tasks.named('releaseCheck')
if (!signingKey.isBlank()) {
dependsOn tasks.named('verifySigningKey')
}
dependsOn tasks.named('publishAllPublicationsToStagingRepository')
dependsOn leafPaths.collect { "${it}:publishAllPublicationsToStagingRepository" }
def staging = layout.buildDirectory.dir('staging-repository')
def artifacts = leaves.collect { it.name }
def coordinates = libraryCoordinates
def signed = !signingKey.isBlank()
def checker = file('scripts/release/check-staging.py')
doLast {
def command = ['python3', checker.path, staging.get().asFile.path, coordinates[0], coordinates[1],
signed ? 'signed' : 'unsigned'] + artifacts
def process = command.execute()
process.waitForProcessOutput(System.out, System.err)
if (process.exitValue() != 0) {
throw new GradleException('releaseRehearsal: the staged release is incomplete (see above).')
}
}
}
// The release: releaseCheck, then every module and the SBOM to Gitea Packages, then an anonymous read
// of each module's metadata. release.yml runs this one task on a vX.Y.Z tag.
tasks.register('release') {
group = 'release'
description = 'releaseCheck, publish to Gitea Packages, then verify the version is readable anonymously.'
dependsOn tasks.named('releaseCheck')
dependsOn tasks.named('verifySigningKey')
dependsOn tasks.named('publishAllPublicationsToGiteaRepository')
dependsOn leafPaths.collect { "${it}:publishAllPublicationsToGiteaRepository" }
def url = providers.gradleProperty('packagesUrl')
def artifacts = leaves.collect { it.name } + ['messaging-library']
def coordinates = libraryCoordinates
def verifier = file('scripts/release/verify-published.sh')
doLast {
def command = ['bash', verifier.path, url.get(), coordinates[0], coordinates[1]] + artifacts
def process = command.execute()
process.waitForProcessOutput(System.out, System.err)
if (process.exitValue() != 0) {
throw new GradleException('release: a published module is not readable anonymously (see above).')
}
}
}
// The stages a strict lane may belong to, executed by .gitea/workflows as `./gradlew <stage>` from the
// repository root. releaseCheck may run on a tag push only.
strictLaneStages {
stage ':ci', ':mainCheck', ':releaseCheck'
workflowDirectory = layout.projectDirectory.dir('.gitea/workflows')
}
+190
View File
@@ -0,0 +1,190 @@
{
"modules": [
{
"id": "messaging-core-api",
"gradle_path": ":messaging:messaging-core-api",
"source_path": "messaging/messaging-core-api",
"allowed_dependencies": []
},
{
"id": "messaging-schema-json",
"gradle_path": ":messaging:messaging-schema-json",
"source_path": "messaging/messaging-schema-json",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-schema-avro",
"gradle_path": ":messaging:messaging-schema-avro",
"source_path": "messaging/messaging-schema-avro",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-schema-protobuf",
"gradle_path": ":messaging:messaging-schema-protobuf",
"source_path": "messaging/messaging-schema-protobuf",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-cloudevents",
"gradle_path": ":messaging:messaging-cloudevents",
"source_path": "messaging/messaging-cloudevents",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-policy",
"gradle_path": ":messaging:messaging-policy",
"source_path": "messaging/messaging-policy",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-transport-spi",
"gradle_path": ":messaging:messaging-transport-spi",
"source_path": "messaging/messaging-transport-spi",
"allowed_dependencies": [
"messaging-core-api",
"messaging-policy"
]
},
{
"id": "messaging-runtime-core",
"gradle_path": ":messaging:messaging-runtime-core",
"source_path": "messaging/messaging-runtime-core",
"allowed_dependencies": [
"messaging-core-api",
"messaging-policy",
"messaging-transport-spi",
"messaging-security",
"messaging-observability"
]
},
{
"id": "messaging-observability",
"gradle_path": ":messaging:messaging-observability",
"source_path": "messaging/messaging-observability",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-security",
"gradle_path": ":messaging:messaging-security",
"source_path": "messaging/messaging-security",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-kafka",
"gradle_path": ":messaging:messaging-kafka",
"source_path": "messaging/messaging-kafka",
"allowed_dependencies": [
"messaging-core-api",
"messaging-policy",
"messaging-transport-spi",
"messaging-observability",
"messaging-security",
"messaging-admin"
]
},
{
"id": "messaging-reliability-api",
"gradle_path": ":messaging:messaging-reliability-api",
"source_path": "messaging/messaging-reliability-api",
"allowed_dependencies": [
"messaging-core-api"
]
},
{
"id": "messaging-reliability",
"gradle_path": ":messaging:messaging-reliability",
"source_path": "messaging/messaging-reliability",
"allowed_dependencies": [
"messaging-core-api",
"messaging-reliability-api"
]
},
{
"id": "messaging-reliability-jdbc-postgresql",
"gradle_path": ":messaging:messaging-reliability-jdbc-postgresql",
"source_path": "messaging/messaging-reliability-jdbc-postgresql",
"allowed_dependencies": [
"messaging-core-api",
"messaging-reliability-api",
"messaging-admin",
"messaging-policy"
]
},
{
"id": "messaging-claim-check",
"gradle_path": ":messaging:messaging-claim-check",
"source_path": "messaging/messaging-claim-check",
"allowed_dependencies": [
"messaging-core-api",
"messaging-reliability-api"
]
},
{
"id": "messaging-admin",
"gradle_path": ":messaging:messaging-admin",
"source_path": "messaging/messaging-admin",
"allowed_dependencies": [
"messaging-core-api",
"messaging-observability"
]
},
{
"id": "messaging-spring-boot-starter",
"gradle_path": ":messaging:messaging-spring-boot-starter",
"source_path": "messaging/messaging-spring-boot-starter",
"allowed_dependencies": [
"messaging-admin",
"messaging-core-api",
"messaging-observability",
"messaging-policy",
"messaging-reliability",
"messaging-reliability-api",
"messaging-reliability-jdbc-postgresql",
"messaging-runtime-core",
"messaging-schema-json",
"messaging-security",
"messaging-transport-spi"
]
},
{
"id": "messaging-spring-boot-starter-kafka",
"gradle_path": ":messaging:messaging-spring-boot-starter-kafka",
"source_path": "messaging/messaging-spring-boot-starter-kafka",
"allowed_dependencies": [
"messaging-spring-boot-starter",
"messaging-kafka",
"messaging-admin",
"messaging-core-api",
"messaging-observability",
"messaging-policy",
"messaging-reliability-api",
"messaging-security",
"messaging-transport-spi"
]
},
{
"id": "messaging-testkit",
"gradle_path": ":messaging:messaging-testkit",
"source_path": "messaging/messaging-testkit",
"allowed_dependencies": [
"messaging-core-api",
"messaging-policy",
"messaging-transport-spi"
]
}
]
}
@@ -0,0 +1,28 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<!--
feature-static-analysis-quality-contract D2 / §3 — Checkstyle suppression filter.
Narrowly-scoped relaxations only. The contract keeps naming + logical rules
blocking on main source; this file carves out documented tool-contract exceptions.
-->
<suppressions>
<!-- code-conventions I6 outside main source.
OneTopLevelClass and OuterTypeFilename replace the hand-rolled `verifyOneTypePerFile`
Gradle task, which read `src/main/java` and nothing else. Applying them to every source set
at the same time would be a policy change smuggled in as a tool change: 28 OneTopLevelClass
violations and 1 OuterTypeFilename violation exist today, all of them co-located test
fixtures (`...Test.java` holding a `...Fixtures` / `Fake...` / `Recording...` type below the
test class), and none of them in main source — main is clean on both rules, including the
package-private top-level types the old regex could not see.
Extending the rule to test sources is a real question with a real answer either way, and it
belongs to whoever moves those 29 fixtures into their own files or decides they should stay.
The regex matches any src/<sourceSet>/java path whose source set is not `main`. -->
<suppress checks="OneTopLevelClass|OuterTypeFilename"
files="[\\/]src[\\/](?!main[\\/])[^\\/]+[\\/]java[\\/]"/>
</suppressions>
+93
View File
@@ -0,0 +1,93 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!--
feature-static-analysis-quality-contract D2 — custom minimal Checkstyle ruleset.
Scope is deliberately limited to what google-java-format (Spotless, D1) CANNOT enforce:
naming and logical/design rules. Formatting and import-order modules are
intentionally ABSENT — the formatter owns them. Enabling LineLength/Indentation/Whitespace/
CustomImportOrder here would fight the formatter (checkstyle #6527) and trap CI in an
infinite reformat loop.
Test-source relaxations live in checkstyle-suppressions.xml (resolved via ${config_loc}).
-->
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="error"/>
<property name="fileExtensions" value="java"/>
<!-- Test-source + generated-source relaxations (checkstyleTest is warning-only anyway). -->
<module name="SuppressionFilter">
<property name="file" value="${config_loc}/checkstyle-suppressions.xml"/>
<property name="optional" value="false"/>
</module>
<module name="TreeWalker">
<!-- ================= naming (KEEP, blocking) — CS-C2 / CS-C5 ================= -->
<module name="TypeName"/>
<module name="MethodName"/>
<!-- ConstantName: real constants are UPPER_SNAKE_CASE (code-conventions N9), but a
Logger has mutable observable state so it is NOT a constant — Google §5.2.4 names
it lowerCamelCase (log/logger). Permit those two idiomatic logger names. -->
<module name="ConstantName">
<property name="format" value="^(log|logger|[A-Z][A-Z0-9]*(_[A-Z0-9]+)*)$"/>
</module>
<module name="MemberName"/>
<module name="StaticVariableName"/>
<module name="ParameterName"/>
<module name="LambdaParameterName"/>
<module name="CatchParameterName"/>
<module name="LocalVariableName"/>
<module name="LocalFinalVariableName"/>
<module name="PackageName"/>
<!-- Type parameters are UPPER alphanumeric. Allows the conventional T/E/K/V/R and the
F-bounded self-type idiom SELF (see ResourceId<SELF extends ResourceId<SELF>>). -->
<module name="ClassTypeParameterName">
<property name="format" value="^[A-Z][A-Z0-9]*$"/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="^[A-Z][A-Z0-9]*$"/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="^[A-Z][A-Z0-9]*$"/>
</module>
<module name="RecordComponentName"/>
<module name="RecordTypeParameterName">
<property name="format" value="^[A-Z][A-Z0-9]*$"/>
</module>
<module name="PatternVariableName"/>
<!-- ================= file/type structure (code-conventions I6) =================
One top-level type per file, and the file is named after it.
These replace the hand-rolled `verifyOneTypePerFile` Gradle task, which matched
`^public ...` line by line. That regex could not see a package-private top-level type
(126 main sources declared none that it matched at all), read only `src/main/java`,
and anchored at column 0 so a block comment or text-block line starting with `public`
would have counted as a declaration. Checkstyle parses the file, so all three go away.
Neither rule is redundant with javac. javac rejects a *public* type whose name does not
match the file; both of these also hold for package-private top-level types, which
javac accepts.
Scope is main source only, which is exactly what the task it replaces checked. Test
sources declare 29 co-located fixture types that these rules would reject, and widening
the rule while claiming to replace a task is two changes wearing one name — the
exemption is in checkstyle-suppressions.xml with the count. -->
<module name="OneTopLevelClass"/>
<module name="OuterTypeFilename"/>
<!-- ================= logical / design (KEEP) — google_checks CS-C1 ================= -->
<module name="NeedBraces"/>
<module name="FallThrough"/>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected|ignored"/>
</module>
<module name="OneStatementPerLine"/>
<module name="MissingSwitchDefault"/>
</module>
</module>
+84
View File
@@ -0,0 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
SpotBugs + FindSecBugs exclude filter for test code: every source set but main (test,
testFixtures, integrationTest, systemTest, architectureTest and the other lanes). Production code
is analysed by spotbugsMain against config/spotbugs/exclude.xml; this file is never applied to it
(QualityConventionsPlugin, testQualityCheck).
Until 2026-11-04 these tasks existed, ran in no gate, and 53 of them failed with 300 findings.
Each finding was judged. A rule is excluded below only when its reason holds for every test
class it can ever match; everything else was fixed, or is a Match scoped to one class with its
own reason (same rule as exclude.xml).
Test code never reaches a production classpath: test fixtures are consumed only by test suites
(`testImplementation testFixtures(...)`, `implementation testFixtures(project())` inside a
JvmTestSuite), which the dependency-direction gate keeps out of production configurations.
-->
<FindBugsFilter>
<!-- FindSecBugs (category SECURITY): taint, injection, deserialization, crypto, SSRF, path,
ReDoS, hard-coded credential and CSRF rules model untrusted input reaching a production
sink. A test writes its own input, runs only under the test runner, and holds fixture
credentials on purpose. The same code moved to main is analysed with these rules on. -->
<Match>
<Bug category="SECURITY"/>
</Match>
<!-- MALICIOUS_CODE (EI_EXPOSE_REP, EI_EXPOSE_REP2, MS_*): these protect a production object from
a caller that mutates state it was handed. Fakes and fixtures hand their state to the test
on purpose — that is how the test observes them. -->
<Match>
<Bug category="MALICIOUS_CODE"/>
</Match>
<!-- CT_CONSTRUCTOR_THROW: the risk is a finalizer attack by untrusted code that subclasses the
class. Test classes are instantiated by JUnit or by the test itself; a constructor that
throws fails the test. -->
<Match>
<Bug pattern="CT_CONSTRUCTOR_THROW"/>
</Match>
<!-- NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE: a test dereferences a value it expects to be there
(a response body, a header, a map entry). If it is null the NullPointerException fails the
test, which is the failure an unmet expectation should produce; a requireNonNull in front
adds a line and changes nothing. -->
<Match>
<Bug pattern="NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"/>
</Match>
<!-- DLS_DEAD_LOCAL_STORE into a local named `unused` or `ignored`: Error Prone's
CheckReturnValue makes a test keep the result it means to drop (`var unused =
catchThrowable(...)` when only the side effect is asserted), and the name says the value is
dropped on purpose. A dead store to any other name is still reported. -->
<Match>
<Bug pattern="DLS_DEAD_LOCAL_STORE"/>
<Local name="~unused|ignored"/>
</Match>
<!-- RV_RETURN_VALUE_IGNORED_INFERRED / _NO_SIDE_EFFECT inside a lambda: in test code these are
the ThrowingCallable / Executable handed to assertThatThrownBy, isThrownBy, catchThrowable
or assertThrows. Their type is void, so the value cannot be kept, and the call is made for
the exception it throws. RV_RETURN_VALUE_IGNORED (a must-check result such as
CountDownLatch.await) stays reported in lambdas too. -->
<Match>
<Or>
<Bug pattern="RV_RETURN_VALUE_IGNORED_INFERRED"/>
<Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT"/>
</Or>
<Method name="~lambda\$.*"/>
</Match>
<!-- DM_GC: both tests are about what garbage collection does — a gauge that must survive a
collection instead of decaying to NaN through a weak reference, and a retained-set bound
measured between two collections. System.gc() is the request they exist to make. -->
<Match>
<Bug pattern="DM_GC"/>
<Or>
<And>
<Class name="dev.caskeleton.messaging.schema.json.PlatformOverheadPerformanceTest"/>
<Method name="aRoundTripDoesNotAllocateAGrowingRetainedSet"/>
</And>
</Or>
</Match>
</FindBugsFilter>
+200
View File
@@ -0,0 +1,200 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
feature-static-analysis-quality-contract D3/D4 — SpotBugs + FindSecBugs exclude filter.
SpotBugs (D3) and FindSecBugs (D4, via spotbugsPlugins) analyse bytecode. Inter-procedural
taint analysis has known limits (FindSecBugs false positives) and generated code carries
patterns the source author never wrote. Add ONLY confirmed false positives here, each as a
narrowly-scoped <Match> — never a blanket bug-pattern exclusion across all sources.
Reference: https://github.com/spotbugs/spotbugs / https://find-sec-bugs.github.io/
-->
<FindBugsFilter>
<!-- The messaging codec retention test measures whether a round trip retains per-message state.
Measuring retained memory requires forcing a collection first and again at the end;
without it the "after" reading is dominated by garbage that simply had not been collected
yet and the test could never distinguish a leak from ordinary allocation. Scoped to the
one test class, so an explicit gc anywhere else stays reportable. -->
<Match>
<Bug pattern="DM_GC"/>
<Source name="PlatformOverheadPerformanceTest.java"/>
</Match>
<!-- The outbox and inbox container tests apply the real shipped Flyway migration by reading it
from the classpath and executing it, which is the whole point: a test that re-declared the
schema inline would certify a schema nothing deploys. The SQL is a build artifact, not
input, and the database is a throwaway container. Scoped to these two classes so any other
dynamic SQL stays reportable. -->
<Match>
<Bug pattern="SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE"/>
<Source name="~(Inbox|Outbox)PostgresIT.java"/>
</Match>
<!-- =========================================================================================
Confidence MEDIUM (review 2026-11-01 08-07). Everything below was added when the report
level went from HIGH to MEDIUM. Each entry was judged against the code it names; defects
were fixed in the code instead of listed here. Counts are in QualityConventionsPlugin.
========================================================================================= -->
<!-- EI_EXPOSE_REP / EI_EXPOSE_REP2, pattern 1 of 4 — references that are not values.
SpotBugs calls any field "mutable" whose type has a set/add/remove/delete/write-shaped
method, and asks for a copy whenever one is stored from a parameter or returned. For a
field that holds a collaborator (a port, a repository, an EntityManager, a MeterRegistry,
an executor, a template, a settings bean), a handle (a channel, a future, a reflected
Method, an exception kept as a cause) or a nested setter-bound settings object, sharing the
reference is the design: constructor injection stores collaborators, and a copy would be a
different collaborator. The check stays on for the types where a copy IS the remedy —
collections, arrays, Date, ByteBuffer and JSON trees — so a value type that keeps a
caller's list or array is still reported. SpotBugs field types are exact names, not
patterns: an array of any other element type is not re-checked by this list. -->
<Match>
<Bug pattern="EI_EXPOSE_REP,EI_EXPOSE_REP2"/>
<Not>
<Or>
<Field type="java.util.Collection"/>
<Field type="java.util.List"/>
<Field type="java.util.Set"/>
<Field type="java.util.SortedSet"/>
<Field type="java.util.NavigableSet"/>
<Field type="java.util.Queue"/>
<Field type="java.util.Deque"/>
<Field type="java.util.Map"/>
<Field type="java.util.SortedMap"/>
<Field type="java.util.NavigableMap"/>
<Field type="java.util.ArrayList"/>
<Field type="java.util.LinkedList"/>
<Field type="java.util.HashSet"/>
<Field type="java.util.LinkedHashSet"/>
<Field type="java.util.TreeSet"/>
<Field type="java.util.EnumSet"/>
<Field type="java.util.HashMap"/>
<Field type="java.util.LinkedHashMap"/>
<Field type="java.util.TreeMap"/>
<Field type="java.util.EnumMap"/>
<Field type="java.util.Date"/>
<Field type="java.nio.ByteBuffer"/>
<Field type="byte[]"/>
<Field type="char[]"/>
<Field type="short[]"/>
<Field type="int[]"/>
<Field type="long[]"/>
<Field type="float[]"/>
<Field type="double[]"/>
<Field type="boolean[]"/>
<Field type="java.lang.Object[]"/>
<Field type="java.lang.String[]"/>
<Field type="tools.jackson.databind.JsonNode"/>
<Field type="tools.jackson.databind.node.ObjectNode"/>
<Field type="tools.jackson.databind.node.ArrayNode"/>
<Field type="com.fasterxml.jackson.databind.JsonNode"/>
<Field type="com.fasterxml.jackson.databind.node.ObjectNode"/>
<Field type="com.fasterxml.jackson.databind.node.ArrayNode"/>
</Or>
</Not>
</Match>
<!-- EI pattern 3 of 4 — settings binding carriers. Setter-bound @ConfigurationProperties
JavaBeans are mutable by contract (a public setter opens more than the getter does), and
the constructor-bound records listed here have no invariant of their own: each is read
once at startup by the factory that compiles it into the runtime type, and that factory
copies (HttpClientProfileFactory and DynamicTargetAutoConfiguration Set.copyOf every list;
MessagingConfigurationCompiler copies into DestinationAccessPolicy and SchemaPolicy;
RedisRuntimeAutoConfiguration validates and maps; FileserverStartupValidator reads the
ancestors once). A settings record that validates a collection in its own constructor
copies it there instead (FileserverPlatformSettings.Security). -->
<Match>
<Bug pattern="EI_EXPOSE_REP,EI_EXPOSE_REP2"/>
<Or>
<Class name="dev.caskeleton.messaging.autoconfigure.MessagingSettings"/>
<Class name="dev.caskeleton.messaging.autoconfigure.BrokerSecuritySettings$Access"/>
<Class name="dev.caskeleton.messaging.autoconfigure.DestinationSettings$Schema"/>
</Or>
</Match>
<!-- EI pattern 4 of 4 — the collection is already an unmodifiable copy. Each field below is
assigned an unmodifiable collection at construction (List/Set/Map.copyOf,
Collectors.toUnmodifiable*, Stream.toList, Collections.unmodifiable* over a fresh copy),
but through a branch, a stream or a private constructor fed by a copying factory, which
SpotBugs does not follow; it recognises only a field assigned straight from copyOf. Listed
by class and field, so another collection added to the same class is still reported. -->
<Match>
<Bug pattern="EI_EXPOSE_REP,EI_EXPOSE_REP2"/>
<Or>
<And><Class name="dev.caskeleton.messaging.api.header.MessageHeaders"/><Field name="values"/></And>
</Or>
</Match>
<!-- CredentialRuntime takes ownership of the secret array the registry resolved for it, so that
clear() overwrites the only copy. Copying in the constructor would leave the provider's
array behind, uncleared, which is the outcome the char[] field type exists to prevent. -->
<Match>
<Bug pattern="EI_EXPOSE_REP2"/>
<Class name="dev.caskeleton.messaging.security.CredentialRuntime"/>
<Method name="&lt;init&gt;"/>
</Match>
<!-- CT_CONSTRUCTOR_THROW (finalizer attack: a subclass's finalize() keeps a half-built object).
A final class cannot be attacked this way, and every class that could be made final was.
These three groups must stay subclassable. -->
<!-- CT group 1 — CGLIB proxies. @RequiresPermission is enforced by a method-security advisor,
and Spring Boot proxies with CGLIB, which subclasses the bean
(RequiresPermissionProxyabilityTest fails the build if such a class is final). The
Annotation matcher covers every class annotated at class level, including ones added
later. A class that annotates only some methods is proxied all the same but is not matched
here; name it when one appears. A @Configuration class is CGLIB-subclassed for its @Bean
methods for the same reason. -->
<Match>
<Bug pattern="CT_CONSTRUCTOR_THROW"/>
<Or>
<Annotation name="dev.caskeleton.application.security.RequiresPermission"/>
<Annotation name="org.springframework.context.annotation.Configuration"/>
</Or>
</Match>
<!-- FindSecBugs REDOS, one Match per constructor or static initialiser. Every pattern flagged
is "segment (separator segment)*" where the separator is a character the segment class
cannot contain ('.', '-', ';', or a class of those), so each input splits exactly one way
and backtracking is linear, not exponential. The application-core and messaging values
also check the length (at most 64-256 characters) before the pattern runs; JsonPathName and SafeSortField
match developer-declared paths; the SNS host comes from a URI host. -->
<Match>
<Bug pattern="REDOS"/>
<Or>
<And><Class name="dev.caskeleton.messaging.api.ContentType"/><Method name="&lt;clinit&gt;"/></And>
</Or>
</Match>
<!-- SQL_INJECTION_JDBC: transition() and transitionWithNextAttempt() append a fixed WHERE clause
to a SET clause that every caller passes as a string literal from this class; every value
is a bound parameter. The method names are the lambdas javac generates inside them. -->
<Match>
<Bug pattern="SQL_INJECTION_JDBC"/>
<Class name="dev.caskeleton.messaging.outbox.JdbcOutboxRepository"/>
<Method name="~lambda\$transition(WithNextAttempt)?\$\d+"/>
</Match>
<!-- PREDICTABLE_RANDOM: log sampling (SamplingTurboFilter.decide) and retry jitter
(BackoffCalculator's default source, HttpClientProfileAutoConfiguration.jitterRandom) only
need spread, not unpredictability; nothing security-relevant is derived from any of these
values. Knowing the next jitter tells a caller when a retry lands, which the retry policy
already bounds. SecureRandom would read as a security requirement that is not there. -->
<Match>
<Bug pattern="PREDICTABLE_RANDOM"/>
<Or>
<And><Class name="dev.caskeleton.messaging.policy.BackoffCalculator"/><Method name="~lambda\$new\$\d+"/></And>
</Or>
</Match>
<!-- MS_EXPOSE_REP on a static that is already immutable: a Jackson 3 ObjectMapper cannot be
reconfigured after build() (NotificationJsonMapper), and CertifiedEvidence.RECORDED is a
Stream.toList() result. -->
<Match>
<Bug pattern="MS_EXPOSE_REP"/>
<Or>
<And><Class name="dev.caskeleton.messaging.testkit.CertifiedEvidence"/><Method name="recorded"/></And>
</Or>
</Match>
</FindBugsFilter>
@@ -0,0 +1,25 @@
# The container images the test lanes start, in one place.
#
# ca.java-conventions reads this file and hands every key to every Test JVM as the system property
# `ca.test.image.<key>`; the file is an input of every Test task, so changing an image reruns the
# lanes that use it. Build scripts read the same values as `testContainerImages['<key>']`. Copied
# from the backend template's src/config/testing/container-images.properties and cut to the images
# this library's lanes start.
#
# Each image is pinned by digest, with its tag in the comment above it: a red lane should mean this
# repository changed, not that someone pushed a new image under the same tag. A lane whose image
# cannot be pulled fails; it does not skip. The broker certification evidence records the Kafka
# digest (messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl), so a
# change of the `kafka` line below changes the evidence and has to rerun the certification lane.
#
# Pulling through a mirror: set TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX in the environment, for example
# `registry.internal/dockerhub/`. Images from other registries (ghcr.io below) are not rewritten by
# the prefix; mirror them under the same name or replace the value here.
# postgres:16-alpine — the outbox, inbox and admin-journal lane (messaging-reliability-jdbc-postgresql)
# and the starter's consume round trip.
postgres-16=postgres@sha256:0cefaabd882e42bcb2a2f3dc56d3ce4770560ba62fd7f197f1a2e008fd5731ab
# apache/kafka:4.1.0 — the certification lane and the starter round trip.
kafka=apache/kafka@sha256:bff074a5d0051dbc0bbbcd25b045bb1fe84833ec0d3c7c965d1797dd289ec88f
# ghcr.io/shopify/toxiproxy:2.12.0 — the certification lane's fault injection.
toxiproxy=ghcr.io/shopify/toxiproxy@sha256:9378ed52a28bc50edc1350f936f518f31fa95f0d15917d6eb40b8e376d1a214e
+13
View File
@@ -0,0 +1,13 @@
# The Maven group every module publishes under, and where. ca.java-conventions refuses a build
# without libraryGroup; ca.library-publishing reads the other two.
libraryGroup=dev.cakit.messaging
packagesUrl=https://git.learn.hyeonworks.com/api/packages/donghyeon.kang/maven
repositoryUrl=https://git.learn.hyeonworks.com/donghyeon.kang/messaging-library
# The release signing key (public fingerprint). verifySigningKey refuses any other key in SIGNING_KEY.
signingKeyFingerprint=92646CEAFE816CF8B9C249F0A1C936D7F791F8AB
# Build defaults, copied from the backend template's src/gradle.properties.
org.gradle.workers.max=4
org.gradle.jvmargs=-Xmx1g -XX:MaxMetaspaceSize=512m -Dfile.encoding=UTF-8
org.gradle.caching=true
org.gradle.parallel=true
+87
View File
@@ -0,0 +1,87 @@
# Version catalog — every dependency and tool version this build pins itself.
#
# Copied from the backend template's src/gradle/libs.versions.toml (see build-logic/UPSTREAM.md for
# the commit) and cut to the entries this library uses. Versions managed by an imported BOM (Spring
# Boot: kafka-clients, Spring JDBC, Micrometer, Jackson, Testcontainers) are not here.
# `gradle.lockfile` fixes what resolves; this file makes the chosen versions visible side by side.
#
# The `pinned-*` libraries: no module declares them, and their upstream still brings a version with
# a High or Critical advisory. build-logic's JavaConventionsPlugin pins every `pinned-*` entry
# through Spring dependency management in every configuration (the Checkstyle and Error Prone
# classpaths included). Delete an entry once every upstream named in its comment brings a fixed
# version itself.
[versions]
assertj = "3.27.7"
# messaging-schema-avro's codec.
avro = "1.12.0"
# Checkstyle *tool* version (the `checkstyle` extension), not a plugin: Checkstyle is a Gradle
# built-in plugin with no coordinate of its own.
checkstyle = "13.5.0"
# messaging-cloudevents' binding.
cloudevents = "4.0.1"
errorprone = "2.49.0"
# The Gradle plugin that runs the checker above. Two different artifacts, two different version
# lines, deliberately adjacent so a bump of one is visibly not a bump of the other.
errorpronePlugin = "5.1.0"
findsecbugs = "1.14.0"
# Spotless's google-java-format step. A formatter version is a repository-wide decision: a bump
# reformats every file.
googleJavaFormat = "1.35.0"
# Pinned (see `pinned-*` below). CVE-2026-102554, fixed in 33.7.2. Brought by Error Prone (33.5.0)
# and the Checkstyle tool (33.6.0).
guava = "33.7.2-jre"
# Only build-logic resolves jackson3 as written (it reads the module registry); in the modules the
# Spring Boot BOM's jackson-bom decides. Keep it at the BOM's number.
jackson3 = "3.1.7"
# JMH benchmarks in messaging-kafka and messaging-testkit (`./gradlew :messaging:<leaf>:jmh`); never
# part of a gate.
jmh = "1.37"
jmhPlugin = "0.7.3"
junitJupiter = "5.11.3"
junitPlatform = "1.11.3"
# Pinned (see `pinned-*` below). CVE-2026-106451, fixed in 1.11.4. Brought by kafka-clients (1.10.1).
lz4Java = "1.11.4"
# Pinned (see `pinned-*` below). CVE-2025-67030, fixed in 3.6.1 on the 3.x line. Brought by the
# Checkstyle tool's doxia (3.3.0).
plexusUtils = "3.6.1"
# messaging-schema-protobuf's codec.
protobuf = "4.33.2"
# Pinned (see `pinned-*` below). CVE-2026-93451 and CVE-2026-108106, fixed in 1.1.10.9. Brought by
# kafka-clients (1.1.10.7).
snappyJava = "1.1.10.9"
# SpotBugs *tool* version (the `spotbugs` extension). The plugin that runs it is spotbugsPlugin.
spotbugs = "4.10.2"
spotbugsPlugin = "6.5.6"
spotless = "8.6.0"
springBoot = "4.0.9"
# The version that actually resolves. Spring Boot 4.0.9's own plugin brings
# dependency-management 1.1.7, so the 1.1.6 that used to be written here was a floor nothing ever
# selected (`./gradlew buildEnvironment` reported `1.1.6 -> 1.1.7`). build-logic applies the plugin
# too and has no Boot plugin to upgrade it, so a catalog stating a version nobody resolves would
# have given the convention plugins a different one from the leaves.
springDependencyManagement = "1.1.7"
# messaging-kafka's certification lane puts Toxiproxy between the client and the broker.
toxiproxy = "2.1.7"
[libraries]
assertj-core = { module = "org.assertj:assertj-core", version.ref = "assertj" }
avro = { module = "org.apache.avro:avro", version.ref = "avro" }
cloudevents-api = { module = "io.cloudevents:cloudevents-api", version.ref = "cloudevents" }
cloudevents-core = { module = "io.cloudevents:cloudevents-core", version.ref = "cloudevents" }
errorprone-core = { module = "com.google.errorprone:error_prone_core", version.ref = "errorprone" }
findsecbugs-plugin = { module = "com.h3xstream.findsecbugs:findsecbugs-plugin", version.ref = "findsecbugs" }
jackson3-core = { module = "tools.jackson.core:jackson-core", version.ref = "jackson3" }
jackson3-databind = { module = "tools.jackson.core:jackson-databind", version.ref = "jackson3" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junitJupiter" }
junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junitPlatform" }
protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" }
toxiproxy-java = { module = "eu.rekawek.toxiproxy:toxiproxy-java", version.ref = "toxiproxy" }
pinned-guava = { module = "com.google.guava:guava", version.ref = "guava" }
pinned-lz4-java = { module = "at.yawk.lz4:lz4-java", version.ref = "lz4Java" }
pinned-plexus-utils = { module = "org.codehaus.plexus:plexus-utils", version.ref = "plexusUtils" }
pinned-snappy-java = { module = "org.xerial.snappy:snappy-java", version.ref = "snappyJava" }
[plugins]
jmh = { id = "me.champeau.jmh", version.ref = "jmhPlugin" }
Binary file not shown.
+8
View File
@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip
distributionSha256Sum=8fad3d78296ca518113f3d29016617c7f9367dc005f932bd9d93bf45ba46072b
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015 the original 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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+1 -1
View File
@@ -98,7 +98,7 @@ tasks.register('verifyMessagingCertificationEvidence') {
description = 'Fails when the committed broker certification manifest claims a scenario the certification lane did not produce.'
dependsOn 'messagingCertificationTest'
def produced = layout.buildDirectory.file('messaging-certification/broker-certification-evidence.jsonl')
def committed = rootProject.file('platforms/messaging/messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl')
def committed = rootProject.file('messaging/messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl')
inputs.file(produced)
inputs.file(committed)
doLast {
+28
View File
@@ -16,3 +16,31 @@ dependencies {
api 'org.junit.jupiter:junit-jupiter'
api 'org.assertj:assertj-core'
}
// The repository contracts of the whole library: every module's public signatures against its
// declared `api` scope, and the one owner of the `app.messaging` settings namespace. They read other
// modules' sources and build scripts, so they run in a lane of their own that declares exactly those
// files as inputs and receives the repository root; the plain `test` lane gets no root, and a test
// that reads the repository without the tag fails there. The template ran them in its app-bootstrap
// `repositoryContractTest` lane until the library left it. Part of `check`, so of the pull-request
// stage.
def repositoryRoot = rootProject.projectDir
strictTestLanes {
lane('repositoryContractTest') {
tag = 'repository-contract'
description = 'Holds every module to its declared api scope and the one owner of app.messaging.'
systemProperty 'ca.repository.root', repositoryRoot.absolutePath
customize { Test task ->
task.inputs.files(fileTree(repositoryRoot) {
include 'messaging/*/build.gradle', 'messaging/*/src/main/**', 'gradle/libs.versions.toml'
exclude '**/build/**'
}).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('repositoryContractInputs')
}
}
}
tasks.named('test', Test) {
useJUnitPlatform { excludeTags 'repository-contract' }
}
tasks.named('check') {
dependsOn 'repositoryContractTest'
}
@@ -1,8 +1,7 @@
package dev.caskeleton.bootstrap.contract.messaging;
package dev.caskeleton.messaging.testkit.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
@@ -34,8 +33,8 @@ import org.junit.jupiter.api.Test;
*
* <p>So the rule is one-directional and mechanical: a vendor library named in a public or protected
* signature is declared {@code api}; one used only behind private members stays {@code
* implementation}. {@code src/platforms/messaging/AGENTS.md} states it as policy — this holds it to
* the source so the two cannot drift.
* implementation}. {@code messaging/AGENTS.md} states it as policy — this holds it to the source so
* the two cannot drift.
*
* <p>The libraries checked are the ones an adopter would otherwise have to reverse-engineer into
* their own build: broker clients, codec libraries, the metrics registry, the reactive facade.
@@ -327,7 +326,7 @@ class MessagingPublicSurfaceContractTest {
*/
private static Map<String, String> catalogModules() {
Map<String, String> modules = new LinkedHashMap<>();
Path catalog = repositoryRoot().resolve("src/gradle/libs.versions.toml");
Path catalog = repositoryRoot().resolve("gradle/libs.versions.toml");
if (!Files.isRegularFile(catalog)) {
return modules;
}
@@ -345,7 +344,7 @@ class MessagingPublicSurfaceContractTest {
}
private static List<Path> messagingLeaves() {
Path family = repositoryRoot().resolve("src/platforms/messaging");
Path family = repositoryRoot().resolve("messaging");
try (Stream<Path> children = Files.list(family)) {
return children
.filter(Files::isDirectory)
@@ -378,9 +377,6 @@ class MessagingPublicSurfaceContractTest {
}
private static Path repositoryRoot() {
// Gradle hands the root only to the lanes that declare the repository files as inputs; the
// plain `test` lane gets none, so a test that reads the repository without a lane tag fails
// here instead of going stale behind an up-to-date check (review 2026-11-01 08-03).
return RepositoryContractResources.fromSystemProperty().repositoryRoot();
return RepositoryRoot.fromSystemProperty();
}
}
@@ -0,0 +1,91 @@
package dev.caskeleton.messaging.testkit.contract;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
/**
* How many types in this library own the {@code app.messaging} settings namespace.
*
* <p>The namespace is shared on purpose with one consumer: the backend template's outbound adapter
* binds {@code app.messaging.producer-id} through a settings type of its own, and the starter's
* {@code MessagingSettings} owns everything else, {@code broker} included. Spring binds both — each
* takes the fields it declares. While the two lived in one repository a single source scan counted
* both (the template's {@code MessagingAuthorityContractTest}, MSG-INT-002). Now each repository
* holds its own half: here, exactly one owner. A second one inside the library is how a setting
* comes to mean two things to two halves of the same product. The prefix is part of this library's
* public contract; renaming it is a MAJOR change.
*/
@Tag("repository-contract")
class MessagingSettingsOwnerContractTest {
private static final Pattern MESSAGING_PREFIX =
Pattern.compile("@ConfigurationProperties\\(\\s*(prefix\\s*=\\s*)?\"app\\.messaging\"");
private static final Pattern MESSAGING_PREFIX_CONSTANT =
Pattern.compile("@ConfigurationProperties\\(prefix = MessagingSettings\\.PREFIX\\)");
/** A strictly bound owner names its tree in a constant rather than an annotation. */
private static final Pattern STRICT_BINDER_PREFIX =
Pattern.compile("String PREFIX\\s*=\\s*\"app\\.messaging\"");
@Test
@DisplayName("이 라이브러리에서 app.messaging의 주인은 starter의 MessagingSettings 하나다")
void theStarterSettingsAreTheOnlyOwner() {
// given
List<Path> sources = productionSources();
// when
List<String> owners =
sources.stream()
.filter(MessagingSettingsOwnerContractTest::ownsTheNamespace)
.map(path -> repositoryRoot().relativize(path).toString())
.toList();
// then
assertThat(owners)
.containsExactly(
"messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/"
+ "autoconfigure/MessagingSettings.java");
}
private static boolean ownsTheNamespace(Path source) {
String text = read(source);
return MESSAGING_PREFIX.matcher(text).find()
|| MESSAGING_PREFIX_CONSTANT.matcher(text).find()
|| STRICT_BINDER_PREFIX.matcher(text).find();
}
private static List<Path> productionSources() {
try (Stream<Path> walk = Files.walk(repositoryRoot().resolve("messaging"))) {
return walk.filter(path -> path.toString().endsWith(".java"))
.filter(path -> path.toString().contains("/src/main/java/"))
.filter(path -> !path.toString().contains("/build/"))
.sorted()
.toList();
} catch (IOException unreadable) {
throw new UncheckedIOException(unreadable);
}
}
private static String read(Path path) {
try {
return Files.readString(path);
} catch (IOException unreadable) {
throw new UncheckedIOException(unreadable);
}
}
private static Path repositoryRoot() {
return RepositoryRoot.fromSystemProperty();
}
}
@@ -0,0 +1,50 @@
package dev.caskeleton.messaging.testkit.contract;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.List;
/**
* The repository root for the contract tests that read other modules' files.
*
* <p>Gradle passes it only to messaging-testkit's {@code repositoryContractTest} lane, which
* declares the files those tests read as its inputs. The plain {@code test} lane gets no root, so
* an untagged test that reads the repository fails here rather than passing on a stale up-to-date
* result. The same rule as the backend template's {@code RepositoryContractResources}, which these
* tests used while they lived there.
*/
final class RepositoryRoot {
static final String ROOT_PROPERTY = "ca.repository.root";
private static final List<String> ROOT_SENTINELS =
List.of("settings.gradle", "config/architecture/modules.json");
private RepositoryRoot() {}
static Path fromSystemProperty() {
String configured = System.getProperty(ROOT_PROPERTY);
if (configured == null || configured.isBlank()) {
throw new IllegalStateException(
"Required system property '"
+ ROOT_PROPERTY
+ "' is missing or blank. Only the repository-contract lane receives it: tag a test"
+ " that reads the repository with `repository-contract`.");
}
Path root;
try {
root = Path.of(configured).toRealPath();
} catch (InvalidPathException | IOException unresolvable) {
throw new IllegalStateException(
"Repository root is not resolvable: " + configured, unresolvable);
}
for (String sentinel : ROOT_SENTINELS) {
if (!Files.isRegularFile(root.resolve(sentinel))) {
throw new IllegalStateException(
"Configured repository root must contain " + ROOT_SENTINELS + ": " + root);
}
}
return root;
}
}
+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env bash
# Checks the release signing secrets before anything is signed, without printing them.
#
# scripts/release/check-signing-key.sh [expected fingerprint]
#
# Reads SIGNING_KEY (an ASCII-armoured PGP secret key) and SIGNING_PASSWORD from the environment and
# prints only shapes and verdicts: line and character counts, whether the armour lines and the blank
# line after BEGIN are where OpenPGP puts them, whether the base64 body decodes and its CRC24 matches,
# the first packet's tag, whether gpg imports it, the imported key's fingerprint (public), and whether
# SIGNING_PASSWORD signs with it. No value, line or fragment of either secret is ever printed; do not
# add `set -x` here.
#
# Why it exists: Gradle's signing reports any of these problems as one "Could not read PGP secret
# key", and the cause sits in a secret nobody can look at in the job log (v1.0.0 release run 9).
# Exit codes: 0 = the key would sign, 1 = a check failed (the line says which), 2 = usage.
set -euo pipefail
expected=${1:-}
fail=0
if [ -z "${SIGNING_KEY:-}" ]; then
echo "check-signing-key: SIGNING_KEY is empty or not set"
exit 1
fi
[ -n "${SIGNING_PASSWORD:-}" ] || echo "check-signing-key: SIGNING_PASSWORD is empty (only right for a key without a passphrase)"
# The passphrase's shape only: a pasted value often carries a line break or spaces the key was not
# protected with, and Gradle uses the value as given.
python3 - <<'PY' || fail=1
import os, sys
p = os.environ.get("SIGNING_PASSWORD", "")
print(f"password shape: {len(p)} characters, line breaks {p.count(chr(10))}, CR {p.count(chr(13))},"
f" leading whitespace {'yes' if p[:1].isspace() else 'no'}, trailing whitespace {'yes' if p[-1:].isspace() else 'no'},"
f" non-ASCII characters {sum(1 for c in p if ord(c) > 127)}")
if "-----BEGIN PGP" in p or len(p) > 1000:
print("PROBLEM: SIGNING_PASSWORD holds a PGP key block (or something as long), not the passphrase."
" Put in only the passphrase chosen when the key was made.")
sys.exit(1)
PY
home=$(mktemp -d)
trap 'rm -rf "$home"' EXIT
chmod 700 "$home"
KEY_OUT=$home/key.asc EXPECTED_FINGERPRINT=$expected python3 - <<'PY' || fail=1
import base64, os, re, sys
key = os.environ["SIGNING_KEY"]
BEGIN = "-----BEGIN PGP PRIVATE KEY BLOCK-----"
END = "-----END PGP PRIVATE KEY BLOCK-----"
problems = []
print(f"shape: {len(key)} characters, {key.count(chr(10)) + 1} lines,"
f" CR {'present' if chr(13) in key else 'absent'},"
f" literal backslash-n sequences {key.count(chr(92) + 'n')},"
f" non-ASCII characters {sum(1 for c in key if ord(c) > 127)},"
f" leading whitespace {'yes' if key[:1].isspace() else 'no'},"
f" trailing whitespace {'yes' if key[-1:].isspace() else 'no'}")
stripped = key.strip()
compact = re.sub(r"\s", "", key)
if "-----BEGIN" not in key and re.fullmatch(r"[A-Za-z0-9+/]+={0,2}", compact or "x"):
try:
unwrapped = base64.b64decode(compact).decode("utf-8")
except Exception:
unwrapped = ""
if unwrapped.strip().startswith("-----BEGIN PGP PRIVATE KEY BLOCK-----"):
print("form: base64 of an armoured key file on one value; the build unwraps it (SigningKeys), so the checks below read the unwrapped text")
key = unwrapped
stripped = key.strip()
print(f"unwrapped shape: {len(key)} characters, {key.count(chr(10)) + 1} lines")
if re.fullmatch(r"(0x)?[0-9A-Fa-f]{8}|(0x)?[0-9A-Fa-f]{16}|[0-9A-Fa-f]{40}", stripped):
expected = os.environ.get("EXPECTED_FINGERPRINT", "")
same = " (the release key's fingerprint)" if expected and stripped.upper() == expected.upper() else ""
print(f"PROBLEM: SIGNING_KEY holds a {len(stripped)}-hex-digit key ID or fingerprint{same}, not the key."
" Put in the output of `gpg --armor --export-secret-keys <fingerprint>` instead, BEGIN to END lines.")
sys.exit(1)
lines = key.replace("\r\n", "\n").replace("\r", "\n").split("\n")
while lines and lines[-1].strip() == "":
lines.pop()
if "\n" not in key.replace("\r", "\n"):
problems.append("the value is one line: the newlines were lost (paste the file as is, with its line breaks)")
first = lines[0].strip() if lines else ""
last = lines[-1].strip() if lines else ""
print(f"armour: first line is BEGIN {'yes' if first == BEGIN else 'no'}, last line is END {'yes' if last == END else 'no'}")
if first != BEGIN:
kind = "a PUBLIC key block" if "PUBLIC KEY BLOCK" in first else "something else"
problems.append(f"the value does not start with the BEGIN PGP PRIVATE KEY BLOCK line (it starts with {kind})")
if last != END:
problems.append("the value does not end with the END PGP PRIVATE KEY BLOCK line (cut short?)")
body = lines[1:-1] if first == BEGIN and last == END else lines
headers = []
while body and ":" in body[0] and body[0].strip():
headers.append(body.pop(0))
blank_after = bool(body) and body[0].strip() == ""
print(f"armour headers: {len(headers)}, blank line after them {'yes' if blank_after else 'no'}")
if not blank_after:
problems.append("no blank line between the BEGIN line (and its headers) and the base64 body")
data = [l.strip() for l in body if l.strip()]
checksum = data.pop() if data and data[-1].startswith("=") else None
lengths = [len(l) for l in data]
full = sum(1 for n in lengths[:-1] if n == lengths[0]) if lengths else 0
print(f"body: {len(data)} base64 lines, first {lengths[0] if lengths else 0} characters wide,"
f" {full + (1 if lengths else 0)} of {len(data)} lines that width or the last,"
f" checksum line {'present' if checksum else 'absent'}")
if lengths and any(n != lengths[0] for n in lengths[:-1]):
problems.append("base64 lines of different widths before the last one (lines joined, split or cut)")
joined = "".join(data)
bad = sum(1 for c in joined if not re.match(r"[A-Za-z0-9+/=]", c))
if bad:
problems.append(f"{bad} characters outside the base64 alphabet in the body")
try:
raw = base64.b64decode(joined, validate=False)
except Exception as error:
raw = b""
problems.append(f"the body does not decode as base64 ({type(error).__name__})")
if raw:
def crc24(data):
crc = 0xB704CE
for byte in data:
crc ^= byte << 16
for _ in range(8):
crc <<= 1
if crc & 0x1000000:
crc ^= 0x1864CFB
return crc & 0xFFFFFF
if checksum:
try:
stated = int.from_bytes(base64.b64decode(checksum[1:]), "big")
match = stated == crc24(raw)
except Exception:
match = False
print(f"CRC24 of the decoded body matches the checksum line: {'yes' if match else 'no'}")
if not match:
problems.append("the CRC24 checksum does not match: the base64 body was changed (a line lost, added or edited)")
header = raw[0]
tag = (header & 0x3F) if header & 0x40 else ((header & 0x3C) >> 2)
names = {5: "secret key", 6: "public key", 7: "secret subkey"}
print(f"first packet: tag {tag} ({names.get(tag, 'not a key packet')}), {len(raw)} bytes decoded")
if not header & 0x80 or tag != 5:
problems.append("the first packet is not a secret key packet (tag 5)")
for problem in problems:
print(f"PROBLEM: {problem}")
with open(os.environ["KEY_OUT"], "w", encoding="utf-8") as out:
out.write(key)
sys.exit(1 if problems else 0)
PY
if [ -s "$home/key.asc" ] && GNUPGHOME="$home" gpg --batch --quiet --import "$home/key.asc" >/dev/null 2>&1; then
fingerprint=$(GNUPGHOME="$home" gpg --batch --with-colons --list-secret-keys 2>/dev/null | awk -F: '/^fpr/{print $10; exit}')
echo "gpg import: ok, secret key fingerprint ${fingerprint:-none}"
if [ -n "$expected" ] && [ "${fingerprint:-}" != "$expected" ]; then
echo "PROBLEM: the imported key is not the release key ${expected}"
fail=1
fi
printf 'signing check\n' > "$home/message"
# gpg reads only the first line of the file; the shape line above says whether there is more.
printf '%s' "${SIGNING_PASSWORD:-}" > "$home/passphrase"
if GNUPGHOME="$home" gpg --batch --pinentry-mode loopback --passphrase-file "$home/passphrase" \
--status-fd 3 --local-user "${fingerprint:-none}" --detach-sign --output "$home/message.sig" \
"$home/message" >/dev/null 2>&1 3>"$home/status"; then
echo "signing with SIGNING_PASSWORD: ok"
else
# gpg's status keywords only (BAD_PASSPHRASE, MISSING_PASSPHRASE, ERROR …): no values.
status=$(awk '$1 == "[GNUPG:]" {print $2}' "$home/status" | sort -u | tr '\n' ' ')
echo "PROBLEM: SIGNING_PASSWORD does not unlock the key for signing (gpg status: ${status:-none})"
fail=1
fi
else
echo "PROBLEM: gpg cannot import SIGNING_KEY"
fail=1
fi
exit "$fail"
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Checks a staged release (build/staging-repository) file by file before anything is uploaded.
check-staging.py <repository dir> <group> <version> signed|unsigned <artifact>...
For every module: the jar, sources and javadoc jars, POM and Gradle module file, each with its
.md5/.sha1/.sha256/.sha512 checksum (and .asc when signed), and every dependency in the POM and the
module file carries a version. The last check is the publishing trap the design names: the modules
declare most dependencies without a version and let a BOM fill it, and a published file written
from the declarations would leave consumers nothing to resolve. For the SBOM artifact
(messaging-library): its POM and the CycloneDX JSON.
"""
import json
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
CHECKSUMS = (".md5", ".sha1", ".sha256", ".sha512")
POM = "{http://maven.apache.org/POM/4.0.0}"
def expect(path: Path, signed: bool, problems: list[str]) -> None:
if not path.is_file():
problems.append(f"missing {path.name}")
return
for suffix in CHECKSUMS + ((".asc",) if signed else ()):
if not path.with_name(path.name + suffix).is_file():
problems.append(f"missing {path.name}{suffix}")
def unversioned_pom(pom: Path) -> list[str]:
root = ET.parse(pom).getroot()
out = []
for dependency in root.iter(f"{POM}dependency"):
version = dependency.findtext(f"{POM}version")
if not version or not version.strip():
out.append(f"{dependency.findtext(f'{POM}groupId')}:{dependency.findtext(f'{POM}artifactId')}")
return out
def unversioned_module(module: Path) -> list[str]:
data = json.loads(module.read_text(encoding="utf-8"))
out = []
for variant in data.get("variants", []):
for dependency in variant.get("dependencies", []):
version = dependency.get("version") or {}
if not any(version.get(k) for k in ("requires", "strictly", "prefers")):
out.append(f"{variant['name']}: {dependency['group']}:{dependency['module']}")
return out
def main() -> int:
if len(sys.argv) < 6:
print(__doc__, file=sys.stderr)
return 2
repository, group, version, signing = Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4]
signed = signing == "signed"
failed = False
for artifact in sys.argv[5:] + ["messaging-library"]:
directory = repository / group.replace(".", "/") / artifact / version
base = directory / f"{artifact}-{version}"
problems: list[str] = []
if artifact == "messaging-library":
expect(base.with_name(base.name + ".pom"), signed, problems)
expect(base.with_name(base.name + "-cyclonedx.json"), signed, problems)
else:
for suffix in (".jar", "-sources.jar", "-javadoc.jar", ".pom", ".module"):
expect(base.with_name(base.name + suffix), signed, problems)
pom, module = base.with_name(base.name + ".pom"), base.with_name(base.name + ".module")
if pom.is_file():
problems += [f"POM dependency without a version: {d}" for d in unversioned_pom(pom)]
if module.is_file():
problems += [f"module dependency without a version: {d}" for d in unversioned_module(module)]
if problems:
failed = True
print(f"{group}:{artifact}:{version}", file=sys.stderr)
for problem in problems:
print(f" - {problem}", file=sys.stderr)
else:
print(f"staged: {group}:{artifact}:{version}{' (signed)' if signed else ''}")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# The release's software bill of materials: one CycloneDX JSON for the version, from the committed
# lockfiles of the published modules (build-logic is a build tool and is not shipped). Made before
# the blocking vulnerability check, so a failed release can still say what it would have shipped.
#
# scripts/release/sbom.sh <output file>
set -euo pipefail
root=$(git rev-parse --show-toplevel)
output=${1:?usage: sbom.sh <output file>}
mkdir -p "$(dirname "$output")"
trivy=$("$root/scripts/tool.sh" trivy)
cd "$root"
"$trivy" fs --skip-version-check --format cyclonedx --skip-dirs build-logic --output "$output" .
python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); assert d.get("bomFormat")=="CycloneDX" and d.get("components"), "empty SBOM"; print("sbom:", len(d["components"]), "components")' "$output"
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
# After `publish`: every module's maven-metadata.xml, fetched anonymously, lists the new version.
# Anonymous on purpose: consumers (the backend template, its image build) read without a token, so a
# package only the owner can read is not published.
#
# scripts/release/verify-published.sh <repository url> <group> <version> <artifact>...
set -euo pipefail
url=${1:?}; group=${2:?}; version=${3:?}; shift 3
[ $# -gt 0 ] || { echo "verify-published: no artifacts named" >&2; exit 2; }
path=${group//.//}
missing=0
for artifact in "$@"; do
metadata=$(curl --fail --show-error --silent --location --retry 3 "$url/$path/$artifact/maven-metadata.xml" || true)
if grep -q "<version>$version</version>" <<<"$metadata"; then
echo "published: $group:$artifact:$version"
else
echo "verify-published: $group:$artifact:$version is not in $url/$path/$artifact/maven-metadata.xml" >&2
missing=1
fi
done
exit "$missing"
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# The release's dependency gate over the committed lockfiles, the backend template's policy:
# 1. HIGH and CRITICAL fail.
# 2. MEDIUM and LOW are reported and do not fail.
# 3. Any finding listed in the CISA Known Exploited Vulnerabilities catalog fails, whatever its
# severity. An unreachable or malformed catalog fails too: a cross-check that did not run must
# not read as "no match".
# Suppressions: .trivyignore.yaml only (each entry with a statement and an expiry).
#
# scripts/release/vulnerability-scan.sh <report directory>
set -euo pipefail
root=$(git rev-parse --show-toplevel)
out=${1:?usage: vulnerability-scan.sh <report directory>}
mkdir -p "$out"
trivy=$("$root/scripts/tool.sh" trivy)
cd "$root"
"$trivy" fs --skip-version-check --scanners vuln --severity CRITICAL,HIGH --exit-code 1 --ignorefile .trivyignore.yaml .
"$trivy" fs --skip-version-check --scanners vuln --severity MEDIUM,LOW --exit-code 0 --ignorefile .trivyignore.yaml .
"$trivy" fs --skip-version-check --scanners vuln --severity CRITICAL,HIGH,MEDIUM,LOW,UNKNOWN --exit-code 0 \
--ignorefile .trivyignore.yaml --format json --output "$out/trivy-all.json" .
kev_url=${KEV_FEED_URL:-https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json}
if ! curl --fail --show-error --silent --location --retry 3 --proto '=https' --tlsv1.2 \
"$kev_url" --output "$out/kev.json"; then
echo "vulnerability-scan: KEV feed unavailable ($kev_url); set KEV_FEED_URL to an approved mirror." >&2
exit 1
fi
python3 - "$out/trivy-all.json" "$out/kev.json" <<'PY'
import json, re, sys
findings, kev = (json.load(open(p, encoding="utf-8")) for p in sys.argv[1:3])
ids = kev.get("vulnerabilities")
if not isinstance(ids, list) or not ids or kev.get("count") != len(ids):
sys.exit("vulnerability-scan: KEV feed is malformed, empty or count-inconsistent")
catalog = {v.get("cveID") for v in ids}
if not all(isinstance(c, str) and re.fullmatch(r"CVE-\d{4}-\d{4,}", c) for c in catalog):
sys.exit("vulnerability-scan: KEV feed holds an invalid cveID")
results = findings.get("Results")
if not isinstance(results, list) or not results:
sys.exit("vulnerability-scan: Trivy found no lockfile to scan")
found = {v["VulnerabilityID"] for r in results for v in (r.get("Vulnerabilities") or [])}
hits = sorted(found & catalog)
if hits:
sys.exit("vulnerability-scan: CISA KEV-listed vulnerability found regardless of severity: " + ", ".join(hits))
print(f"vulnerability-scan: {len(found)} finding(s) below HIGH, none in the KEV catalog ({len(catalog)} entries).")
PY
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Prints the path of a pinned, checksum-verified tool binary, downloading it once into
# ${TOOL_CACHE:-~/.cache/messaging-library}/<tool>-<version>/.
#
# scripts/tool.sh trivy
#
# A tool is a native binary, not a Maven artifact, so Gradle cannot resolve it; this is the one place
# that says which version and which bytes. A download whose SHA-256 differs from the one written here
# fails and leaves nothing behind. Exit codes: 0 = path printed, 1 = download or checksum failed,
# 2 = usage or unsupported machine.
set -euo pipefail
tool=${1:-}
case "$(uname -s)-$(uname -m)" in
Linux-x86_64) arch=amd64 ;;
Linux-aarch64 | Linux-arm64) arch=arm64 ;;
*) echo "tool.sh: unsupported machine $(uname -s)-$(uname -m)" >&2; exit 2 ;;
esac
case "$tool" in
trivy)
# Trivy 0.71.2, the version and checksums the backend template's dependency-vulnerability.yml pins.
version=0.71.2
[ "$arch" = amd64 ] && asset="trivy_${version}_Linux-64bit.tar.gz" || asset="trivy_${version}_Linux-ARM64.tar.gz"
[ "$arch" = amd64 ] \
&& sha256=0510e71e2fd39bf863856d499c8dc19feb4e7336546394c502a8f5cc7ab27460 \
|| sha256=fe1c7106e15a5365d485b098a8c338f91e3b7ba71cb0e4963b98a3a098763cfc
url="${TRIVY_DOWNLOAD_BASE_URL:-https://github.com/aquasecurity/trivy/releases/download/v${version}}/${asset}"
archive=1
;;
*) echo "usage: scripts/tool.sh trivy" >&2; exit 2 ;;
esac
dir="${TOOL_CACHE:-$HOME/.cache/messaging-library}/${tool}-${version}"
binary="$dir/$tool"
if [ ! -x "$binary" ]; then
mkdir -p "$dir"
tmp=$(mktemp "$dir/.download.XXXXXX")
trap 'rm -f "$tmp"' EXIT
curl --fail --show-error --silent --location --retry 3 --proto '=https' --tlsv1.2 "$url" --output "$tmp"
if ! printf '%s %s\n' "$sha256" "$tmp" | sha256sum -c - >/dev/null 2>&1; then
echo "tool.sh: $asset does not match the pinned SHA-256 $sha256" >&2
exit 1
fi
if [ "$archive" = 1 ]; then
tar -xzf "$tmp" -C "$dir" "$tool"
else
mv "$tmp" "$binary"
fi
chmod 0755 "$binary"
fi
printf '%s\n' "$binary"
+20 -16
View File
@@ -3,18 +3,20 @@
#
# scripts/verify.sh <단계> [--on here|<호스트>] [--log <이름>]
#
# 단계 무엇 채우는 곳
# docs 루트 지침·장부 검사 run_docs(뼈대에 기본 검사가 있다)
# unit 빠른 단위 시험 run_unit
# pr PR 전에 통과해야 하는 게이트 묶음 run_pr
# app 앱을 띄워 health와 기본 기능을 직접 확인 run_app
# 단계 무엇 Gradle
# docs 루트 지침·장부 검사 (없음)
# unit 모듈 check 전부(단위 시험·정적 분석·lane 포함) checkAll
# pr PR 단계 = pr.yml ci, verifyStrictLaneStages --dry-run
# main main 단계 = main.yml(Docker 필요) mainCheck
# release release.yml에서 올리기 직전까지(Docker 필요, 비밀 값 없이) releaseRehearsal
# 라이브러리라 띄울 앱이 없다. 템플릿 뼈대의 `app` 단계는 두지 않는다.
#
# --on <호스트>: 지금 작업 트리(커밋 안 된 변경 포함)를 패치로 그 호스트에 옮긴다. 기준 커밋에서 새 worktree를
# 만들어 패치를 적용하고, 트리 해시가 여기와 같은지 본 뒤 잠금 아래에서 같은 단계를 돌리고 worktree를 지운다.
# push하지 않는다. 기준 커밋은 원격 checkout이 fetch로 받을 수 있어야 한다(기본: origin/main과 갈라진 곳).
# 환경 변수: VERIFY_HOST(--on 기본값, 없으면 here), VERIFY_REMOTE_REPO(원격 checkout, 기본 ~/workspace/<repo 이름>),
# VERIFY_BASE_REF(기본 origin/main), VERIFY_LOCK(기본 /tmp/claude-gates/heavy.lock), VERIFY_SSH(기본 ssh).
# 종료 코드: 단계의 종료 코드. 2 = 사용법, 3 = 아직 채우지 않은 단계, 4 = 원격 준비 실패.
# 종료 코드: 단계의 종료 코드. 2 = 사용법, 4 = 원격 준비 실패.
set -euo pipefail
ROOT=$(git rev-parse --show-toplevel)
@@ -23,15 +25,10 @@ TMP_FILES=()
trap '[ ${#TMP_FILES[@]} -eq 0 ] || rm -f "${TMP_FILES[@]}"' EXIT # 빈 배열 + set -u는 옛 bash에서 오류다
usage() {
sed -n '2,19p' "$0" | sed 's/^# \{0,1\}//' >&2
sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//' >&2
exit 2
}
todo() {
echo "verify: '$1' 단계는 아직 정하지 않았다. scripts/verify.sh의 run_$1을 채운다." >&2
return 3
}
# ---------------------------------------------------------------- 단계 본문(프로젝트가 채운다)
run_docs() {
@@ -56,17 +53,24 @@ for n, line in enumerate(open(sys.argv[1], encoding="utf-8"), 1):
return "$rc"
}
run_unit() { todo unit; }
run_unit() { ./gradlew checkAll --console=plain; }
run_pr() { run_docs && run_unit && todo pr; }
run_pr() { run_docs && ./gradlew ci --console=plain && ./gradlew verifyStrictLaneStages --dry-run --console=plain; }
run_app() { todo app; }
run_main() { ./gradlew mainCheck --console=plain; }
# releaseCheck needs a release version and a commit id. The rehearsal uses 0.0.0 unless
# RELEASE_VERSION is given: a version no release tag (v1.0.0 onward) will ever name.
run_release() {
RELEASE_VERSION=${RELEASE_VERSION:-0.0.0} GIT_SHA=${GIT_SHA:-$(git rev-parse HEAD)} \
./gradlew releaseRehearsal --console=plain
}
# ---------------------------------------------------------------- 실행 위치
run_here() {
case "$1" in
docs | unit | pr | app) "run_$1" ;;
docs | unit | pr | main | release) "run_$1" ;;
*) usage ;;
esac
}
+4
View File
@@ -0,0 +1,4 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
empty=incomingCatalogForLibs0
+20
View File
@@ -0,0 +1,20 @@
// The library's one Gradle build. The repository root is the Gradle root: config/, gradle/ and
// build-logic/ sit next to the module family messaging/.
pluginManagement {
includeBuild('build-logic')
}
// ca.architecture-registry includes every module config/architecture/modules.json lists, at its
// source_path. A module the registry does not list is not part of the build.
plugins {
id 'ca.architecture-registry'
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
}
}
rootProject.name = 'messaging-library'