Code Monkey home page Code Monkey logo

gradle-errorprone-plugin's Introduction

gradle-errorprone-plugin

This plugin configures JavaCompile tasks to use the Error Prone compiler.

Requirements

This plugin requires using at least Gradle 5.2.

While JDK 8 is supported, it is recommended to use at least a JDK 9 compiler. See note below about JDK 8 support.

Usage

plugins {
    id("net.ltgt.errorprone") version "<plugin version>"
}

Note: snippets in this guide use features from the latest Gradle version, so beware if copy/pasting.

This plugin creates a configuration named errorprone, and configures the <sourceSet>AnnotationProcessor configuration for each source set to extend it. This allows configuring Error Prone dependencies from a single place.

Error Prone needs to be added as a dependency in this configuration:

repositories {
    mavenCentral()
}
dependencies {
    errorprone("com.google.errorprone:error_prone_core:$errorproneVersion")
}

CAUTION: Using a dynamic or changing version for Error Prone, such as latest.release or 2.+, means that your build could fail at any time, if a new version of Error Prone adds or enables new checks that your code would trigger.

Error Prone can then be configured on the JavaCompile tasks:

tasks.withType(JavaCompile).configureEach {
    options.errorprone.disableWarningsInGeneratedCode = true
}
with Kotlin DSL
import net.ltgt.gradle.errorprone.errorprone

tasks.withType<JavaCompile>().configureEach {
    options.errorprone.disableWarningsInGeneratedCode.set(true)
}

and can also be disabled altogether:

tasks.named("compileTestJava").configure {
    options.errorprone.enabled = false
}
with Kotlin DSL
tasks.named<JavaCompile>("compileTestJava") {
    options.errorprone.isEnabled.set(false)
}

Note that this plugin only enables Error Prone on tasks for source sets (i.e. compileJava for the main source set, compileTestJava for the test source set, and compileIntegTestJava for a custom integTest source set). If you're creating custom JavaCompile tasks, then you'll have to configure them manually to enable Error Prone:

tasks.register("compileCustom", JavaCompile) {
    source "src/custom/"
    include "**/*.java"
    classpath = configurations.custom
    sourceCompatibility = "8"
    targetCompatibility = "8"
    destinationDir = file("$buildDir/classes/custom")

    // Error Prone must be available in the annotation processor path
    options.annotationProcessorPath = configurations.errorprone
    // Enable Error Prone
    options.errorprone.enabled = true
    // It can then be configured for the task
    options.errorprone.disableWarningsInGeneratedCode = true
}
with Kotlin DSL
tasks.register<JavaCompile>("compileCustom") {
    source("src/custom/")
    include("**/*.java")
    classpath = configurations["custom"]
    sourceCompatibility = "8"
    targetCompatibility = "8"
    destinationDir = file("$buildDir/classes/custom")

    // Error Prone must be available in the annotation processor path
    options.annotationProcessorPath = configurations["errorprone"]
    // Enable Error Prone
    options.errorprone.isEnabled.set(true)
    // It can then be configured for the task
    options.errorprone.disableWarningsInGeneratedCode.set(true)
}

In Android projects, tasks cannot be configured until afterEvaluate due to how the Android Plugin for Gradle works:

afterEvaluate {
    tasks.withType(JavaCompile).configureEach {
        options.errorprone.disableWarningsInGeneratedCode = true
    }
}
with Kotlin DSL
afterEvaluate {
    tasks.withType<JavaCompile>().configureEach {
        options.errorprone.disableWarningsInGeneratedCode.set(true)
    }
}

JDK 8 support

Error Prone requires at least a JDK 9 compiler. When using JDK 8, you can configure a dependency on the Error Prone javac in the errorproneJavac configuration:

dependencies {
    errorproneJavac("com.google.errorprone:javac:9+181-r4173-1")
}

and the plugin will configure the JavaCompile tasks to use a forking compiler and will override the compiler by prepending the dependencies to the bootstrap classpath (using a -Xbootclasspath/p: JVM argument).

Alternatively, you can configure JavaCompile tasks to use such a JDK while still using JDK 8 for running Gradle:

tasks.withType(JavaCompile).configureEach {
    options.fork(javaHome: project.getProperty("jdk11home"))
}
with Kotlin DSL
tasks.withType<JavaCompile>().configureEach {
    options.fork = true
    options.forkOptions.javaHome = project.getProperty("jdk11home")
}

The plugin will try to detect those cases and won't configure the bootstrap classpath in this case, but to play safe it will actually ignore any task that forks and defines either a javaHome or an executable (this also means that it won't configure the bootstrap classpath if you're e.g. running Gradle with a more recent JDK and forking the compilation tasks to use JDK 8).

If you need it, you can configure the bootstrap classpath manually for those tasks that the plugin would have skipped:

someTask.configure {
    //

    inputs.files(configurations.errorproneJavac).withNormalizer(ClasspathNormalizer)
    doFirst {
        options.forkOptions.jvmArgs += "-Xbootclasspath/p:${configurations.errorproneJavac.asPath}"
    }
}
with Kotlin DSL
someTask.configure {
    //

    inputs.files(configurations.errorproneJavac).withNormalizer(ClasspathNormalizer::class)
    doFirst {
        options.forkOptions.jvmArgs.add("-Xbootclasspath/p:${configurations["errorproneJavac"].asPath}")
    }
}
(if you're using `forkOptions.executable`, then use `-J-Xbootclasspath/p:` instead.)

Migration from versions 0.0.x

If you relied on the default Error Prone dependency (which you shouldn't have, see warning above about changing versions), you'll have to configure it explicitly (see above). If you need to support building with JDK 8, you'll need to configure the Error Prone javac dependency (see above).

Contrary to versions 0.0.x, later versions use a DSL to configure Error Prone, and passing Error Prone-specific arguments to options.compilerArgs won't work. As an easy migration step, you can pass those arguments to options.errorprone.errorproneArgs instead:

  tasks.withType(JavaCompile).configureEach {
-     options.compilerArgs << "-Xlint:all" << "-Werror" << "-XepDisableWarningsInGeneratedCode"
-     options.compilerArgs << "-Xep:NullAway:ERROR" << "-XepOpt:NullAway:AnnotatedPackages=net.ltgt"
+     options.compilerArgs << "-Xlint:all" << "-Werror"
+     options.errorprone.errorproneArgs << "-XepDisableWarningsInGeneratedCode"
+     options.errorprone.errorproneArgs << "-Xep:NullAway:ERROR" << "-XepOpt:NullAway:AnnotatedPackages=com.uber"
  }

The next (optional) step would be to move to using the DSL:

  tasks.withType(JavaCompile).configureEach {
      options.compilerArgs << "-Xlint:all" << "-Werror"
-     options.errorprone.errorproneArgs << "-XepDisableWarningsInGeneratedCode"
-     options.errorprone.errorproneArgs << "-Xep:NullAway:ERROR" << "-XepOpt:NullAway:AnnotatedPackages=com.uber"
+     options.errorprone {
+         disableWarningsInGeneratedCode = true
+         error("NullAway")
+         option("NullAway:AnnotatedPackages", "net.ltgt")
+     }
  }

Finally, the net.ltgt.errorprone-base plugin is removed without replacement. In most cases, it can be replaced by disabling or enabling Error Prone on selected tasks.

Custom Error Prone checks

This requires Error Prone 2.3.0 or later.

Custom Error Prone checks can be added to the errorprone configuration too:

dependencies {
    errorprone("com.uber.nullaway:nullaway:$nullawayVersion")
}

or alternatively to the <sourceSet>AnnotationProcessor configuration, if they only need to be enabled for a given source set:

dependencies {
    annotationProcessor("com.google.guava:guava-beta-checker:$betaCheckerVersion")
}

and can then be configured on the tasks; for example:

tasks.withType(JavaCompile).configureEach {
    options.errorprone {
        option("NullAway:AnnotatedPackages", "net.ltgt")
    }
}
tasks.named("compileJava").configure {
    // The check defaults to a warning, bump it up to an error for the main sources
    options.errorprone.error("NullAway")
}
with Kotlin DSL
tasks.withType<JavaCompile>().configureEach {
    options.errorprone {
        option("NullAway:AnnotatedPackages", "net.ltgt")
    }
}
tasks.named("compileJava", JavaCompile::class) {
    // The check defaults to a warning, bump it up to an error for the main sources
    options.errorprone.error("NullAway")
}

Configuration

As noted above, this plugin adds an errorprone extension to the JavaCompile.options. It can be configured either as a property (options.errorprone.xxx = …) or script block (options.errorprone { … }).

In a *.gradle.kts script, the Kotlin extensions need to be imported:

import net.ltgt.gradle.errorprone.errorprone

Properties

Property Description
enabled (isEnabled with Kotlin DSL) Allows disabling Error Prone altogether for the task. Defaults to true.
disableAllChecks Disable all Error Prone checks. This will be the first argument, so checks can then be re-enabled on a case-by-case basis. Defaults to false.
allErrorsAsWarnings Defaults to false.
allDisabledChecksAsWarnings Enables all Error Prone checks, checks that are disabled by default are enabled as warnings. Defaults to false.
disableWarningsInGeneratedCode Disables warnings in classes annotated with javax.annotation.processing.Generated or @javax.annotation.Generated. Defaults to false.
ignoreUnknownCheckNames Defaults to false.
ignoreSuppressionAnnotations (since Error Prone 2.3.3) Defaults to false.
compilingTestOnlyCode (isCompilingTestOnlyCode with Kotlin DSL) Defaults to false. (defaults to true for a source set inferred as a test source set)
excludedPaths A regular expression pattern (as a string) of file paths to exclude from Error Prone checking. Defaults to null.
checks A map of check name to CheckSeverity, to configure which checks are enabled or disabled, and their severity. Defaults to an empty map.
checkOptions A map of check options to their value. Use an explicit "true" value for a boolean option. Defaults to an empty map.
errorproneArgs Additional arguments passed to Error Prone. Defaults to an empty list.
errorproneArgumentProviders A list of CommandLineArgumentProvider for additional arguments passed to Error Prone. Defaults to an empty list.

Methods

Method Description
enable(checkNames...) Adds checks with their default severity. Useful in combination with disableAllChecks to selectively re-enable checks.
disable(checkNames...) Disable checks.
warn(checkNames...) Adds checks with warning severity.
error(checkNames...) Adds checks with error severity.
check(checkName to severity...) (Kotlin DSL only) Adds pairs of check name to severity.
check(checkName, severity) Adds a check with a given severity. The severity can be passed as a provider for lazy configuration.
option(optionName) Enables a boolean check option. Equivalent to option(checkName, true).
option(optionName, value) Adds a check option with a given value. Value can be a boolean or a string, or a provider of string.

A check severity can take values: DEFAULT, OFF, WARN, or ERROR.
Note that the net.ltgt.gradle.errorprone.CheckSeverity needs to be imported into your build scripts (see examples above).

gradle-errorprone-plugin's People

Contributors

tbroyer avatar aalmiray avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.