Skip to content

About

Shared Gradle conventions for Java projects

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

java-conventions

Shared Gradle conventions for JDK-based projects.

What it provides

  • Applies common plugins: java, checkstyle, jacoco, spotless, errorprone, and pitest (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 add mavenLocal() (both configurable).
  • Sets Checkstyle tool version and uses the root project's config/checkstyle files 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 (pitest task, 95 % mutation threshold) for the resolved base package; it is not part of check.
  • Configures Spotless for basic Java formatting (unused imports, import order, trailing whitespace, newline at EOF).
  • Applies Spotless license header conventions when LICENSE_HEADER exists in the project root.
  • Adds common compile/test dependencies (Lombok, JSpecify, JetBrains annotations, Error Prone/NullAway, JUnit Jupiter, AssertJ).
  • Configures all Test tasks to use JUnit Platform and adds JUnit Platform launcher as testRuntimeOnly.
  • Enables sourcesJar and javadocJar generation.
  • Adds maven-publish conventions by default (mavenJava publication + optional GitHub Packages repository).
  • Resolves leanish.conventions.basePackage from project config or infers it from src/main/java package declarations.
  • Adds root-only helper tasks (installGitHooks, setupProject) and makes build depend on installGitHooks.
  • Makes check depend on every JacocoCoverageVerification task.
  • Declares configuration cache support on the Gradle Plugin Portal (isolated projects are not declared).

How to use

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.

Single-project build

build.gradle.kts:

plugins {
    id("io.github.leanish.java-conventions") version "0.7.1"
}

Multi-project build

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")
}

Local development before release

If the plugin version is not published to the Gradle Plugin Portal yet:

  1. Publish this plugin locally:
    ./gradlew publishToMavenLocal
    This publishes the version from build.gradle.kts; request that exact version from the consumer.
  2. Ensure consumer settings.gradle(.kts) has mavenLocal() in pluginManagement.repositories (before remote repositories) while testing local builds, for example:
    pluginManagement {
        repositories {
            mavenLocal()
            gradlePluginPortal()
            mavenCentral()
        }
    }
  3. Do not use pluginManagement { includeBuild("../java-conventions") }; consume by plugin id + version.
  4. 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.

Convention properties

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_ENABLED
  • JAVA_CONVENTIONS_MAVEN_CENTRAL_ENABLED
  • JAVA_CONVENTIONS_PITEST_ENABLED
  • JAVA_CONVENTIONS_PUBLISHING_ENABLED
  • JAVA_CONVENTIONS_PUBLISHING_GITHUB_PACKAGES_ENABLED
  • JAVA_CONVENTIONS_PUBLISHING_GITHUB_OWNER
  • JAVA_CONVENTIONS_PUBLISHING_DEVELOPER_ID
  • JAVA_CONVENTIONS_PUBLISHING_DEVELOPER_NAME
  • JAVA_CONVENTIONS_PUBLISHING_DEVELOPER_URL
  • JAVA_CONVENTIONS_BASE_PACKAGE
  • GITHUB_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/java package 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 (or project.name when missing)

Publishing owner/developer metadata is optional:

  • leanish.conventions.publishing.githubOwner resolves owner for GitHub URLs/repository.
  • Owner resolves by GITHUB_REPOSITORY_OWNER, then JAVA_CONVENTIONS_PUBLISHING_GITHUB_OWNER, then leanish.conventions.publishing.githubOwner, then group when it matches io.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 the developers block 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_TOKEN or GITHUB_REPOSITORY_OWNER counts as unset (for example a secret a workflow run can't read), so the next source is used. A blank JAVA_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.

Publishing

  • For Gradle Plugin Portal, set gradle.publish.key and gradle.publish.secret in ~/.gradle/gradle.properties, or use GRADLE_PUBLISH_KEY and GRADLE_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.

Override patterns

Override existing values

Replace defaults with your own:

tasks.withType<JacocoCoverageVerification>().configureEach {
    violationRules {
        rules.forEach { rule ->
            rule.limits.forEach { limit ->
                limit.minimum = "0.83".toBigDecimal()
            }
        }
    }
}

Add to defaults

Keep defaults and append more:

tasks.withType<JavaCompile>().configureEach {
    options.errorprone {
        errorproneArgs.add("-Xep:MissingOverride:WARN")
    }
}

Reset and replace

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()
    }
}

JDK toolchain

  • 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.release stays at 25, which an older javac rejects (release version 25 not supported).
java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(21))
    }
}

tasks.withType<JavaCompile>().configureEach {
    options.release.set(21)
}

Sources and Javadocs artifacts

  • The plugin enables sourcesJar and javadocJar by 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 sourcesElements and javadocElements variants:
components.named<AdhocComponentWithVariants>("java") {
    withVariantsFromConfiguration(configurations["sourcesElements"]) { skip() }
    withVariantsFromConfiguration(configurations["javadocElements"]) { skip() }
}

Coverage behavior

  • Enforces instruction coverage via jacocoTestCoverageVerification.
  • Default minimum is 0.85 unless 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.
  • jacocoTestCoverageVerification runs when there is execution data, as JaCoCo does, and also without it when its class directories (additionalClassDirs included) contain loose .class files. So a project with classes and no tests fails it (0 % coverage; lower the minimum to 0 to 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. Other JacocoCoverageVerification tasks keep JaCoCo's behavior and skip when they have no execution data.

Mutation testing

  • Applies info.solidsoft.pitest (gradle-pitest-plugin) with PIT and its JUnit 5 plugin, at the versions in gradle/libs.versions.toml.
  • ./gradlew pitest writes HTML and XML reports to build/reports/pitest (not timestamped).
  • targetClasses and targetTests default to <package>.* for every package in the resolved leanish.conventions.basePackage, so narrowing targetClasses keeps running every test under the base package.
  • threads defaults to the number of available processors.
  • PIT runs on the same toolchain launcher as Test tasks. JVM arguments of Test tasks are not copied; set pitest { jvmArgs = listOf(...) } when the tests need them.
  • In multi-project builds, every project that applies the plugin gets its own pitest task, which by default mutates only that project's classes. Projects without mutable code fail pitest (PIT's failWhenNoMutations); set pitest { failWhenNoMutations = false } there. Cross-project mutation and aggregated reports need extra gradle-pitest-plugin setup (additionalMutableCodePaths, the info.solidsoft.pitest.aggregator plugin).
  • mutationThreshold defaults to 95: ./gradlew pitest fails when the mutation score (as PIT rounds it) is below 95 %. Override it per project, or set it to 0 to report without failing. -DexcludeTags leaves the threshold active.
  • pitest is not wired into check, because a run takes noticeably longer than the tests. Run ./gradlew pitest in a separate CI job; make that job optional for advisory feedback, or required to enforce the threshold.
  • leanish.conventions.pitest.enabled=false (or JAVA_CONVENTIONS_PITEST_ENABLED=false) skips applying and configuring PIT: no pitest task, so a pitest { } block in the build script no longer compiles. A project that applies info.solidsoft.pitest itself while the switch is off gets the plugin's own defaults.
  • Known warning: gradle-pitest-plugin 1.19.0 calls Configuration.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 all shows the call, scheduled for removal in Gradle 11). It is only a warning under the default warning mode, but --warning-mode fail turns 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
}

Dependency conventions

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, and com.google.errorprone:error_prone_annotations as compileOnly and testCompileOnly.
  • Adds org.projectlombok:lombok as compileOnly, testCompileOnly, annotationProcessor, and testAnnotationProcessor.
  • Sets a Guava 33.8.0-jre version floor for Checkstyle and Error Prone to fix CVE-2026-102554 and GHSA-v5x9-67m3-7m56. Consumer Checkstyle toolVersion overrides remain supported.
  • Sets a commonmark 0.31.0 version floor for Error Prone, whose google-java-format parses Markdown javadoc with it, to fix commonmark-java's denial-of-service advisories: it declares commonmark-ext-gfm-tables 0.31.0, which depends on commonmark (core) 0.31.0, so core resolves to at least that version too. A consumer that excludes the tables extension from errorprone needs its own core floor.
  • Adds Error Prone analysis dependencies:
    • com.google.errorprone:error_prone_core
    • com.uber.nullaway:nullaway

JUnit Platform

  • All Test tasks call useJUnitPlatform().
  • The plugin adds org.junit.jupiter:junit-jupiter and org.assertj:assertj-core as testImplementation.
  • The plugin adds org.junit.platform:junit-platform-launcher as testRuntimeOnly.
  • If you need different test execution behavior for specific tasks, override those tasks in your build script.

Maven Publish conventions

Publishing conventions are enabled by default. To disable, set leanish.conventions.publishing.enabled=false.

When enabled, the plugin:

  • Applies maven-publish.
  • Creates/configures mavenJava publication 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 name uses project.name
    • POM description uses project.description (or falls back to project.name)
  • Adds GitHub Packages (GitHubPackages) publishing repository only when:
    • leanish.conventions.publishing.githubPackages.enabled=true (default), and
    • owner is resolvable.

Overriding publishing

Two supported patterns:

  1. Keep conventions enabled and reconfigure existing entries.

    • Reconfigure mavenJava with publications.named("mavenJava", MavenPublication::class.java).
    • Reconfigure GitHubPackages with repositories.named("GitHubPackages", MavenArtifactRepository::class.java). When the owner comes only from a group set in the build script, the owner-dependent parts (POM URL, developer, SCM and the GitHubPackages repository) are added after the project is evaluated, so named(...) can't see the repository yet; set the owner explicitly, or use repositories.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, because mavenJava already exists.
  2. Fully replace plugin publishing behavior.

    • Set leanish.conventions.publishing.enabled=false.
    • Configure maven-publish entirely in the consumer project (publications { create(...) }, custom repositories, full POM metadata).

Import order

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.

License header conventions

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_HEADER from 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.

Error Prone

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 javac annotation 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.

Notes

  • Checkstyle uses the tool version from gradle/libs.versions.toml (checkstyle).
  • Checkstyle uses config/checkstyle/checkstyle.xml and config/checkstyle/suppressions.xml from 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.xml and empty suppressions).
  • The bundled checkstyle.xml rejects imports from Jackson 2's com.fasterxml.jackson.core and com.fasterxml.jackson.databind (use Jackson 3's tools.jackson.*; com.fasterxml.jackson.annotation stays allowed). A project that still needs them can suppress that rule alone in its config/checkstyle/suppressions.xml, for example <suppress id="jacksonTwoImport" files=".*"/>.
  • These files are materialized under build/generated/checkstyle for 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 spotlessApply and ./gradlew checkstyleMain checkstyleTest on 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 add them and commit again. Committing part of a file's changes (partial staging) is therefore refused while the rest is unstaged; stash it first, or use git commit --no-verify.
  • installGitHooks installs scripts/git-hooks/pre-commit if 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 in pre-commit.java-conventions.sha256 next 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, delete pre-commit from the hooks directory (below) and run installGitHooks.
  • installGitHooks asks git (it must be on the PATH) 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 different scripts/git-hooks/pre-commit updates the shared hook). When core.hooksPath is set, in the repository or globally, it installs nothing and leaves those hooks to you; set your own core.hooksPath if worktrees need separate hooks. If git can't run or the lookup fails, it warns and skips.

Plugin project CI (maintainers)

  • Checked-in Linux jobs run on ubuntu-26.04, with Gradle 9.9.1 and the existing JDK baselines.
  • .github/workflows/ci.yml runs 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.yml runs a matrix on legacy runtime JDKs (17, 21).
  • The legacy matrix uses -PjavaConventions.runtimeJdkVersion=<version> to set the plugin project's own Test runtime launcher.
  • javaConventions.runtimeJdkVersion is a plugin-project testing override only; it is not a consumer convention property.
  • .github/workflows/publishing-github.yml requires both ci.yml and testing-legacy-jdk.yml jobs to pass before publishing. It then calls the reusable .github/workflows/publishing-github-packages.yml (see below). The local publishAllPublicationsToGitHubPackagesRepository path still runs Gradle with your credentials.
  • .github/workflows/publishing-github-packages.yml is 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 prepare job (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 in build/publication-staging, and hands them over as an artifact (one per attempt, kept 30 days). Its publish job holds packages: 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-running publish alone 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.Z tag, and a tag publishes only the version it names.
    • Inputs: coordinates (required; repository paths such as io/github/leanish/sqs-codec, space or newline separated; one ending in .gradle.plugin is a plugin marker, a POM only) and java-versions (one per line, the last one runs Gradle; default 25). Libraries publish .jar, -sources.jar, -javadoc.jar, .pom and .module.
    • The caller grants contents: read and packages: write (each job narrows them), runs its checks first, sets concurrency so one publish runs at a time, and its build declares a Staging Maven repository at build/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.
  • 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 of check) 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.yml runs the leanish/leanish-development gate: on a PR it fails what the change makes worse (new advisories, young versions, unpinned new actions), and it scans main on every push and daily; an open PR is checked again only when it's reopened, updated, edited or re-run. .github/dependency-floors.json records the Guava and commonmark floors, which the gate checks against what the build declares and resolves.

About

Shared Gradle conventions for Java projects

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages