Awesome
gradle-animalsniffer-plugin
About
Gradle AnimalSniffer plugin for Java, Groovy (only with @CompileStatic
!),
Kotlin or Scala projects (may work with other jvm-based languages too).
Initially, AnimalSniffer was created to check compatibility with lower Java versions
(to prevent situations when newer API methods called).
But it's a general tool: signatures could be created for any library to check api compatibility against older library versions. For example, AnimalSniffer was adopted by Android community to verify lower android SDK compatibility.
Plugin implemented in the same way as core Gradle quality plugins (Checkstyle, PMD, etc.):
Verification task is registered for each source set (animalsnifferMain, animalsnifferTest) and attached to the check
task.
Advanced features:
- Signature build task
- Check task classpath caching to speed-up subsequent checks (useful when check runs often without clean)
- Merging check signatures (when small 3rd party lib signatures are used)
- Viewing signature content task
Used by:
- Mockito for java and android compatibility checks
- Okhttp for java and android compatibility checks (using kotlin multiplatform)
Applicability
NOTE: JDK 9+ signatires are not published:
Starting with JDK9+ you can't define a full API signature cause based on the module system you can define your own (limited view on JDK). Apart from that you can use the release configuration in maven-compiler-plugin with JDK9+ to have exactly what animal sniffer offers and that's the reason why there are no JDK9+ signatures.
To check JDK 9+ compatibility use --release flag instead of plugin (or build signatures manually with maven plugin):
compileJava {
options.release = 11
}
Plugin could still be useful:
- For Android projects to check API compatibility (because Android API signatures are published).
- To check strong compatibility with some library: you'll need to generate signatures for this library and will be able to use them to check project compatibility (on API level, ofc) with older library versions.
Summary
- Configuration extensions:
animalsniffer
- check configurationanimalsnifferSignature
- signature build configuration (optional)
- Tasks:
check[Main]
- check source set taskanimalsnifferSignature
- build signature (active whenanimalsnifferSignature
configuration declared)type:BuildSignatureTask
- custom signature build task may be used to merge signaturestype:SignatureInfoTask
- view signature "contents"
- Dependencies configuration:
signature
- signatures for check
Setup
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.7.2'
}
}
apply plugin: 'ru.vyarus.animalsniffer'
OR
plugins {
id 'ru.vyarus.animalsniffer' version '1.7.2'
}
Example projects (with intentional errors to see output):
- Java (including android signatures)
- Groovy
- Kotlin
- Scala
- Signature build examples
Compatibility
IMPORTANT: Plugin only works when java-base
plugin (activated by any java-related plugin like java-library
, groovy
, scala
, org.jetbrains.kotlin.jvm
, etc.) is enabled,
otherwise nothing will be registered.
Currently, there is no support for the Android plugin (java-base
plugin must be used to perform animalsniffer check),
but android support will be released with the next version.
For kotlin multiplatform plugin enable java support:
kotlin {
jvm().withJava()
}
The plugin is compiled for Java 8, and is compatible with Java 11.
Gradle | Version |
---|---|
5-8 | 1.7.2 |
4.x | 1.4.6 |
Snapshots
<details> <summary>Snapshots may be used through JitPack or GitHub packages</summary>GitHub package
WARNING: Accessing GitHub package requires GitHub authorization!
-
Add to
settings.gradle
(top most!) (exact commit hash might be used as version) :pluginManagement { repositories { gradlePluginPortal() maven { url = 'https://maven.pkg.github.com/xvik/gradle-animalsniffer-plugin' credentials { username = settings.ext.find('gpr.user') ?: System.getenv("USERNAME") password = settings.ext.find('gpr.key') ?: System.getenv("TOKEN") } } } }
-
In global gradle file
~/.gradle/gradle.properties
addgpr.user=<your github user name> gpr.key=<your github password or classic token>
(or credentials must be declared in environment: USERNAME/TOKEN (more usable for CI)) Read personal access tokens creation guide Note that token needs only "package/read" permission
-
Use plugin snapshot (see the latest published package version):
plugins { id 'ru.vyarus.animalsniffer' version '2.0.0-SNAPSHOT' }
JitPack
-
Add to
settings.gradle
(top most!) (exact commit hash might be used as version) :pluginManagement { resolutionStrategy { eachPlugin { if (requested.id.id == 'ru.vyarus.use-python') { useModule('ru.vyarus:gradle-animalsniffer-plugin:master-SNAPSHOT') } } } repositories { gradlePluginPortal() maven { url 'https://jitpack.io' } } }
Note: this would use the latest snapshot. To use exact commit version, go to JitPack project page
-
Use plugin without declaring version:
plugins { id 'ru.vyarus.animalsniffer' }
Usage
Additional tasks will be assigned to the check
task. So animalsniffer checks will be executed during:
$ gradlew check
NOTE: in case of configuration problems use animalsniffer.debug
option to see actual task configuration
Signatures
AnimalSniffer requires a signature file to check against. To define a signature (or multiple signatures) use
the signature
configuration.
To check Java version compatibility:
repositories { mavenCentral() }
dependencies {
signature 'org.codehaus.mojo.signature:java16:1.1@signature'
}
To check Android compatibility (in java project):
repositories { mavenCentral() }
dependencies {
signature 'net.sf.androidscents.signature:android-api-level-14:4.0_r4@signature'
}
To check both Java version and Android compatibility:
dependencies {
signature 'org.codehaus.mojo.signature:java16:1.1@signature'
signature 'net.sf.androidscents.signature:android-api-level-14:4.0_r4@signature'
}
In the last case animalsniffer will run 2 times for each signature. You may see the same errors two times if a class/method is absent in both signatures. Each error message in the log (and file) will also contain the signature name to avoid confusion.
When no signatures are defined animalsniffer tasks will always pass.
You can also use custom libraries signatures to check version compatibility.
Scope
All project dependencies are excluded from the analysis: only classes from your source set are checked.
By default, all source sets are checked. To only check main sources:
animalsniffer {
sourceSets = [sourceSets.main]
}
Output
Violations are always printed to the console. Example output:
2 AnimalSniffer violations were found in 1 files. See the report at: file:///myproject/build/reports/animalsniffer/main.text
[Undefined reference] invalid.(Sample.java:9)
>> int Boolean.compare(boolean, boolean)
[Undefined reference] invalid.(Sample.java:14)
>> java.nio.file.Path java.nio.file.Paths.get(String, String[])
NOTE: text report file will contain simplified report (error per line):
invalid.Sample:9 Undefined reference: int Boolean.compare(boolean, boolean)
invalid.Sample:14 Undefined reference: java.nio.file.Path java.nio.file.Paths.get(String, String[])
NOTE: when multiple signatures are used, output will contain the signature name in the error message to avoid confusion.
Suppress violations
An annotation could be used to suppress violations: examples
Default annotation
Add dependency on the annotation artifact:
implementation "org.codehaus.mojo:animal-sniffer-annotations:1.16"
Use provided
scope if you can.
Annotation is configured by default, so you can simply use annotation to suppress violation:
@IgnoreJRERequirement
private Optional param;
Custom annotation
You can define your own annotation:
package com.mycompany
@Retention(RetentionPolicy.CLASS)
@Documented
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
public @interface SuppressSignatureCheck {}
Configure annotation:
animalsniffer {
annotation = 'com.mycompany.SuppressSignatureCheck'
}
Now check will skip blocks annotated with your annotation:
@SuppressSignatureCheck
private Optional param;
Extend signature
Your project could target multiple Java versions and so reference classes, not present in a signature.
For example, your implementation could try to use Java 7 Paths
and if the class is not available, fall back
to the Java 6 implementation. In this case Paths
could be added to the ignored classes:
animalsniffer {
ignore 'java.nio.file.Paths'
}
Now usages of Paths
will not cause warnings.
Multiple ignored classes could be defined:
animalsniffer {
ignore 'java.nio.file.Paths', 'some.other.Class'
}
Or
animalsniffer {
ignore 'java.nio.file.Paths'
ignore 'some.other.Class'
}
Or by directly assigning collection:
animalsniffer {
ignore = ['java.nio.file.Paths', 'some.other.Class']
}
Entire packages could be ignored using asterisk:
animalsniffer {
ignore 'some.pkg.*'
}
See more info in the documentation.
Configuration
Configuration example:
animalsniffer {
toolVersion = '1.23'
sourceSets = [sourceSets.main]
ignoreFailures = true
reportsDir = file("$project.buildDir/animalsnifferReports")
annotation = 'com.mypackage.MyAnnotation'
ignore = ['java.nio.file.Paths']
}
There are no required configurations - the plugin will generate defaults for all of them.
Property | Description | Default value |
---|---|---|
toolVersion | AnimalSniffer version | 1.23 |
sourceSets | Source sets to check | all source sets |
ignoreFailures | False to stop build when violations found, true to continue | false |
debug | Log animalsniffer configuration (useful in case of configuration problems) | false |
reportsDir | Reports directory | file("$project.buildDir/reports/animalsniffer") |
annotation | Annotation class to avoid check under annotated block | |
ignore | Ignore usage of classes, not mentioned in signature | |
signatures | Signatures to use for check | configurations.signature |
excludeJars | Patterns to exclude jar names from classpath. Required for library signatures usage | |
cache | Cache configuration | By default, cache disabled |
NOTE: ignore
does not exclude your classes from check, it allows you to use classes not mentioned in the signature.
See more details above.
Tasks
The animalsniffer task is registered for each source set:
animalsnifferMain
- run AnimalAniffer for compiled main classesanimalsnifferTest
- run AnimalSniffer for compiled test classesanimalsniffer[SourceSet]
- run AnimalSniffer for compiled[SourceSet]
classes
The check
task will depend only on tasks from configured in animalsniffer.sourceSets
source sets.
Tasks support text report, enabled by default.
To disable reports for a task:
animalsnifferMain.reports.text.enabled = false
or for all tasks:
tasks.withType(AnimalSniffer) {
reports.text.enabled = false
}
Animalsniffer task is a SourceTask and may be configured to include/exclude classes from check.
NOTE: The task operates on compiled classes and not sources! Be careful when defining patterns.
For example, to exclude classes in a 'invalid' subpackage from check:
animalsnifferMain {
exclude('**/invalid/*')
}
Advanced features
Read wiki for advanced features:
- Build your project signature
- Optimize often check task calls to speed-up subsequent checks (useful when check runs often without clean)
- Merging library signatures (when small 3rd party lib signatures used)
- View signature content
Might also like
- quality-plugin - java and groovy source quality checks
- mkdocs-plugin - project documentation generator
- pom-plugin - improves pom generation
- java-lib-plugin - avoid boilerplate for java or groovy library project
- github-info-plugin - pre-configure common plugins with github related info
- java-library generator - java library project generator