1. Overview
Sometimes during development, we might end up adding more dependencies than we use.
In this quick tutorial, we’re going to see how to use the Gradle Nebula Lint plugin to identify and fix problems like these.
2. Setup and Configuration
We're using a multi-module Gradle 5 setup in our examples.
This plugin only works for Groovy-based build files.
Let's configure it in the root project build file:
plugins { id "nebula.lint" version "16.9.0" } description = "Gradle 5 root project" allprojects { apply plugin :"java" apply plugin :"nebula.lint" gradleLint { rules=['unused-dependency'] } group = "com.baeldung" version = "0.0.1" sourceCompatibility = "1.8" targetCompatibility = "1.8" repositories { jcenter() } }
We can only configure it this way for multi-project builds for the time being. This means we can't apply it separately in each module.
Next, let’s configure our module dependencies:
description = "Gradle Unused Dependencies example" dependencies { implementation('com.google.guava:guava:29.0-jre') testImplementation('junit:junit:4.12') }
Now let’s add a simple main class in our module sources:
public class UnusedDependencies { public static void main(String[] args) { System.out.println("Hello world"); } }
We’ll build on this a bit later and see how the plugin works.
3. Detection Scenarios and Reports
The plugin searches the output jars to detect whether a dependency is used or not.
However, depending on several conditions, it can give us different results.
We'll explore the more interesting cases in the next sections.
3.1. Unused Dependencies
Now that we have our setup, let's see the basic use-case. We're interested in unused dependencies.
Let's run the lintGradle task:
$ ./gradlew lintGradle > Task :lintGradle FAILED # failure output omitted warning unused-dependency this dependency is unused and can be removed unused-dependencies/build.gradle:6 implementation('com.google.guava:guava:29.0-jre') 1 problem (0 errors, 1 warning) To apply fixes automatically, run fixGradleLint, review, and commit the changes. # some more failure output
Let's see what happened. We have an unused dependency (guava) in our compileClasspath configuration.
If we run fixGradleLint task as the plugin suggests, the dependency is automatically removed from our build.gradle.
However, let's use some dummy logic with our dependency instead:
public static void main(String[] args) { System.out.println("Hello world"); useGuava(); } private static void useGuava() { List<String> list = ImmutableList.of("Baledung", "is", "cool"); System.out.println(list.stream().collect(Collectors.joining(" "))); }
If we rerun it we get no more errors:
$ ./gradlew lintGradle BUILD SUCCESSFUL in 559ms 3 actionable tasks: 1 executed, 2 up-to-date
3.2. Using Transitive Dependencies
Let's now include another dependency:
dependencies { implementation('com.google.guava:guava:29.0-jre') implementation('org.apache.httpcomponents:httpclient:4.5.12') testImplementation('junit:junit:4.12') }
This time, let's use something from a transitive dependency:
public static void main(String[] args) { System.out.println("Hello world"); useGuava(); useHttpCore(); } // other methods private static void useHttpCore() { SSLContextBuilder.create(); }
Let's see what happens:
$ ./gradlew lintGradle > Task :lintGradle FAILED # failure output omitted warning unused-dependency one or more classes in org.apache.httpcomponents:httpcore:4.4.13 are required by your code directly (no auto-fix available) warning unused-dependency this dependency is unused and can be removed unused-dependencies/build.gradle:8 implementation('org.apache.httpcomponents:httpclient:4.5.12') 2 problems (0 errors, 2 warnings)
We get two errors. The first error roughly says we should reference httpcore directly.
The SSLContextBuilder in our sample is actually part of it.
The second error says we're not using anything from httpclient.
If we use a transitive dependency, the plugin tells us to make it a direct one.
Let's take a peek at our dependency tree:
$ ./gradlew unused-dependencies:dependencies --configuration compileClasspath > Task :unused-dependencies:dependencies ------------------------------------------------------------ Project :unused-dependencies - Gradle Unused Dependencies example ------------------------------------------------------------ compileClasspath - Compile classpath for source set 'main'. +--- com.google.guava:guava:29.0-jre | +--- com.google.guava:failureaccess:1.0.1 | +--- com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava | +--- com.google.code.findbugs:jsr305:3.0.2 | +--- org.checkerframework:checker-qual:2.11.1 | +--- com.google.errorprone:error_prone_annotations:2.3.4 | \--- com.google.j2objc:j2objc-annotations:1.3 \--- org.apache.httpcomponents:httpclient:4.5.12 +--- org.apache.httpcomponents:httpcore:4.4.13 +--- commons-logging:commons-logging:1.2 \--- commons-codec:commons-codec:1.11
In this case, we can see that httpcore is brought in by httpclient.
3.3. Using Dependencies with Reflection
What about when we use reflection?
Let's enhance our example a bit:
public static void main(String[] args) { System.out.println("Hello world"); useGuava(); useHttpCore(); useHttpClientWithReflection(); } // other methods private static void useHttpClientWithReflection() { try { Class<?> httpBuilder = Class.forName("org.apache.http.impl.client.HttpClientBuilder"); Method create = httpBuilder.getMethod("create", null); create.invoke(httpBuilder, null); } catch (Exception e) { e.printStackTrace(); } }
Now let's rerun the Gradle task:
$ ./gradlew lintGradle > Task :lintGradle FAILED # failure output omitted warning unused-dependency one or more classes in org.apache.httpcomponents:httpcore:4.4.13 are required by your code directly (no auto-fix available) warning unused-dependency this dependency is unused and can be removed unused-dependencies/build.gradle:9 implementation('org.apache.httpcomponents:httpclient:4.5.12') 2 problems (0 errors, 2 warnings)
What happened? We used HttpClientBuilder from our dependency (httpclient) but still got errors.
If we use a library with reflection, the plugin does not detect its usage.
As a result, we can see the same two errors.
In general, we should configure such dependencies as runtimeOnly.
3.4. Generating Reports
For big projects, the number of errors returned in a terminal becomes challenging to handle.
Let's configure the plugin to give us a report instead:
allprojects { apply plugin :"java" apply plugin :"nebula.lint" gradleLint { rules=['unused-dependency'] reportFormat = 'text' } // other details omitted }
Let's run the generateGradleLintReport task and check our build output:
$ ./gradlew generateGradleLintReport # task output omitted $ cat unused-dependencies/build/reports/gradleLint/unused-dependencies.txt CodeNarc Report - Jun 20, 2020, 3:25:28 PM Summary: TotalFiles=1 FilesWithViolations=1 P1=0 P2=3 P3=0 File: /home/user/tutorials/gradle-5/unused-dependencies/build.gradle Violation: Rule=unused-dependency P=2 Line=null Msg=[one or more classes in org.apache.httpcomponents:httpcore:4.4.13 are required by your code directly] Violation: Rule=unused-dependency P=2 Line=9 Msg=[this dependency is unused and can be removed] Src=[implementation('org.apache.httpcomponents:httpclient:4.5.12')] Violation: Rule=unused-dependency P=2 Line=17 Msg=[this dependency is unused and can be removed] Src=[testImplementation('junit:junit:4.12')] [CodeNarc (http://www.codenarc.org) v0.25.2]
Now it detects unused dependencies on the testCompileClasspath configuration.
This is, unfortunately, an inconsistent behavior of the plugin. As a result, we now get three errors.
4. Conclusion
In this tutorial, we saw how to find unused dependencies on Gradle builds.
First, we explained the general setup. After that, we explored the errors reported with different dependencies and their usage.
Finally, we saw how to generate text-based reports.
As usual, we can find the complete code samples over on GitHub.