build: 템플릿 밖에서 혼자 빌드·배포되는 Gradle 루트를 만든다
옮겨 온 gRPC 모듈은 템플릿의 두 번째 빌드(optional build)였다. 그 빌드는 템플릿 build-logic·카탈로그·registry·config를 상대 경로로 읽었고, grpc-operation-ledger-jpa는 템플릿 persistence-jpa의 testFixtures 파일 셋을 빌드 때 복사해 왔다. 별도 repo에는 그 경로가 없다. repo 루트를 Gradle 루트로 둔다. - build-logic: 템플릿 22df3525의 src/build-logic을 복사하고 쓰지 않는 플러그인(bootrun-dotenv, redis topology, config contract, spring-library, optional registry, purity 태스크)을 뺐다. 출처와 고친 곳은 build-logic/UPSTREAM.md에 적었다(설계 10.3절 L1). - registry config/architecture/modules.json: 템플릿의 optional-grpc 9행, source_path는 Gradle 루트 기준. - 카탈로그·config: 이 repo가 쓰는 항목만. SpotBugs 제외는 이 repo 클래스와 일반 규칙만 남겼다. - group은 gradle.properties의 libraryGroup(com.hyeonworks.grpc)에서 읽는다. 버전은 -PreleaseVersion 말고 RELEASE_TAG(vX.Y.Z)에서도 읽고, 다른 모양의 태그는 빌드 전에 거부한다. - 배포: 새 ca.library-publishing이 모듈마다 Maven publication(sources· javadoc jar, versionMapping으로 해석된 버전)과 저장소 gitea·staging, SIGNING_KEY가 있으면 PGP 서명을 단다. 루트는 SBOM artifact grpc-library와 단계 태스크 ci·mainCheck·releaseCheck·release· releaseRehearsal을 가진다. Trivy·Buf는 scripts/tool.sh가 SHA-256으로 고정해 받는다. - testFixtures 결합(설계 4.6절 2번)은 integrationTest 안 사본으로 끊었다. - Buf lint·breaking은 Gradle 태스크(scripts/buf.sh)로 ci에 넣었다. 버린 대안: build-logic을 템플릿이 배포(L2, 순환), 공통 repo(L3, repo가 하나 더), 표준 플러그인만으로 새로 쓰기(L4, strict lane과 방향 검사를 잃음). SBOM은 CycloneDX Gradle 플러그인 대신 이미 고정해 쓰는 Trivy로 만든다(도구를 늘리지 않는다). 위험: strictlane 단계 검사는 included build 태스크를 따라가다 실패해서 그 태스크를 건너뛰게 고쳤다(UPSTREAM.md). Gitea에 실제로 올리는 경로는 비밀 값이 없어 이 커밋에서는 시험하지 못했다. 검증(desktop, 이 트리): ./gradlew ci rc=0, 테스트 739개(build-logic 포함) 중 첫 실행 실패 1개(템플릿 경로를 찾던 GrpcPackageOwnershipTest)를 고친 뒤 통과. ./gradlew verifyStrictLaneStages --dry-run rc=0. Refs: design-docs repo-structure/05-library-repos.md 4.6·7·10절
This commit is contained in:
@@ -6,3 +6,11 @@
|
||||
.env.production
|
||||
|
||||
__pycache__/
|
||||
|
||||
# Gradle and IDE output
|
||||
.gradle/
|
||||
build/
|
||||
**/bin/
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
|
||||
@@ -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: []
|
||||
@@ -0,0 +1,8 @@
|
||||
# build-logic — 이 repo의 Gradle convention 플러그인
|
||||
|
||||
백엔드 템플릿 `src/build-logic/`의 사본이다. 출처와 뺀 것·고친 것은 `UPSTREAM.md`가 정본이다. 루트 `AGENTS.md`가 먼저다.
|
||||
|
||||
- 모듈은 `ca.platform-module`(Java 라이브러리 + 배포) 또는 `ca.grpc-platform-module`(위 + io.grpc BOM)을 쓴다. 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` 「템플릿 수정을 옮기는 법」을 따른다.
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,38 @@
|
||||
# build-logic의 출처 — 백엔드 템플릿에서 복사해 줄였다
|
||||
|
||||
- 복사한 곳: `clean-architecture-backend-template` main `22df3525`의 `src/build-logic/`(2026-11-08)
|
||||
- 함께 복사: `src/gradle/libs.versions.toml`(이 repo가 쓰는 항목만), `src/gradle/wrapper/`, `src/gradlew*`, `src/config/checkstyle/`, `src/config/spotbugs/`(이 repo 클래스와 일반 규칙만), `src/config/testing/container-images.properties`(`postgres-16`만)
|
||||
- 근거: design-docs `repo-structure/05-library-repos.md` 10.3절 L1(복사 후 줄이기). 다시 열 조건: 라이브러리 repo가 셋 이상이 되거나, 6개월 안에 템플릿에서 이 사본으로 옮긴 수정이 3번을 넘으면 공통 빌드 규칙 repo(L3)를 본다.
|
||||
|
||||
## 뺀 것
|
||||
|
||||
| 무엇 | 이유 |
|
||||
| --- | --- |
|
||||
| `ca.bootrun-dotenv`, `ca.redis-topology-lane`, `ca.config-contract`, `ca.spring-library` | 이 repo 모듈이 쓰지 않는다 |
|
||||
| `ca.optional-architecture-registry`, `MainBuild` | 템플릿 안 두 번째 빌드(optional build)를 위한 것. 여기서는 repo 루트가 곧 Gradle 루트다 |
|
||||
| `VerifyApplicationCoreDependencyPurityTask`(`ca.architecture` 안) | 템플릿 계층 이름(`domain-core`·`application-*`·`shared-contract`)에만 걸린다 |
|
||||
| `README.md`, 템플릿 `AGENTS.md` | 템플릿 빌드 설명이다. 이 폴더 `AGENTS.md`로 바꿨다 |
|
||||
| 위 플러그인의 테스트 | 플러그인과 함께 |
|
||||
|
||||
`ca.api-surface`는 남겼다. 설계 10.1절은 라이브러리 모듈에 켜기를 권하지만, 공개 타입 기준선 파일과 정책은 새 결정이라 아직 어느 모듈에도 켜지 않았다.
|
||||
|
||||
## 고친 것
|
||||
|
||||
| 파일 | 바뀐 점 |
|
||||
| --- | --- |
|
||||
| `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`)는 묻지 않는다. 템플릿 `ci`에는 그런 의존이 없어 드러나지 않았다. 템플릿에도 옮길 만한 수정이다 |
|
||||
| 새 `publishing/LibraryPublishingPlugin`(`ca.library-publishing`) | 모듈마다 Maven publication(sources·javadoc jar, 해석된 버전), 저장소 `gitea`·`staging`, `SIGNING_KEY`가 있으면 PGP 서명 |
|
||||
| 테스트 fixture | `source_path`를 Gradle 루트 기준으로, `PlatformModuleConventionTest`에 `libraryGroup` |
|
||||
|
||||
Java 패키지 `dev.caskeleton.buildlogic`은 그대로 두었다. 배포하지 않는 빌드 도구이고, 템플릿 파일과 나란히 비교하기 쉽게 하려는 것이다.
|
||||
|
||||
## 템플릿 수정을 옮기는 법
|
||||
|
||||
1. 템플릿에서 `git log --oneline 22df3525..main -- src/build-logic`으로 이후 변경을 본다.
|
||||
2. 위 「뺀 것」에 해당하지 않는 변경만 같은 파일에 옮긴다. 옮긴 커밋은 본문에 템플릿 커밋 SHA를 적는다.
|
||||
3. 옮긴 뒤 이 파일의 「복사한 곳」 커밋을 그 템플릿 커밋으로 바꾸고, 옮긴 횟수를 세어 다시 열 조건과 비교한다.
|
||||
@@ -0,0 +1,95 @@
|
||||
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'
|
||||
}
|
||||
grpcPlatformModuleConvention {
|
||||
id = 'ca.grpc-platform-module'
|
||||
implementationClass = 'dev.caskeleton.buildlogic.convention.GrpcPlatformModuleConventionPlugin'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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,298 @@
|
||||
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);
|
||||
String buildName = module.has("build") ? requireNonBlankText(module, "build", id) : "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);
|
||||
}
|
||||
}
|
||||
+63
@@ -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));
|
||||
});
|
||||
}
|
||||
}
|
||||
+89
@@ -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);
|
||||
}
|
||||
}
|
||||
+92
@@ -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());
|
||||
}
|
||||
}
|
||||
+201
@@ -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);
|
||||
}
|
||||
}
|
||||
+96
@@ -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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package dev.caskeleton.buildlogic.convention;
|
||||
|
||||
import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.Plugin;
|
||||
import org.gradle.api.Project;
|
||||
import org.gradle.api.artifacts.VersionCatalogsExtension;
|
||||
|
||||
public final class GrpcPlatformModuleConventionPlugin implements Plugin<Project> {
|
||||
@Override
|
||||
public void apply(Project project) {
|
||||
project.getPluginManager().apply("ca.platform-module");
|
||||
|
||||
var catalogs = project.getExtensions().getByType(VersionCatalogsExtension.class);
|
||||
var grpc =
|
||||
catalogs
|
||||
.named("libs")
|
||||
.findVersion("grpc")
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new GradleException(
|
||||
"Version catalog 'libs' must define version 'grpc' for ca.grpc-platform-module"));
|
||||
String grpcVersion = grpc.getRequiredVersion();
|
||||
DependencyManagementExtension dependencyManagement =
|
||||
project.getExtensions().getByType(DependencyManagementExtension.class);
|
||||
dependencyManagement.imports(imports -> imports.mavenBom("io.grpc:grpc-bom:" + grpcVersion));
|
||||
}
|
||||
}
|
||||
+13
@@ -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");
|
||||
}
|
||||
}
|
||||
+14
@@ -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");
|
||||
}
|
||||
}
|
||||
+44
@@ -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);
|
||||
}
|
||||
}
|
||||
+38
@@ -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");
|
||||
}
|
||||
}
|
||||
+39
@@ -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);
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package dev.caskeleton.buildlogic.publishing;
|
||||
|
||||
import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.Plugin;
|
||||
import org.gradle.api.Project;
|
||||
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.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 <PACKAGES_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) 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));
|
||||
|
||||
Provider<String> packagesUrl = project.getProviders().gradleProperty("packagesUrl");
|
||||
Provider<String> repositoryUrl = project.getProviders().gradleProperty("repositoryUrl");
|
||||
Provider<String> token = project.getProviders().environmentVariable("PACKAGES_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 = 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);
|
||||
}
|
||||
|
||||
// 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(
|
||||
"PACKAGES_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);
|
||||
}
|
||||
}
|
||||
+284
@@ -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();
|
||||
}
|
||||
}
|
||||
+63
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -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
+60
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -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);
|
||||
}
|
||||
}
|
||||
+322
@@ -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;
|
||||
}
|
||||
}
|
||||
+28
@@ -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);
|
||||
}
|
||||
}
|
||||
+473
@@ -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()
|
||||
+ "'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+209
@@ -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
|
||||
}
|
||||
+1410
File diff suppressed because it is too large
Load Diff
@@ -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,183 @@
|
||||
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 buildOwnershipDefaultsToMainAndCanSelectOptionalModules() throws Exception {
|
||||
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"}
|
||||
""");
|
||||
ModuleRegistry parsed = read(json);
|
||||
assertEquals("main", parsed.byId("app-bootstrap").buildName());
|
||||
assertEquals("optional-grpc", parsed.byId("grpc-client").buildName());
|
||||
assertEquals(List.of("app-bootstrap"), parsed.modulesForBuild("main").stream().map(ModuleRegistry.Module::id).toList());
|
||||
assertEquals(List.of("grpc-client"), parsed.modulesForBuild("optional-grpc").stream().map(ModuleRegistry.Module::id).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankBuildOwnershipIsRefused() {
|
||||
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("nonblank string 'build'"), 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));
|
||||
}
|
||||
}
|
||||
+199
@@ -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);
|
||||
}
|
||||
}
|
||||
+182
@@ -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);
|
||||
}
|
||||
}
|
||||
+122
@@ -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");
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
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(true);
|
||||
// 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 grpcConventionImportsBom() throws Exception {
|
||||
buildFile(
|
||||
"""
|
||||
plugins { id 'ca.grpc-platform-module' }
|
||||
tasks.register('reportManagedVersion') {
|
||||
String managed = dependencyManagement.managedVersions['io.grpc:grpc-api']
|
||||
doLast { logger.lifecycle('managed-grpc-api=' + managed) }
|
||||
}
|
||||
""");
|
||||
BuildResult result = runner("reportManagedVersion").build();
|
||||
assertTrue(result.getOutput().contains("managed-grpc-api=1.68.1"), result.getOutput());
|
||||
}
|
||||
|
||||
@Test
|
||||
void grpcConventionRefusesMissingVersion() throws Exception {
|
||||
writeCatalog(false);
|
||||
buildFile("plugins { id 'ca.grpc-platform-module' }\n");
|
||||
BuildResult result = runner("tasks").buildAndFail();
|
||||
assertTrue(
|
||||
result.getOutput().contains("Version catalog 'libs' must define version 'grpc'"),
|
||||
result.getOutput());
|
||||
}
|
||||
|
||||
@Test
|
||||
void grpcConventionBringsDependencyManagement() throws Exception {
|
||||
buildFile(
|
||||
"""
|
||||
plugins { id 'ca.grpc-platform-module' }
|
||||
tasks.register('reportDependencyManagement') {
|
||||
boolean present = project.extensions.findByName('dependencyManagement') != null
|
||||
doLast { logger.lifecycle('dependency-management-present=' + present) }
|
||||
}
|
||||
""");
|
||||
BuildResult result = runner("reportDependencyManagement").build();
|
||||
assertTrue(result.getOutput().contains("dependency-management-present=true"), 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(boolean grpc) 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"
|
||||
%s
|
||||
|
||||
[libraries]
|
||||
pinned-fixture = { module = "org.example:pinned-fixture", version = "2.0.1" }
|
||||
unpinned-fixture = { module = "org.example:unpinned-fixture", version = "1.0.0" }
|
||||
""".formatted(grpc ? "grpc = \"1.68.1\"" : ""));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+162
@@ -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);
|
||||
}
|
||||
}
|
||||
+783
@@ -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);
|
||||
}
|
||||
}
|
||||
+817
@@ -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();
|
||||
}
|
||||
}
|
||||
+1581
File diff suppressed because it is too large
Load Diff
+220
-48
@@ -1,92 +1,264 @@
|
||||
import dev.caskeleton.buildlogic.java.JavaConventionsPlugin
|
||||
|
||||
plugins {
|
||||
id 'ca.architecture'
|
||||
// Every strict lane of this build belongs to a stage a workflow executes, checked here exactly
|
||||
// as in the main build: the main build's check cannot see this build's lanes, and while only it
|
||||
// applied the plugin, grpcPerformanceTest ran nowhere (review 2026-11-03 RR-06-03).
|
||||
// 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, `grpc-library`, next to the modules.
|
||||
id 'maven-publish'
|
||||
id 'signing'
|
||||
}
|
||||
|
||||
// No `ca.release-provenance` any more: each gRPC leaf's `ca.java-conventions` derives its version
|
||||
// and `sourceRevision` from the same -PreleaseVersion/-PgitRevision (GIT_SHA, GITHUB_SHA) inputs the
|
||||
// main build reads, so one commit produces one version scheme in both builds (review BUILD-O3-5).
|
||||
// The modules: every leaf the registry includes (settings.gradle). The family projects `:grpc` and
|
||||
// `:grpc-advanced` are folders, not modules.
|
||||
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' : '')
|
||||
|
||||
tasks.register('resolveAndLockAll') {
|
||||
group = 'build setup'
|
||||
description = 'Regenerates dependency locks for every optional gRPC leaf (requires --write-locks).'
|
||||
dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:resolveAndLockAll" }
|
||||
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 gRPC optional-platform leaf check.'
|
||||
dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:check" }
|
||||
description = 'Runs every module check.'
|
||||
dependsOn leafPaths.collect { "${it}:check" }
|
||||
}
|
||||
|
||||
tasks.register('qualityCheck') {
|
||||
group = 'verification'
|
||||
description = 'Runs production-bytecode static analysis for every optional-platform leaf.'
|
||||
dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:qualityCheck" }
|
||||
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). This build has
|
||||
// no main stage, and the run is short (eleven tasks), so it joins `ci`.
|
||||
// SpotBugs + FindSecBugs over the test source sets (config/spotbugs/exclude-test.xml). Short here
|
||||
// (nine modules), so it joins `ci`.
|
||||
tasks.register('testQualityCheck') {
|
||||
group = 'verification'
|
||||
description = 'Runs test-code static analysis for every optional-platform leaf.'
|
||||
dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:testQualityCheck" }
|
||||
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). Buf lint and breaking-change policy run here rather than in each
|
||||
// module's `check`: Buf is a downloaded binary and the breaking check reads Git history, which a
|
||||
// local `./gradlew :grpc:grpc-contract:check` should not need.
|
||||
tasks.register('ci') {
|
||||
group = 'verification'
|
||||
description = 'Runs the optional gRPC platform verification surface.'
|
||||
description = 'The pull-request stage: module checks, architecture, static analysis, locks, Buf and build-logic tests.'
|
||||
dependsOn tasks.named('checkAll')
|
||||
dependsOn tasks.named('qualityCheck')
|
||||
dependsOn tasks.named('testQualityCheck')
|
||||
// architectureCheck, not only the direction gate: it also runs verifyNoIgnoredSourcePackages, so
|
||||
// a gRPC source Git would drop fails this build's ci the way it fails the main build's.
|
||||
dependsOn tasks.named('verifyDependencyLocks')
|
||||
// architectureCheck, not only the direction gate: it also runs verifyNoIgnoredSourcePackages.
|
||||
dependsOn tasks.named('architectureCheck')
|
||||
dependsOn ':grpc:grpc-contract:bufLint', ':grpc:grpc-contract:bufBreaking'
|
||||
dependsOn tasks.named('buildLogicTest')
|
||||
}
|
||||
|
||||
// A strict integration lane that no workflow invokes is not coverage; it is a file that looks like
|
||||
// coverage. `grpc-operation-ledger-jpa` declares a Testcontainers PostgreSQL lane that certifies the
|
||||
// atomic `INSERT ... ON CONFLICT DO NOTHING` claim the whole durable-idempotency contract rests on,
|
||||
// and until this aggregate existed `ci` reached `checkAll`, `qualityCheck` and the dependency
|
||||
// verifier only — none of which runs a lane whose category is INTEGRATION.
|
||||
//
|
||||
// Kept out of `ci`: every lane here starts a container, and `ci` is the per-PR gate for this build.
|
||||
// The caller is integration-main.yml, the stage that owns container-backed lanes.
|
||||
// Every module's integration lanes: grpc-operation-ledger-jpa's Testcontainers PostgreSQL lane, which
|
||||
// certifies the atomic `INSERT ... ON CONFLICT DO NOTHING` claim durable idempotency rests on. Needs a
|
||||
// container runtime.
|
||||
tasks.register('integrationCheck') {
|
||||
group = 'verification'
|
||||
description = 'Runs every optional-platform leaf integration test lane. Needs a container runtime.'
|
||||
dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:integrationTestLaneCheck" }
|
||||
description = 'Runs every module integration test lane. Needs a container runtime.'
|
||||
dependsOn leafPaths.collect { "${it}:integrationTestLaneCheck" }
|
||||
}
|
||||
|
||||
// The performance stage of this build: grpcPerformanceTest. It asserts the shape of a measurement
|
||||
// (ordered percentiles, a gate that reads them) with a generous budget, not a number, so it can run
|
||||
// on a shared runner. integration-main.yml's performance-check job runs it next to the main build's
|
||||
// `:performanceCheck`; before this aggregate it ran when somebody asked for it by name, which was
|
||||
// nobody (review 2026-11-03 RR-06-03).
|
||||
// grpcPerformanceTest asserts the shape of a measurement (ordered percentiles, a gate that reads
|
||||
// them) with a generous budget, not a number, so it can run on a shared runner.
|
||||
tasks.register('performanceCheck') {
|
||||
group = 'verification'
|
||||
description = 'Runs every optional-platform leaf performance test lane.'
|
||||
dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:performanceTestLaneCheck" }
|
||||
description = 'Runs every module performance test lane.'
|
||||
dependsOn leafPaths.collect { "${it}:performanceTestLaneCheck" }
|
||||
}
|
||||
|
||||
// The tag-only stage of this build: the hermetic strict lanes (the three gRPC certification lanes).
|
||||
// Their tests already run inside each leaf's `test`; the lanes add the one thing `test` cannot say —
|
||||
// that a tag still selects something — which is worth asserting once per release tag. release.yml
|
||||
// runs this aggregate instead of naming the lanes, so a lane added here is in the release gate
|
||||
// without a workflow edit.
|
||||
// The main-branch stage (main.yml): the pull-request stage again on the merged commit, plus the lanes
|
||||
// that start containers or measure.
|
||||
tasks.register('mainCheck') {
|
||||
group = 'verification'
|
||||
description = 'The main-branch stage: ci, integrationCheck and performanceCheck.'
|
||||
dependsOn tasks.named('ci')
|
||||
dependsOn tasks.named('integrationCheck')
|
||||
dependsOn tasks.named('performanceCheck')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- release (release.yml)
|
||||
|
||||
def sbomFile = layout.buildDirectory.file("release/grpc-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 = version.toString()
|
||||
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 certification lanes of every module (their tests already run in
|
||||
// `test`; a lane adds that its tag still selects something), the integration lanes, the version
|
||||
// check, the SBOM and the dependency gate. grpcPerformanceTest is not release evidence on a shared
|
||||
// runner and stays in mainCheck.
|
||||
tasks.register('releaseCheck') {
|
||||
group = 'verification'
|
||||
description = 'Runs every optional-platform leaf hermetic strict test lane (the release gate).'
|
||||
dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:testLaneCheck" }
|
||||
description = 'The release stage before publishing: certification and integration lanes, version, SBOM, dependency gate.'
|
||||
dependsOn tasks.named('verifyReleaseVersion')
|
||||
dependsOn leafPaths.collect { "${it}:testLaneCheck" }
|
||||
dependsOn tasks.named('integrationCheck')
|
||||
dependsOn tasks.named('releaseSbom')
|
||||
dependsOn tasks.named('dependencyVulnerabilityScan')
|
||||
}
|
||||
|
||||
// The stages this build's strict lanes may belong to, executed by workflows as
|
||||
// `./gradlew -p platforms/optional-build <stage>` from `src`. A command counts when it starts in this
|
||||
// directory (working-directory joined with -p), which the plugin reads from where this build is.
|
||||
publishing {
|
||||
publications {
|
||||
sbom(MavenPublication) {
|
||||
artifactId = 'grpc-library'
|
||||
artifact(sbomFile) {
|
||||
classifier = 'cyclonedx'
|
||||
extension = 'json'
|
||||
builtBy tasks.named('releaseSbom')
|
||||
}
|
||||
pom {
|
||||
name = 'grpc-library'
|
||||
description = 'CycloneDX SBOM of the grpc-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('PACKAGES_TOKEN').getOrElse('')}"
|
||||
}
|
||||
authentication {
|
||||
header(HttpHeaderAuthentication)
|
||||
}
|
||||
}
|
||||
maven {
|
||||
name = 'staging'
|
||||
url = layout.buildDirectory.dir('staging-repository')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def signingKey = providers.environmentVariable('SIGNING_KEY').getOrElse('')
|
||||
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('PACKAGES_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('PACKAGES_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')
|
||||
dependsOn(([path] + leafPaths).collect { "${it == ':' ? '' : it}:publishAllPublicationsToStagingRepository" })
|
||||
def staging = layout.buildDirectory.dir('staging-repository')
|
||||
def artifacts = leaves.collect { it.name }
|
||||
def coordinates = [group.toString(), version.toString()]
|
||||
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(([path] + leafPaths).collect { "${it == ':' ? '' : it}:publishAllPublicationsToGiteaRepository" })
|
||||
def url = providers.gradleProperty('packagesUrl')
|
||||
def artifacts = leaves.collect { it.name } + ['grpc-library']
|
||||
def coordinates = [group.toString(), version.toString()]
|
||||
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', ':integrationCheck', ':performanceCheck', ':releaseCheck'
|
||||
workflowDirectory = layout.projectDirectory.dir('../../../.github/workflows')
|
||||
stage ':ci', ':mainCheck', ':releaseCheck'
|
||||
workflowDirectory = layout.projectDirectory.dir('.gitea/workflows')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"modules": [
|
||||
{
|
||||
"id": "grpc-contract",
|
||||
"gradle_path": ":grpc:grpc-contract",
|
||||
"source_path": "grpc/grpc-contract",
|
||||
"allowed_dependencies": []
|
||||
},
|
||||
{
|
||||
"id": "grpc-core-api",
|
||||
"gradle_path": ":grpc:grpc-core-api",
|
||||
"source_path": "grpc/grpc-core-api",
|
||||
"allowed_dependencies": []
|
||||
},
|
||||
{
|
||||
"id": "grpc-observability",
|
||||
"gradle_path": ":grpc:grpc-observability",
|
||||
"source_path": "grpc/grpc-observability",
|
||||
"allowed_dependencies": [
|
||||
"grpc-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grpc-operation-ledger-jpa",
|
||||
"gradle_path": ":grpc:grpc-operation-ledger-jpa",
|
||||
"source_path": "grpc/grpc-operation-ledger-jpa",
|
||||
"allowed_dependencies": [
|
||||
"grpc-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grpc-runtime",
|
||||
"gradle_path": ":grpc:grpc-runtime",
|
||||
"source_path": "grpc/grpc-runtime",
|
||||
"allowed_dependencies": [
|
||||
"grpc-core-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grpc-spring-boot-starter",
|
||||
"gradle_path": ":grpc:grpc-spring-boot-starter",
|
||||
"source_path": "grpc/grpc-spring-boot-starter",
|
||||
"allowed_dependencies": [
|
||||
"grpc-core-api",
|
||||
"grpc-runtime",
|
||||
"grpc-observability"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grpc-testkit",
|
||||
"gradle_path": ":grpc:grpc-testkit",
|
||||
"source_path": "grpc/grpc-testkit",
|
||||
"allowed_dependencies": [
|
||||
"grpc-core-api",
|
||||
"grpc-runtime",
|
||||
"grpc-observability",
|
||||
"grpc-operation-ledger-jpa"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grpc-advanced",
|
||||
"gradle_path": ":grpc-advanced:grpc-advanced",
|
||||
"source_path": "grpc-advanced/grpc-advanced",
|
||||
"allowed_dependencies": [
|
||||
"grpc-core-api",
|
||||
"grpc-runtime"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "grpc-advanced-compat",
|
||||
"gradle_path": ":grpc-advanced:grpc-advanced-compat",
|
||||
"source_path": "grpc-advanced/grpc-advanced-compat",
|
||||
"allowed_dependencies": [
|
||||
"grpc-core-api",
|
||||
"grpc-runtime"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,64 @@
|
||||
<?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>
|
||||
</FindBugsFilter>
|
||||
@@ -0,0 +1,175 @@
|
||||
<?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>
|
||||
<!-- Generated sources (MapStruct / annotation processors): exclude from analysis. -->
|
||||
<Match>
|
||||
<Source name="~.*[\\/]generated[\\/].*" />
|
||||
</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>
|
||||
<!-- 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>
|
||||
<!-- CT group 2 — designed for extension. Exception hierarchy roots (HttpClientException,
|
||||
JpaPersistenceException, RedisOperationException, FileserverException and the optional
|
||||
gRPC build's GrpcPlatformException, which GrpcDeadlineExceededException extends, each have
|
||||
subclasses), ClientRuntime (BlockingClientRuntime extends it) and the abstract
|
||||
JpaRepositoryFragmentSupport, which service repository fragments extend. -->
|
||||
<Match>
|
||||
<Bug pattern="CT_CONSTRUCTOR_THROW" />
|
||||
<Or>
|
||||
<Class name="dev.caskeleton.grpc.api.error.GrpcPlatformException" />
|
||||
</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, and so do the
|
||||
gRPC identifiers (GrpcIdentifiers.requireBounded, 256); 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.grpc.core.GrpcChannelProfileName" />
|
||||
<Method name="<clinit>" />
|
||||
</And>
|
||||
<And>
|
||||
<Class name="dev.caskeleton.grpc.core.GrpcServiceName" />
|
||||
<Method name="<clinit>" />
|
||||
</And>
|
||||
</Or>
|
||||
</Match>
|
||||
<!-- FindSecBugs REDOS, the "x([class]*x)?" shape: GrpcMetadataKey.CANONICAL and
|
||||
GrpcResolverSafetyPolicy.AUTHORITY. The only unbounded quantifier sits in a group that
|
||||
repeats at most once, so a failing match gives back one character at a time from a single
|
||||
star — n steps, not 2^n. Measured with java.util.regex on 1k/10k/100k-unit inputs built to
|
||||
fail late ("a.a"... + "!"): time grows tenfold per tenfold input, 300k characters in under
|
||||
7 ms. The metadata key is also capped at 64 characters before the pattern runs; the
|
||||
resolver authority has no cap, and a linear match costs no more than reading the update. -->
|
||||
<Match>
|
||||
<Bug pattern="REDOS" />
|
||||
<Or>
|
||||
<And>
|
||||
<Class name="dev.caskeleton.grpc.api.context.GrpcMetadataKey" />
|
||||
<Method name="<clinit>" />
|
||||
</And>
|
||||
<And>
|
||||
<Class name="dev.caskeleton.grpc.advanced.discovery.GrpcResolverSafetyPolicy" />
|
||||
<Method name="<clinit>" />
|
||||
</And>
|
||||
</Or>
|
||||
</Match>
|
||||
<!-- FindSecBugs UNSAFE_HASH_EQUALS asks for a constant-time compare so that timing cannot leak a
|
||||
secret digest. None of these digests is a secret: content SHA-256 the uploader supplied or
|
||||
can compute (ContentPublishVerification, MetadataPointerContentPublisher,
|
||||
FinalizeUploadApplicationUseCase), an integrity digest of the record's own policy snapshot
|
||||
(ObjectOperationRecord), idempotency request/response digests the caller's own replay
|
||||
produces (PostgreSqlIdempotencyStore), and a configured worker identity used as a lease
|
||||
owner (PosterImageUploadIntent), and the gRPC channel profile fingerprints that
|
||||
GrpcPlatformSnapshotService.driftAgainstRelease compares between two snapshots it was
|
||||
handed — a configuration hash, published in the snapshot itself, compared offline with no
|
||||
caller to time it. A comparison that leaks what the caller already knows leaks nothing. -->
|
||||
<Match>
|
||||
<Bug pattern="UNSAFE_HASH_EQUALS" />
|
||||
<Or>
|
||||
<And>
|
||||
<Class name="dev.caskeleton.grpc.admin.GrpcPlatformSnapshotService" />
|
||||
<Method name="~lambda\$driftAgainstRelease\$\d+" />
|
||||
</And>
|
||||
</Or>
|
||||
</Match>
|
||||
<!-- COMMAND_INJECTION: GrpcTlsTestMaterial.runKeytool starts the running JDK's own keytool
|
||||
(java.home/bin) through ProcessBuilder with an argument list — no shell, so no argument is
|
||||
parsed as a command. Its callers pass fixed flags, paths of a temporary directory the
|
||||
fixture created, and the hostname a test names for its certificate. It lives in
|
||||
grpc-testkit, which no production leaf depends on. -->
|
||||
<Match>
|
||||
<Bug pattern="COMMAND_INJECTION" />
|
||||
<Class name="dev.caskeleton.grpc.testkit.netty.GrpcTlsTestMaterial" />
|
||||
<Method name="runKeytool" />
|
||||
</Match>
|
||||
</FindBugsFilter>
|
||||
@@ -0,0 +1,16 @@
|
||||
# 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. 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.
|
||||
#
|
||||
# Pulling through a mirror: set TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX in the environment, for example
|
||||
# `registry.internal/dockerhub/`.
|
||||
|
||||
# postgres:16-alpine — grpc-operation-ledger-jpa's integrationTest lane.
|
||||
postgres-16=postgres@sha256:0cefaabd882e42bcb2a2f3dc56d3ce4770560ba62fd7f197f1a2e008fd5731ab
|
||||
+7
-5
@@ -1,8 +1,10 @@
|
||||
# optional-platforms is a build of its own (`./gradlew -p platforms/optional-build ...`), and Gradle reads
|
||||
# gradle.properties from the build's root directory only, so src/gradle.properties never reached it:
|
||||
# the optional build ran serially and without the build cache (review 2026-11-01 08-06).
|
||||
# The values and their reasons are src/gradle.properties'. settings.gradle fails the build when the
|
||||
# two files disagree, so this is a copy that cannot drift, not a second source.
|
||||
# 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=com.hyeonworks.grpc
|
||||
packagesUrl=https://git.learn.hyeonworks.com/api/packages/donghyeon.kang/maven
|
||||
repositoryUrl=https://git.learn.hyeonworks.com/donghyeon.kang/grpc-library
|
||||
|
||||
# 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
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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, io.grpc) are not here; `grpc` below is the version of the BOM itself. `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"
|
||||
# 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"
|
||||
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 gRPC (33.2.1), Error
|
||||
# Prone (33.5.0) and the Checkstyle tool (33.6.0).
|
||||
guava = "33.7.2-jre"
|
||||
# io.grpc BOM. ca.grpc-platform-module imports it in the modules that apply that convention.
|
||||
grpc = "1.75.0"
|
||||
# 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"
|
||||
junitJupiter = "5.11.3"
|
||||
junitPlatform = "1.11.3"
|
||||
# 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"
|
||||
# protobuf-java for grpc:grpc-contract's generated messages. Keep it at the protobuf-java that
|
||||
# grpc-protobuf of the gRPC BOM above declares, so the schema runs on the runtime gRPC was built
|
||||
# against.
|
||||
protobufGrpc = "3.25.8"
|
||||
# The Gradle plugin that runs protoc for grpc:grpc-contract. protoc and the protobuf-java runtime
|
||||
# the generated code links against are both `protobufGrpc` above, so generator and runtime move
|
||||
# together with the gRPC BOM.
|
||||
protobufPlugin = "0.10.0"
|
||||
# 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"
|
||||
|
||||
[libraries]
|
||||
assertj-core = { module = "org.assertj:assertj-core", version.ref = "assertj" }
|
||||
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-grpc = { module = "com.google.protobuf:protobuf-java", version.ref = "protobufGrpc" }
|
||||
protoc = { module = "com.google.protobuf:protoc", version.ref = "protobufGrpc" }
|
||||
|
||||
pinned-guava = { module = "com.google.guava:guava", version.ref = "guava" }
|
||||
pinned-plexus-utils = { module = "org.codehaus.plexus:plexus-utils", version.ref = "plexusUtils" }
|
||||
|
||||
[plugins]
|
||||
protobuf = { id = "com.google.protobuf", version.ref = "protobufPlugin" }
|
||||
Vendored
BIN
Binary file not shown.
+8
@@ -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
|
||||
@@ -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
@@ -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,12 +1,11 @@
|
||||
# Buf module configuration for the Stable gRPC schema.
|
||||
#
|
||||
# Buf owns lint and breaking-change policy for src/main/proto; protoc (the Gradle protobuf plugin in
|
||||
# build.gradle) owns compilation. CI runs both `buf lint` and `buf breaking` from this directory —
|
||||
# see the `grpc-proto-buf` job in .github/workflows/ci-quality-gates.yml.
|
||||
# build.gradle) owns compilation. The root `ci` stage runs `buf lint` and `buf breaking` through
|
||||
# scripts/buf.sh:
|
||||
#
|
||||
# cd src/platforms/grpc/grpc-contract
|
||||
# buf lint
|
||||
# buf breaking --against '<baseline>#subdir=src/platforms/grpc/grpc-contract'
|
||||
# scripts/buf.sh lint (from the repository root; :grpc:grpc-contract:bufLint)
|
||||
# scripts/buf.sh breaking (:grpc:grpc-contract:bufBreaking)
|
||||
#
|
||||
# No dependencies: the only imports are protoc's own well-known types (google/protobuf/*.proto).
|
||||
version: v2
|
||||
|
||||
@@ -7,10 +7,12 @@ plugins {
|
||||
// from them.
|
||||
//
|
||||
// protoc, not a hand-written parser, decides whether the schema is valid, and Buf (buf.yaml next to
|
||||
// this file) owns lint and breaking-change policy. Buf runs in CI — `.github/workflows/
|
||||
// ci-quality-gates.yml` job `grpc-proto-buf` — because it is a native binary and not a Maven
|
||||
// artifact; this build does not re-implement its rules. Until 2026-09-28 this leaf was
|
||||
// grpc-proto-contract + grpc-codegen, which did both with regular expressions (owner decision 18).
|
||||
// this file) owns lint and breaking-change policy. Buf is a native binary and not a Maven
|
||||
// artifact, so bufLint and bufBreaking below run scripts/buf.sh (a pinned, checksum-verified
|
||||
// binary), and the root `ci` stage depends on them rather than this module's `check`: the breaking
|
||||
// check reads Git history and a download, which a local module check should not need. This build
|
||||
// does not re-implement Buf's rules. Until 2026-09-28 this leaf was grpc-proto-contract +
|
||||
// grpc-codegen, which did both with regular expressions (owner decision 18).
|
||||
//
|
||||
// Generated code lands under build/, in the package each file's `java_package` names
|
||||
// (`caskeleton.*.generated`), which is disjoint from the hand-written `dev.caskeleton` root.
|
||||
@@ -45,3 +47,19 @@ tasks.named('checkstyleMain') {
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.errorprone.excludedPaths = '.*/build/generated/.*'
|
||||
}
|
||||
|
||||
def protoSources = fileTree('src/main/proto') + files('buf.yaml')
|
||||
tasks.register('bufLint', Exec) {
|
||||
group = 'verification'
|
||||
description = 'Runs buf lint over the Stable schema (buf.yaml).'
|
||||
inputs.files(protoSources)
|
||||
outputs.upToDateWhen { false }
|
||||
commandLine 'bash', rootProject.file('scripts/buf.sh'), 'lint'
|
||||
}
|
||||
tasks.register('bufBreaking', Exec) {
|
||||
group = 'verification'
|
||||
description = 'Refuses a breaking change to the Stable schema against the baseline commit (scripts/buf.sh).'
|
||||
inputs.files(protoSources)
|
||||
outputs.upToDateWhen { false }
|
||||
commandLine 'bash', rootProject.file('scripts/buf.sh'), 'breaking'
|
||||
}
|
||||
|
||||
@@ -16,33 +16,13 @@ configurations {
|
||||
integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
|
||||
}
|
||||
|
||||
// One definition of a versioned migration file and of Flyway's order for both builds (re-review
|
||||
// README 12, r6-b; r9), and one concurrent index check (round 7, RR7-03-01). This build cannot
|
||||
// depend on persistence-jpa's testkit, so the files the ledger lanes need from it, all JDK only —
|
||||
// VersionedMigrationFiles, and ConcurrentIndexMigrationInspector with the MigrationResource it
|
||||
// takes — are copied from there into this lane's sources at build time instead of being kept here
|
||||
// as second copies that could drift.
|
||||
// Rejected: that testkit directory as a source root of this lane (Spotless refuses a target outside
|
||||
// this project's directory, and the include filter would cover this lane's own sources too), a
|
||||
// dependency on the main build (it would pull the whole main build into this one), and a test that
|
||||
// compares two copies (two definitions stay, and the test would have to parse Java source text).
|
||||
def sharedMigrationFileSources = tasks.register('sharedMigrationFileSources', Sync) {
|
||||
from(file('../../../adapter/outbound/persistence-jpa/src/testFixtures/java')) {
|
||||
include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/VersionedMigrationFiles.java'
|
||||
include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java'
|
||||
include 'dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java'
|
||||
}
|
||||
into(layout.buildDirectory.dir('generated/sources/sharedMigrationFiles/java'))
|
||||
}
|
||||
sourceSets.integrationTest.java.srcDir(sharedMigrationFileSources)
|
||||
// The copy is not this build's to format: Spotless here would name the generated file, and its
|
||||
// spotlessApply would rewrite only that copy, which the next Sync puts back (re-review 2026-11-03
|
||||
// round 6, RR6-03-04). The main build's persistence-jpa spotlessCheck formats the original.
|
||||
spotless {
|
||||
java {
|
||||
targetExclude('build/generated/sources/sharedMigrationFiles/**')
|
||||
}
|
||||
}
|
||||
// The ledger lanes need three JDK-only migration helpers that the backend template keeps in
|
||||
// adapter:outbound:persistence-jpa's testFixtures: VersionedMigrationFiles (Flyway's order of
|
||||
// versioned files), ConcurrentIndexMigrationInspector and the MigrationResource it takes. They live
|
||||
// here as copies in src/integrationTest/java/.../ledger/migration, an edge-less copy like the digest
|
||||
// helpers in grpc-runtime: this repository cannot depend on the template, and until the split the
|
||||
// build copied them in from the template's source tree by path, which a separate repository has
|
||||
// no path to. The template's files are the original; a fix there is copied here by hand.
|
||||
|
||||
// Durable mutation idempotency: the operation ledger entity, its state machine, the vendor-neutral
|
||||
// repository port and the Spring Data JPA binding, plus the migration that owns the unique
|
||||
|
||||
+2
-2
@@ -4,8 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
import static org.junit.jupiter.params.provider.Arguments.arguments;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.ConcurrentIndexMigrationInspector;
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationResource;
|
||||
import dev.caskeleton.grpc.ledger.migration.ConcurrentIndexMigrationInspector;
|
||||
import dev.caskeleton.grpc.ledger.migration.MigrationResource;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.grpc.ledger;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.testkit.migration.VersionedMigrationFiles;
|
||||
import dev.caskeleton.grpc.ledger.migration.VersionedMigrationFiles;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package dev.caskeleton.grpc.ledger.migration;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Requires a concurrent index statement to say that it runs outside a transaction, and to be alone
|
||||
* in its migration (design §32; {@code docs/jpa/migration-guide.md}, "Concurrent index builds").
|
||||
*
|
||||
* <p>PostgreSQL refuses {@code CREATE INDEX CONCURRENTLY}, {@code DROP INDEX CONCURRENTLY} and
|
||||
* {@code REINDEX ... CONCURRENTLY} inside a transaction block. Flyway 11 runs a script outside its
|
||||
* transaction on its own when it holds {@code CREATE} or {@code DROP INDEX CONCURRENTLY}, or {@code
|
||||
* REINDEX SCHEMA|DATABASE} with or without {@code CONCURRENTLY}. It runs {@code REINDEX INDEX|TABLE
|
||||
* ... CONCURRENTLY} — the option-list form {@code REINDEX (CONCURRENTLY) TABLE} included — in the
|
||||
* transaction, and PostgreSQL refuses it at deploy ({@code
|
||||
* postgresqlMigrationLockWaitIntegrationTest} shows the five forms; re-review 2026-11-03 round 7,
|
||||
* RR7-03-02). So {@link #validate} wants {@code executeInTransaction=false} beside every concurrent
|
||||
* statement, whether Flyway would detect it or not.
|
||||
*
|
||||
* <p>{@link #requireIsolatedStatement} wants the statement alone in its migration. Next to another
|
||||
* statement it is refused by Flyway before any of the script runs when nothing configures the file
|
||||
* (Flyway's default {@code mixed=false}); with the {@code executeInTransaction=false} that {@link
|
||||
* #validate} asks for, Flyway runs and commits each statement on its own, and a failed build leaves
|
||||
* the statements before it applied (round 7, RR7-03-04). Alone, a failed statement leaves an
|
||||
* invalid index and its version's failed history row, which Flyway refuses the next deploy over
|
||||
* until the row is gone: {@code docs/runbooks/migration-failed.md} ("Recover a failed concurrent
|
||||
* index migration") deletes that one row, after dropping the index a failed build or rebuild left.
|
||||
* A failed {@code DROP INDEX CONCURRENTLY} leaves invalid the index it was dropping, and the deploy
|
||||
* after the row is gone drops it ({@code postgresqlConcurrentIndexMigrationIntegrationTest} runs
|
||||
* all three; round 7, RR7-03-03; round 8, RR8-03-01).
|
||||
*
|
||||
* <p>Outside a transaction, {@code CREATE INDEX CONCURRENTLY} and {@code REINDEX ... CONCURRENTLY}
|
||||
* still wait for every transaction older than themselves. They finish because the template's Flyway
|
||||
* holds its PostgreSQL lock for the session ({@code FlywaySchemaPolicy.configure()}): under
|
||||
* Flyway's default the lock's own open transaction is one of those, and the deploy never ends
|
||||
* (re-review 2026-11-03 round 6, RR6-03-01 and RR6-03-05).
|
||||
*
|
||||
* <p>The gRPC ledger's lane uses it too. It lives in the optional build, which cannot depend on
|
||||
* this testkit, so {@code grpc-operation-ledger-jpa} compiles this file and {@link
|
||||
* MigrationResource} from here into its integration-test sources at build time (its {@code
|
||||
* build.gradle}, {@code sharedMigrationFileSources}; round 7, RR7-03-01). Hence the rule for both
|
||||
* files: the JDK only, nothing else from this testkit.
|
||||
*/
|
||||
public final class ConcurrentIndexMigrationInspector {
|
||||
|
||||
/**
|
||||
* A concurrent index statement in any spelling PostgreSQL accepts: {@code UNIQUE}, any
|
||||
* whitespace, and {@code CONCURRENTLY} after the object kind or, for {@code REINDEX}, in its
|
||||
* option list ({@code (CONCURRENTLY)}, {@code (VERBOSE, CONCURRENTLY true)}; not {@code
|
||||
* (CONCURRENTLY false)}).
|
||||
*/
|
||||
private static final Pattern CONCURRENT_STATEMENT =
|
||||
Pattern.compile(
|
||||
"\\b(?:create\\s+(?:unique\\s+)?index|drop\\s+index"
|
||||
+ "|reindex\\s*(?:\\([^)]*\\)\\s*)?(?:index|table|schema|database|system))"
|
||||
+ "\\s+concurrently\\b"
|
||||
+ "|\\breindex\\s*\\((?=[^)]*\\bconcurrently\\b(?!\\s*(?:false|off|0)\\b))");
|
||||
|
||||
/**
|
||||
* Fails when a migration containing a concurrent index statement is transactional.
|
||||
*
|
||||
* @param executeInTransaction whether Flyway will wrap this migration in a transaction
|
||||
* @throws IllegalStateException naming the migration and the required marker
|
||||
*/
|
||||
public void validate(MigrationResource migration, boolean executeInTransaction) {
|
||||
Objects.requireNonNull(migration, "migration");
|
||||
if (!executeInTransaction || !containsConcurrentIndexStatement(migration.sql())) {
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
migration.name()
|
||||
+ " must set executeInTransaction=false: PostgreSQL refuses a concurrent index"
|
||||
+ " statement inside a transaction block, and Flyway runs REINDEX INDEX|TABLE ..."
|
||||
+ " CONCURRENTLY in one unless the migration says otherwise");
|
||||
}
|
||||
|
||||
/** Whether the script contains a statement PostgreSQL forbids inside a transaction. */
|
||||
public boolean containsConcurrentIndexStatement(String sql) {
|
||||
if (sql == null) {
|
||||
return false;
|
||||
}
|
||||
return CONCURRENT_STATEMENT.matcher(sql.toLowerCase(Locale.ROOT)).find();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails when a concurrent-index migration also contains other statements.
|
||||
*
|
||||
* <p>A concurrent index statement can fail and leave an invalid index and its version's failed
|
||||
* history row behind. When the migration did nothing else, recovering is the runbook's few
|
||||
* statements: drop the index a failed build left, delete that one failed row, deploy again
|
||||
* ({@code docs/runbooks/migration-failed.md}, "Recover a failed concurrent index migration").
|
||||
* When it did more, Flyway ran the file outside a transaction and has committed the statements
|
||||
* before the failed one, and that partial state has to be reconstructed by hand.
|
||||
*/
|
||||
public void requireIsolatedStatement(MigrationResource migration) {
|
||||
Objects.requireNonNull(migration, "migration");
|
||||
if (!containsConcurrentIndexStatement(migration.sql())) {
|
||||
return;
|
||||
}
|
||||
long statements =
|
||||
migration
|
||||
.sql()
|
||||
.lines()
|
||||
.map(line -> line.trim())
|
||||
.filter(line -> !line.isEmpty() && !line.startsWith("--"))
|
||||
.filter(line -> line.endsWith(";"))
|
||||
.count();
|
||||
if (statements > 1L) {
|
||||
throw new IllegalStateException(
|
||||
migration.name()
|
||||
+ " mixes a concurrent index statement with other statements; outside a"
|
||||
+ " transaction Flyway commits each of them on its own, so a failed build leaves the"
|
||||
+ " others applied. Alone, a failed statement is recovered by deleting its version's"
|
||||
+ " failed history row (docs/runbooks/migration-failed.md, \"Recover a failed"
|
||||
+ " concurrent index migration\")");
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package dev.caskeleton.grpc.ledger.migration;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* One migration script as the inspector sees it (design §32).
|
||||
*
|
||||
* <p>The gRPC ledger's lane in the optional build compiles this file with {@link
|
||||
* ConcurrentIndexMigrationInspector} (see there), so it keeps to the JDK only.
|
||||
*
|
||||
* @param name the versioned script name, e.g. {@code V42__order_index.sql}
|
||||
* @param sql the script body
|
||||
*/
|
||||
public record MigrationResource(String name, String sql) {
|
||||
|
||||
public MigrationResource {
|
||||
Objects.requireNonNull(name, "name");
|
||||
Objects.requireNonNull(sql, "sql");
|
||||
if (name.isBlank()) {
|
||||
throw new IllegalArgumentException("migration name must not be blank");
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package dev.caskeleton.grpc.ledger.migration;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The versioned migrations of one tree, found the way Flyway finds them: {@code V}, a version whose
|
||||
* parts are separated by {@code _} or {@code .} ({@code V22}, {@code V22_1}, {@code V22.1}), two
|
||||
* underscores, a description, {@code .sql}. Repeatable ({@code R__}) and undo ({@code U}) scripts
|
||||
* and {@code .sql.conf} files are not versioned migrations.
|
||||
*
|
||||
* <p>One definition for every check that walks a tree — the operating trees' lock-wait and checksum
|
||||
* checks and the sample stream's. Two copies had drifted: the operating trees' skipped {@code
|
||||
* V22_1__} while the sample's counted it, so a decimal version in an operating tree was neither
|
||||
* pinned nor held to the lock-wait rule (re-review 2026-11-03 round 3, RR3-02-03).
|
||||
*
|
||||
* <p>The gRPC ledger's lanes use it too. They live in the optional build, which cannot depend on
|
||||
* this testkit, so {@code grpc-operation-ledger-jpa} compiles this one file from here into its
|
||||
* integration-test sources at build time (its {@code build.gradle}, {@code
|
||||
* sharedMigrationFileSources}) instead of keeping a copy that could drift (re-review README 12,
|
||||
* r6-b; r9). Hence the rule for this file: the JDK only, nothing else from this testkit.
|
||||
*/
|
||||
public final class VersionedMigrationFiles {
|
||||
|
||||
private static final Pattern VERSIONED = Pattern.compile("V\\d+(?:[._]\\d+)*__.+\\.sql");
|
||||
|
||||
private VersionedMigrationFiles() {}
|
||||
|
||||
/**
|
||||
* Every versioned migration below {@code root}, keyed by its path relative to {@code root} with
|
||||
* {@code /} separators ({@code postgresql/V22__...sql}).
|
||||
*/
|
||||
public static SortedMap<String, Path> under(Path root) throws IOException {
|
||||
Objects.requireNonNull(root, "root");
|
||||
SortedMap<String, Path> migrations = new TreeMap<>();
|
||||
try (Stream<Path> files = Files.walk(root)) {
|
||||
for (Path file : files.filter(VersionedMigrationFiles::isVersioned).toList()) {
|
||||
migrations.put(root.relativize(file).toString().replace('\\', '/'), file);
|
||||
}
|
||||
}
|
||||
return migrations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every versioned migration below {@code root} in the order Flyway applies them: by version, its
|
||||
* parts compared as numbers, a missing part as zero ({@code V2 < V2_1 < V2.10 < V10}, and {@code
|
||||
* V1} is {@code V1_0}).
|
||||
*
|
||||
* @throws IllegalStateException naming both files when two have the same version, which Flyway
|
||||
* refuses as well
|
||||
*/
|
||||
public static List<Path> inVersionOrder(Path root) throws IOException {
|
||||
List<Path> ordered = new ArrayList<>(under(root).values());
|
||||
ordered.sort((left, right) -> compareVersions(version(left), version(right)));
|
||||
for (int i = 1; i < ordered.size(); i++) {
|
||||
if (compareVersions(version(ordered.get(i - 1)), version(ordered.get(i))) == 0) {
|
||||
throw new IllegalStateException(
|
||||
ordered.get(i - 1).getFileName()
|
||||
+ " and "
|
||||
+ ordered.get(i).getFileName()
|
||||
+ " have the same version; Flyway refuses two migrations with one version");
|
||||
}
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
private static boolean isVersioned(Path file) {
|
||||
return VERSIONED.matcher(file.getFileName().toString()).matches();
|
||||
}
|
||||
|
||||
private static BigInteger[] version(Path file) {
|
||||
String name = file.getFileName().toString();
|
||||
return Arrays.stream(name.substring(1, name.indexOf("__")).split("[._]"))
|
||||
.map(BigInteger::new)
|
||||
.toArray(BigInteger[]::new);
|
||||
}
|
||||
|
||||
private static int compareVersions(BigInteger[] left, BigInteger[] right) {
|
||||
for (int i = 0; i < Math.max(left.length, right.length); i++) {
|
||||
BigInteger l = i < left.length ? left[i] : BigInteger.ZERO;
|
||||
BigInteger r = i < right.length ? right[i] : BigInteger.ZERO;
|
||||
int compared = l.compareTo(r);
|
||||
if (compared != 0) {
|
||||
return compared;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -20,7 +20,7 @@ class GrpcPackageOwnershipTest {
|
||||
List<String> leaves = List.of("grpc-core-api", "grpc-runtime", "grpc-operation-ledger-jpa");
|
||||
Map<String, List<String>> owners = new LinkedHashMap<>();
|
||||
for (String leaf : leaves) {
|
||||
Path source = repo.resolve("src/platforms/grpc").resolve(leaf).resolve("src/main/java");
|
||||
Path source = repo.resolve("grpc").resolve(leaf).resolve("src/main/java");
|
||||
try (var files = Files.walk(source)) {
|
||||
for (Path file : files.filter(path -> path.toString().endsWith(".java")).toList()) {
|
||||
var matcher = PACKAGE.matcher(Files.readString(file));
|
||||
@@ -44,7 +44,7 @@ class GrpcPackageOwnershipTest {
|
||||
private static Path repositoryRoot() {
|
||||
Path candidate = Path.of("").toAbsolutePath();
|
||||
while (candidate != null
|
||||
&& !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) {
|
||||
&& !Files.isRegularFile(candidate.resolve("config/architecture/modules.json"))) {
|
||||
candidate = candidate.getParent();
|
||||
}
|
||||
if (candidate == null) {
|
||||
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# Buf lint and breaking-change policy for the Stable gRPC schema (grpc/grpc-contract, buf.yaml there).
|
||||
#
|
||||
# scripts/buf.sh lint
|
||||
# scripts/buf.sh breaking
|
||||
#
|
||||
# protoc (the Gradle protobuf plugin) compiles the schema; Buf owns lint and breaking policy. The
|
||||
# root `ci` stage runs both through :grpc:grpc-contract:bufLint and :bufBreaking.
|
||||
#
|
||||
# breaking compares the working tree with a baseline commit:
|
||||
# BUF_AGAINST set → that ref
|
||||
# a pull request (GITHUB_BASE_REF) → the merge base with origin/<base>
|
||||
# otherwise → the merge base with origin/main, or HEAD^ when HEAD is on it
|
||||
# (or when a local clone has no origin/main)
|
||||
# A baseline without grpc/grpc-contract/buf.yaml has nothing to be compatible with, and the check
|
||||
# says so and passes. A baseline Git cannot find fails: a shallow clone cannot answer the question.
|
||||
set -euo pipefail
|
||||
|
||||
root=$(git rev-parse --show-toplevel)
|
||||
module=grpc/grpc-contract
|
||||
buf=$("$root/scripts/tool.sh" buf)
|
||||
cd "$root/$module"
|
||||
|
||||
case "${1:-}" in
|
||||
lint)
|
||||
"$buf" lint
|
||||
;;
|
||||
breaking)
|
||||
if [ -n "${BUF_AGAINST:-}" ]; then
|
||||
baseline=$BUF_AGAINST
|
||||
else
|
||||
base_branch="origin/${GITHUB_BASE_REF:-main}"
|
||||
if git rev-parse --verify --quiet "$base_branch^{commit}" >/dev/null; then
|
||||
baseline=$(git merge-base HEAD "$base_branch")
|
||||
elif [ "${GITHUB_ACTIONS:-}" = true ]; then
|
||||
# In CI the base branch must be there; a missing one means a shallow checkout, and comparing
|
||||
# with something else would answer a different question.
|
||||
echo "buf.sh: $base_branch is not in this clone; fetch it (actions/checkout fetch-depth: 0)." >&2
|
||||
exit 1
|
||||
else
|
||||
echo "buf.sh: no $base_branch here; comparing with HEAD^ (set BUF_AGAINST to choose)."
|
||||
baseline=$(git rev-parse HEAD)
|
||||
fi
|
||||
if [ -z "${GITHUB_BASE_REF:-}" ] && [ "$baseline" = "$(git rev-parse HEAD)" ]; then
|
||||
baseline=$(git rev-parse --verify --quiet 'HEAD^' || true)
|
||||
fi
|
||||
fi
|
||||
commit=$(git rev-parse --verify --quiet "${baseline}^{commit}" || true)
|
||||
if [ -z "$commit" ]; then
|
||||
echo "buf.sh: no baseline commit for '${baseline:-HEAD^}'; nothing to compare (first commit)." >&2
|
||||
[ -z "${baseline:-}" ] && exit 0 || exit 1
|
||||
fi
|
||||
if ! git cat-file -e "$commit:$module/buf.yaml" 2>/dev/null; then
|
||||
echo "buf.sh: baseline ${commit:0:12} has no $module/buf.yaml; breaking check skipped."
|
||||
exit 0
|
||||
fi
|
||||
echo "buf.sh: breaking against ${commit:0:12}"
|
||||
"$buf" breaking --against "$root/.git#ref=$commit,subdir=$module"
|
||||
;;
|
||||
*)
|
||||
echo "usage: scripts/buf.sh lint|breaking" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -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
|
||||
(grpc-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:] + ["grpc-library"]:
|
||||
directory = repository / group.replace(".", "/") / artifact / version
|
||||
base = directory / f"{artifact}-{version}"
|
||||
problems: list[str] = []
|
||||
if artifact == "grpc-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())
|
||||
Executable
+15
@@ -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 --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"
|
||||
Executable
+22
@@ -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"
|
||||
Executable
+47
@@ -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 --scanners vuln --severity CRITICAL,HIGH --exit-code 1 --ignorefile .trivyignore.yaml .
|
||||
"$trivy" fs --scanners vuln --severity MEDIUM,LOW --exit-code 0 --ignorefile .trivyignore.yaml .
|
||||
"$trivy" fs --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
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prints the path of a pinned, checksum-verified tool binary, downloading it once into
|
||||
# ${TOOL_CACHE:-~/.cache/grpc-library}/<tool>-<version>/.
|
||||
#
|
||||
# scripts/tool.sh buf|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
|
||||
buf)
|
||||
# Buf 1.73.0, the version the backend template's grpc-proto-buf job ran.
|
||||
version=1.73.0
|
||||
[ "$arch" = amd64 ] && asset=buf-Linux-x86_64 || asset=buf-Linux-aarch64
|
||||
[ "$arch" = amd64 ] \
|
||||
&& sha256=8f2986298ad08f0cc1bf999b9797b7c383adf32d7edf0f73d6f1e1a701baeac1 \
|
||||
|| sha256=902b75267db7f4391e99b7fa0756050e5354234cc0437ef50eee9c788950c7a3
|
||||
url="https://github.com/bufbuild/buf/releases/download/v${version}/${asset}"
|
||||
archive=0
|
||||
;;
|
||||
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 buf|trivy" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
dir="${TOOL_CACHE:-$HOME/.cache/grpc-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"
|
||||
+7
-23
@@ -1,9 +1,13 @@
|
||||
// The library's one Gradle build. The repository root is the Gradle root: config/, gradle/ and
|
||||
// build-logic/ sit next to the module families grpc/ and grpc-advanced/.
|
||||
pluginManagement {
|
||||
includeBuild('../../build-logic')
|
||||
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.optional-architecture-registry'
|
||||
id 'ca.architecture-registry'
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
@@ -11,26 +15,6 @@ dependencyResolutionManagement {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
versionCatalogs {
|
||||
libs {
|
||||
from(files('../../gradle/libs.versions.toml'))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = 'optional-platforms'
|
||||
|
||||
// gradle.properties here must say what src/gradle.properties says (review 2026-11-01 08-06): Gradle
|
||||
// reads only this build's own file, and a copy that drifted would make the optional build quietly
|
||||
// slower or differently configured than the main one.
|
||||
def readBuildProperties = { File file ->
|
||||
def properties = new Properties()
|
||||
file.withInputStream { properties.load(it) }
|
||||
properties
|
||||
}
|
||||
def mainBuildProperties = readBuildProperties(new File(settingsDir, '../../gradle.properties'))
|
||||
def ownBuildProperties = readBuildProperties(new File(settingsDir, 'gradle.properties'))
|
||||
if (mainBuildProperties != ownBuildProperties) {
|
||||
throw new GradleException("platforms/optional-build/gradle.properties differs from src/gradle.properties: " +
|
||||
"${ownBuildProperties} vs ${mainBuildProperties}. Copy the main build's values.")
|
||||
}
|
||||
rootProject.name = 'grpc-library'
|
||||
|
||||
Reference in New Issue
Block a user