Shared Gradle conventions for JDK-based projects.
- Applies common plugins:
java,checkstyle,jacoco,spotless,errorprone, andpitest(unless disabled). - Configures Java toolchain, runtime launcher, and bytecode level (defaults to JDK 25 from any available vendor).
- The plugin itself targets Kotlin/JVM 17.
- Adds
mavenCentral()by default and can optionally addmavenLocal()(both configurable). - Sets Checkstyle tool version and uses the root project's
config/checkstylefiles when provided (bundled defaults otherwise); every project that applies the plugin shares them. - Sets JaCoCo tool version and enforces instruction coverage.
- Configures PIT mutation testing (
pitesttask, 95 % mutation threshold) for the resolved base package; it is not part ofcheck. - Configures Spotless for basic Java formatting (unused imports, import order, trailing whitespace, newline at EOF).
- Applies Spotless license header conventions when
LICENSE_HEADERexists in the project root. - Adds common compile/test dependencies (Lombok, JSpecify, JetBrains annotations, Error Prone/NullAway, JUnit Jupiter, AssertJ).
- Configures all
Testtasks to use JUnit Platform and adds JUnit Platform launcher astestRuntimeOnly. - Enables
sourcesJarandjavadocJargeneration. - Adds
maven-publishconventions by default (mavenJavapublication + optional GitHub Packages repository). - Resolves
leanish.conventions.basePackagefrom project config or infers it fromsrc/main/javapackage declarations. - Adds root-only helper tasks (
installGitHooks,setupProject) and makesbuilddepend oninstallGitHooks. - Makes
checkdepend on everyJacocoCoverageVerificationtask. - Declares configuration cache support on the Gradle Plugin Portal (isolated projects are not declared).
Use the Gradle Plugin Portal for released versions.
The examples below target 0.7.1. Until it is published, use the latest version available on the
Gradle Plugin Portal.
The plugin adds mavenCentral() by default to every project where it is applied.
The canonical plugin id is io.github.leanish.java-conventions.
build.gradle.kts:
plugins {
id("io.github.leanish.java-conventions") version "0.7.1"
}settings.gradle.kts:
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
}
plugins {
id("io.github.leanish.java-conventions") version "0.7.1"
}
}Apply it in each build.gradle.kts:
plugins {
id("io.github.leanish.java-conventions")
}If the plugin version is not published to the Gradle Plugin Portal yet:
- Publish this plugin locally:
This publishes the
./gradlew publishToMavenLocal
versionfrombuild.gradle.kts; request that exact version from the consumer. - Ensure consumer
settings.gradle(.kts)hasmavenLocal()inpluginManagement.repositories(before remote repositories) while testing local builds, for example:pluginManagement { repositories { mavenLocal() gradlePluginPortal() mavenCentral() } } - Do not use
pluginManagement { includeBuild("../java-conventions") }; consume by plugin id + version. - When you switch back to a released version, remove
mavenLocal()(or move it after remote repositories) to avoid resolving stale local artifacts.
If you want root-only tasks (installGitHooks, setupProject) in a multi-project build, apply the plugin in the root project too:
plugins {
id("io.github.leanish.java-conventions") version "0.7.1"
}A root project without src/main/java can't infer a base package, so build fails when it configures compileJava
there. Set leanish.conventions.basePackage for it. In the root gradle.properties the value reaches every subproject
too, so use it there only when every project's packages lie under that package (for example com.acme for
com.acme.app and com.acme.lib): NullAway's annotated packages and PIT's <package>.* targets include
subpackages. When the projects have unrelated packages, a shared value would point NullAway and PIT at the wrong code:
don't invent a common prefix just to make the root configure. Set the property in each project's own
gradle.properties instead (the root's included); a project's own file takes precedence over the root's.
Configure behavior through gradle.properties (or -P...):
# Repository conventions
leanish.conventions.repositories.mavenLocal.enabled=false
leanish.conventions.repositories.mavenCentral.enabled=true
# Publishing conventions
leanish.conventions.publishing.enabled=true
leanish.conventions.publishing.githubPackages.enabled=true
leanish.conventions.publishing.githubOwner=acme
leanish.conventions.publishing.developer.id=acme
leanish.conventions.publishing.developer.name=Acme Team
leanish.conventions.publishing.developer.url=https://github.com/acme
# Project conventions (optional override)
leanish.conventions.basePackage=io.github.leanish
# Mutation testing conventions
leanish.conventions.pitest.enabled=true
Environment variables are also supported, and they override gradle.properties / -P values:
JAVA_CONVENTIONS_MAVEN_LOCAL_ENABLEDJAVA_CONVENTIONS_MAVEN_CENTRAL_ENABLEDJAVA_CONVENTIONS_PITEST_ENABLEDJAVA_CONVENTIONS_PUBLISHING_ENABLEDJAVA_CONVENTIONS_PUBLISHING_GITHUB_PACKAGES_ENABLEDJAVA_CONVENTIONS_PUBLISHING_GITHUB_OWNERJAVA_CONVENTIONS_PUBLISHING_DEVELOPER_IDJAVA_CONVENTIONS_PUBLISHING_DEVELOPER_NAMEJAVA_CONVENTIONS_PUBLISHING_DEVELOPER_URLJAVA_CONVENTIONS_BASE_PACKAGEGITHUB_REPOSITORY_OWNER(highest precedence for publishing owner inference)
Wrapper plugins can import these names directly from
io.github.leanish.gradleconventions.ConventionProperties instead of duplicating string literals.
leanish.conventions.basePackage is optional:
- If configured, the plugin uses that value.
- If missing, the plugin infers it from
src/main/javapackage declarations, stores the inferred value in project extra properties, and logs the inference. - Each project infers its own value: a subproject doesn't take a parent's inferred value, although extra properties are
inherited. A value configured in a parent (
gradle.properties,-P, or an extra property set in its build script) still applies to its subprojects that don't set their own. - The plugin fails fast only when the property is blank or when it cannot infer any Java package.
Publishing repository/name/description conventions are derived from project metadata and are not configurable properties:
- GitHub repository defaults to
project.name - POM name defaults to
project.name - POM description defaults to
project.description(orproject.namewhen missing)
Publishing owner/developer metadata is optional:
leanish.conventions.publishing.githubOwnerresolves owner for GitHub URLs/repository.- Owner resolves by
GITHUB_REPOSITORY_OWNER, thenJAVA_CONVENTIONS_PUBLISHING_GITHUB_OWNER, thenleanish.conventions.publishing.githubOwner, thengroupwhen it matchesio.github.<owner>. - Developer fields (
id,name,url) are optional and independent; missing values are inferred from resolved owner when possible (id=<owner>,name=<owner>,url=https://github.com/<owner>), and thedevelopersblock is emitted only when all three resolve. - GitHub Packages credentials resolve by environment first (
GITHUB_ACTOR,GITHUB_TOKEN), then properties (gpr.user,gpr.key). - A blank
GITHUB_ACTOR,GITHUB_TOKENorGITHUB_REPOSITORY_OWNERcounts as unset (for example a secret a workflow run can't read), so the next source is used. A blankJAVA_CONVENTIONS_*variable or property fails the build when it is the value used: a string setting names the variable or property, a boolean one names the Gradle property.
- For Gradle Plugin Portal, set
gradle.publish.keyandgradle.publish.secretin~/.gradle/gradle.properties, or useGRADLE_PUBLISH_KEYandGRADLE_PUBLISH_SECRET. - Publish with
./gradlew publishPlugins. - For local testing, use
./gradlew publishToMavenLocal. - For GitHub Packages publishing of this plugin project:
- repository is
https://maven.pkg.github.com/leanish/java-conventions - credentials resolve by environment first (
GITHUB_ACTOR,GITHUB_TOKEN), then properties (gpr.user,gpr.key) - publish with
./gradlew publishAllPublicationsToGitHubPackagesRepository.
- repository is
Replace defaults with your own:
tasks.withType<JacocoCoverageVerification>().configureEach {
violationRules {
rules.forEach { rule ->
rule.limits.forEach { limit ->
limit.minimum = "0.83".toBigDecimal()
}
}
}
}Keep defaults and append more:
tasks.withType<JavaCompile>().configureEach {
options.errorprone {
errorproneArgs.add("-Xep:MissingOverride:WARN")
}
}Clear defaults, then define your own (google-java-format 1.37.0 needs Gradle running on JDK 21+):
spotless {
java {
clearSteps()
googleJavaFormat("1.37.0")
endWithNewline()
}
}- Default JDK version is 25; vendor is
ANY. - To change the vendor without changing the version:
java {
toolchain {
vendor.set(JvmVendorSpec.ADOPTIUM)
}
}- To change bytecode level:
tasks.withType<JavaCompile>().configureEach {
options.release.set(21)
}- The toolchain version and the bytecode level are set separately. To use an older toolchain (JDK 21 is the minimum),
lower the bytecode level with it:
options.releasestays at 25, which an olderjavacrejects (release version 25 not supported).
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
tasks.withType<JavaCompile>().configureEach {
options.release.set(21)
}- The plugin enables
sourcesJarandjavadocJarby default. - Consumers can disable them in
build.gradle.kts:
tasks.named("sourcesJar") {
enabled = false
}
tasks.named("javadocJar") {
enabled = false
}- If you also want to omit these artifacts from publications, skip the
sourcesElementsandjavadocElementsvariants:
components.named<AdhocComponentWithVariants>("java") {
withVariantsFromConfiguration(configurations["sourcesElements"]) { skip() }
withVariantsFromConfiguration(configurations["javadocElements"]) { skip() }
}- Enforces instruction coverage via
jacocoTestCoverageVerification. - Default minimum is
0.85unless overridden. - Set
-DexcludeTags=integration(or any other non-blank tags) to skip those tests and disable coverage verification. The same tags are excluded from mutation testing. jacocoTestCoverageVerificationruns when there is execution data, as JaCoCo does, and also without it when its class directories (additionalClassDirsincluded) contain loose.classfiles. So a project with classes and no tests fails it (0 % coverage; lower the minimum to0to accept that), while without execution data a project without loose classes (none, or only JARs given as class input) skips it. Classes with no measurable instructions (interfaces with only abstract methods, for example) pass. The conventions replace the task's run condition: a condition added before them is dropped, one added after them still applies. OtherJacocoCoverageVerificationtasks keep JaCoCo's behavior and skip when they have no execution data.
- Applies
info.solidsoft.pitest(gradle-pitest-plugin) with PIT and its JUnit 5 plugin, at the versions ingradle/libs.versions.toml. ./gradlew pitestwrites HTML and XML reports tobuild/reports/pitest(not timestamped).targetClassesandtargetTestsdefault to<package>.*for every package in the resolvedleanish.conventions.basePackage, so narrowingtargetClasseskeeps running every test under the base package.threadsdefaults to the number of available processors.- PIT runs on the same toolchain launcher as
Testtasks. JVM arguments ofTesttasks are not copied; setpitest { jvmArgs = listOf(...) }when the tests need them. - In multi-project builds, every project that applies the plugin gets its own
pitesttask, which by default mutates only that project's classes. Projects without mutable code failpitest(PIT'sfailWhenNoMutations); setpitest { failWhenNoMutations = false }there. Cross-project mutation and aggregated reports need extra gradle-pitest-plugin setup (additionalMutableCodePaths, theinfo.solidsoft.pitest.aggregatorplugin). mutationThresholddefaults to95:./gradlew pitestfails when the mutation score (as PIT rounds it) is below 95 %. Override it per project, or set it to0to report without failing.-DexcludeTagsleaves the threshold active.pitestis not wired intocheck, because a run takes noticeably longer than the tests. Run./gradlew pitestin a separate CI job; make that job optional for advisory feedback, or required to enforce the threshold.leanish.conventions.pitest.enabled=false(orJAVA_CONVENTIONS_PITEST_ENABLED=false) skips applying and configuring PIT: nopitesttask, so apitest { }block in the build script no longer compiles. A project that appliesinfo.solidsoft.pitestitself while the switch is off gets the plugin's own defaults.- Known warning: gradle-pitest-plugin
1.19.0callsConfiguration.setVisible(boolean), which Gradle 9.1+ deprecates. On Gradle 9.8.0, builds that apply it end with "Deprecated Gradle features were used in this build, making it incompatible with Gradle 10." (--warning-mode allshows the call, scheduled for removal in Gradle 11). It is only a warning under the default warning mode, but--warning-mode failturns it into a build failure. The fix is merged upstream (szpak/gradle-pitest-plugin#398) and these conventions will move to the first plugin release that includes it. Turning PIT off removes the warning.
pitest {
targetClasses = listOf("com.example.core.*")
mutationThreshold = 90
}Exact versions of everything the plugin injects or applies (dependencies, Checkstyle, JaCoCo, PIT, and the Spotless,
Error Prone and PIT Gradle plugins) live in gradle/libs.versions.toml; the copy at a
release tag is what that release uses.
- Adds
org.jspecify:jspecify,org.jetbrains:annotations, andcom.google.errorprone:error_prone_annotationsascompileOnlyandtestCompileOnly. - Adds
org.projectlombok:lombokascompileOnly,testCompileOnly,annotationProcessor, andtestAnnotationProcessor. - Sets a Guava
33.8.0-jreversion floor for Checkstyle and Error Prone to fixCVE-2026-102554andGHSA-v5x9-67m3-7m56. Consumer CheckstyletoolVersionoverrides remain supported. - Sets a commonmark
0.31.0version floor for Error Prone, whose google-java-format parses Markdown javadoc with it, to fix commonmark-java's denial-of-service advisories: it declarescommonmark-ext-gfm-tables0.31.0, which depends oncommonmark(core)0.31.0, so core resolves to at least that version too. A consumer that excludes the tables extension fromerrorproneneeds its own core floor. - Adds Error Prone analysis dependencies:
com.google.errorprone:error_prone_corecom.uber.nullaway:nullaway
- All
Testtasks calluseJUnitPlatform(). - The plugin adds
org.junit.jupiter:junit-jupiterandorg.assertj:assertj-coreastestImplementation. - The plugin adds
org.junit.platform:junit-platform-launcherastestRuntimeOnly. - If you need different test execution behavior for specific tasks, override those tasks in your build script.
Publishing conventions are enabled by default. To disable, set
leanish.conventions.publishing.enabled=false.
When enabled, the plugin:
- Applies
maven-publish. - Creates/configures
mavenJavapublication from the Java component. - Configures POM defaults from project metadata:
- repository and SCM use
https://github.com/<githubOwner>/<project.name>when owner is resolvable - POM
nameusesproject.name - POM
descriptionusesproject.description(or falls back toproject.name)
- repository and SCM use
- Adds GitHub Packages (
GitHubPackages) publishing repository only when:leanish.conventions.publishing.githubPackages.enabled=true(default), and- owner is resolvable.
Two supported patterns:
-
Keep conventions enabled and reconfigure existing entries.
- Reconfigure
mavenJavawithpublications.named("mavenJava", MavenPublication::class.java). - Reconfigure
GitHubPackageswithrepositories.named("GitHubPackages", MavenArtifactRepository::class.java). When the owner comes only from agroupset in the build script, the owner-dependent parts (POM URL, developer, SCM and theGitHubPackagesrepository) are added after the project is evaluated, sonamed(...)can't see the repository yet; set the owner explicitly, or userepositories.withType<MavenArtifactRepository>().matching { it.name == "GitHubPackages" }.configureEach { ... }. Override the POM URL or SCM there with.set(...): a.convention(...)from the build script is replaced by the owner-derived one, which is applied later. - Do not use
create<MavenPublication>("mavenJava")when conventions are enabled, becausemavenJavaalready exists.
- Reconfigure
-
Fully replace plugin publishing behavior.
- Set
leanish.conventions.publishing.enabled=false. - Configure
maven-publishentirely in the consumer project (publications { create(...) }, custom repositories, full POM metadata).
- Set
With the bundled Checkstyle configuration, Spotless orders imports the way its ImportOrder rule expects: static imports
first, then java, javax, org, com and everything else (for example lombok), one blank line between groups and
alphabetical within each. spotlessApply (and the pre-commit hook) fixes the order, so the IDE's import layout doesn't
matter. When the root project has its own config/checkstyle/checkstyle.xml, the plugin adds no import-order step; add
importOrder(...) to spotless { java { } } to match that config.
The plugin applies Spotless Java license headers only when LICENSE_HEADER exists in the project root.
When the file exists, the plugin:
- Applies Spotless Java license header step.
- Uses
LICENSE_HEADERfrom the project root.
When LICENSE_HEADER is missing, the plugin skips the header step and logs at INFO level.
There is no separate leanish.conventions.spotless.licenseHeader.enabled property; file presence controls behavior.
The conventions plugin applies net.ltgt.errorprone and adds Error Prone + NullAway dependencies automatically.
It:
- Adds
-XDaddTypeAnnotationsToSymbol=true. - Configures Error Prone with default arguments (including NullAway).
- Sets NullAway annotated packages from resolved
leanish.conventions.basePackage. - Disables Error Prone for
compileTestJava.
Runtime requirement: Error Prone runs as a
javacannotation processor and requires the Java compilation toolchain to be JDK 21 or newer. The default JDK 25 toolchain satisfies this. Overriding the toolchain below JDK 21 (e.g.java { toolchain { languageVersion.set(JavaLanguageVersion.of(17)) } }) will cause compilation to fail.
Fail-fast validation: The plugin validates the configured Java toolchain during configuration and fails early with a descriptive error when
languageVersion < 21.
- Checkstyle uses the tool version from
gradle/libs.versions.toml(checkstyle). - Checkstyle uses
config/checkstyle/checkstyle.xmlandconfig/checkstyle/suppressions.xmlfrom the root project when present; subprojects use the root's files, not their own. - If either file is missing, the plugin falls back to bundled defaults (
checkstyle.xmland empty suppressions). - The bundled
checkstyle.xmlrejects imports from Jackson 2'scom.fasterxml.jackson.coreandcom.fasterxml.jackson.databind(use Jackson 3'stools.jackson.*;com.fasterxml.jackson.annotationstays allowed). A project that still needs them can suppress that rule alone in itsconfig/checkstyle/suppressions.xml, for example<suppress id="jacksonTwoImport" files=".*"/>. - These files are materialized under
build/generated/checkstylefor Checkstyle only and are not packaged into JARs/publications. - Checkstyle runtime requirement: Checkstyle 14.x requires the Java toolchain used by the plugin's runtime launcher to be JDK 21 or newer. The default toolchain is JDK 25, which satisfies this. If you override the project Java toolchain to a version lower than JDK 21, Checkstyle tasks will fail even when the Gradle daemon itself runs on a newer JDK.
- The plugin does not add a toolchain resolver; ensure the configured JDK is available locally or add a resolver in the consuming project.
- Dependencies added by the plugin are additive; your project dependencies remain in effect.
- The bundled pre-commit hook runs
./gradlew spotlessApplyand./gradlew checkstyleMain checkstyleTeston the working copy, then refuses the commit if any staged file differs from its working copy: formatting changed it, or it has unstaged changes. It never stages anything itself: review the changes,git addthem and commit again. Committing part of a file's changes (partial staging) is therefore refused while the rest is unstaged; stash it first, or usegit commit --no-verify. installGitHooksinstallsscripts/git-hooks/pre-commitif the project has one, else the bundled hook, and keeps a pre-commit hook it didn't install (an installed hook edited locally, a symbolic link, or, when its bytes aren't a previously bundled hook's, a project hook a 0.6.x version installed whose source has changed since) with a warning; it records what it installed inpre-commit.java-conventions.sha256next to the hook, adopts a hook already identical to what it would install, and recognizes hooks bundled by earlier versions. To switch to the conventions' hook, deletepre-commitfrom the hooks directory (below) and runinstallGitHooks.installGitHooksasksgit(it must be on thePATH) where Git runs hooks:.git/hooks, or in a linked worktree the main repository's hooks directory, which all linked worktrees share (so a worktree with a differentscripts/git-hooks/pre-commitupdates the shared hook). Whencore.hooksPathis set, in the repository or globally, it installs nothing and leaves those hooks to you; set your owncore.hooksPathif worktrees need separate hooks. If git can't run or the lookup fails, it warns and skips.
- Checked-in Linux jobs run on
ubuntu-26.04, with Gradle9.9.1and the existing JDK baselines. .github/workflows/ci.ymlruns the default build path: compilation toolchain JDK 17 (Kotlin, and the Java toolchain it sets); Gradle runtime and the default test launcher on JDK 25..github/workflows/testing-legacy-jdk.ymlruns a matrix on legacy runtime JDKs (17,21).- The legacy matrix uses
-PjavaConventions.runtimeJdkVersion=<version>to set the plugin project's ownTestruntime launcher. javaConventions.runtimeJdkVersionis a plugin-project testing override only; it is not a consumer convention property..github/workflows/publishing-github.ymlrequires bothci.ymlandtesting-legacy-jdk.ymljobs to pass before publishing. It then calls the reusable.github/workflows/publishing-github-packages.yml(see below). The localpublishAllPublicationsToGitHubPackagesRepositorypath still runs Gradle with your credentials..github/workflows/publishing-github-packages.ymlis a reusable workflow (workflow_call) that publishes a Gradle build to the calling repository's GitHub Packages without Gradle ever holding a write token:- Its
preparejob (read-only; build code there can use its read token, so it can read any package that token may read) reads the version from the root project, builds and stages the publications inbuild/publication-staging, and hands them over as an artifact (one per attempt, kept 30 days). Itspublishjob holdspackages: write, runs no Gradle or repository code, and uploads exactly the files the coordinates and the version call for: each artifact with its.md5/.sha1/.sha256/.sha512, and nothing else. An identical remote file is skipped and a different one fails, so re-runningpublishalone completes a partial upload; an older SNAPSHOT build is never put over a newer one. GitHub Packages generates the Maven metadata itself. - A release must be dispatched from its
vX.Y.Ztag, and a tag publishes only the version it names. - Inputs:
coordinates(required; repository paths such asio/github/leanish/sqs-codec, space or newline separated; one ending in.gradle.pluginis a plugin marker, a POM only) andjava-versions(one per line, the last one runs Gradle; default25). Libraries publish.jar,-sources.jar,-javadoc.jar,.pomand.module. - The caller grants
contents: readandpackages: write(each job narrows them), runs its checks first, setsconcurrencyso one publish runs at a time, and its build declares aStagingMaven repository atbuild/publication-staging. Call it pinned by full commit SHA:uses: leanish/java-conventions/.github/workflows/publishing-github-packages.yml@<sha>. - A green run means the files are on the registry; it doesn't resolve them from a consumer.
- Its
- The build resolves
convention*configurations (conventionCheckstyle,conventionErrorprone, …) that mirror what the plugin injects into consumer builds, with the same Guava floor, so a dependency scan of this repository covers the versions consumers get. Nothing compiles against them;ConventionMirrorsTest(part ofcheck) applies the plugin to a consumer build and fails unless every consumer configuration the plugin declares something in has a mirror, and each of those configurations declares exactly the mirror's modules, at the same versions. .github/workflows/supply-chain.ymlruns the leanish/leanish-development gate: on a PR it fails what the change makes worse (new advisories, young versions, unpinned new actions), and it scansmainon every push and daily; an open PR is checked again only when it's reopened, updated, edited or re-run..github/dependency-floors.jsonrecords the Guava and commonmark floors, which the gate checks against what the build declares and resolves.