Home

Awesome

SpotBugs Gradle Plugin

This is the official Gradle Plugin to run SpotBugs on Java and Android project.

Coverage Status Debt Gradle Plugin Portal

Goal

This Gradle plugin is designed to solve the following problems in the legacy plugin:

Usage

Apply to your project

Apply the plugin to your project. Refer the Gradle Plugin portal about the detail of installation procedure.

Configure SpotBugs Plugin

Configure spotbugs extension to configure the behaviour of tasks:

// require Gradle 8.2+
import com.github.spotbugs.snom.Confidence
import com.github.spotbugs.snom.Effort
spotbugs {
    ignoreFailures = false
    showStackTraces = true
    showProgress = true
    effort = Effort.DEFAULT
    reportLevel = Confidence.DEFAULT
    visitors = listOf("FindSqlInjection", "SwitchFallthrough")
    omitVisitors = listOf("FindNonShortCircuit")
    reportsDir = file("$buildDir/spotbugs")
    includeFilter = file("include.xml")
    excludeFilter = file("exclude.xml")
    baselineFile = file("baseline.xml")
    onlyAnalyze = listOf("com.foobar.MyClass", "com.foobar.mypkg.*")
    maxHeapSize = "1g"
    extraArgs = listOf("-nested:false")
    jvmArgs = listOf("-Duser.language=ja")
}
<details> <summary>with Groovy DSL</summary>
import com.github.spotbugs.snom.Confidence
import com.github.spotbugs.snom.Effort
spotbugs {
    ignoreFailures = false
    showStackTraces = true
    showProgress = true

    // https://discuss.kotlinlang.org/t/bug-cannot-use-kotlin-enum-from-groovy/1521
    // https://touk.pl/blog/2018/05/28/testing-kotlin-with-spock-part-2-enum-with-instance-method/
    effort = Effort.valueOf('DEFAULT')
    reportLevel = Confidence.valueOf('DEFAULT')

    visitors = [ 'FindSqlInjection', 'SwitchFallthrough' ]
    omitVisitors = [ 'FindNonShortCircuit' ]
    reportsDir = file("$buildDir/spotbugs")
    includeFilter = file("include.xml")
    excludeFilter = file("exclude.xml")
    baselineFile = file("baseline.xml")
    onlyAnalyze = [ 'com.foobar.MyClass', 'com.foobar.mypkg.*' ]
    maxHeapSize = '1g'
    extraArgs = [ '-nested:false' ]
    jvmArgs = [ '-Duser.language=ja' ]
}
</details>

Configure spotbugsPlugin to apply any SpotBugs plugin:

dependencies {
    spotbugsPlugins("com.h3xstream.findsecbugs:findsecbugs-plugin:1.13.0")
}
<details> <summary>with Groovy DSL</summary>
dependencies {
    spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.13.0'
}
</details>

Configure spotbugs to choose your favorite SpotBugs version:

dependencies {
    spotbugs("com.github.spotbugs:spotbugs:4.8.6")
}
<details> <summary>with Groovy DSL</summary>
dependencies {
    spotbugs 'com.github.spotbugs:spotbugs:4.8.6'
}
</details>

Apply to Java project

Apply this plugin with the java plugin to your project, then SpotBugsTask will be generated for each existing sourceSet.

If you want to create and configure SpotBugsTask by own, apply the base plugin (com.github.spotbugs-base) instead, then it won't create tasks automatically.

Apply to Android project

TBU

Configure the SpotBugsTask

Configure SpotBugsTask directly, to set task-specific properties.

// require Gradle 8.2+
tasks.spotbugsMain {
    reports.create("html") {
        required = true
        outputLocation = file("$buildDir/reports/spotbugs.html")
        setStylesheet("fancy-hist.xsl")
    }
}
<details> <summary>with Groovy DSL</summary>
// Example to configure HTML report
spotbugsMain {
    reports {
        html {
            required = true
            outputLocation = file("$buildDir/reports/spotbugs/main/spotbugs.html")
            stylesheet = 'fancy-hist.xsl'
        }
    }
}
</details>

Migration guides

SpotBugs version mapping

By default, this Gradle Plugin uses the SpotBugs version listed in the following table.

You can change SpotBugs version by the toolVersion property of the spotbugs extension or the spotbugs configuration.

Gradle PluginSpotBugs
6.0.184.8.6
6.0.144.8.5
6.0.104.8.4
6.0.34.8.3
6.0.04.8.2
5.2.54.8.2
5.2.34.8.1
5.1.54.8.0
5.0.134.7.3
5.0.124.7.2
5.0.94.7.1
5.0.74.7.0
5.0.44.5.3
5.0.34.5.2
5.0.24.5.1

Refer the version in the build script

From v4, the spotbugs.toolVersion is changed from String to Provider<String>, so use get() or other methods to refer to the actual version.

dependencies {
    compileOnly "com.github.spotbugs:spotbugs-annotations:${spotbugs.toolVersion.get()}"
}
<details> <summary>with Kotlin DSL</summary>
dependencies {
    compileOnly("com.github.spotbugs:spotbugs-annotations:${spotbugs.toolVersion.get()}")
}
</details>

Development

Setup

#!/usr/bin/env python
import re, sys, os

#turn off the traceback as it doesn't help readability
sys.tracebacklimit = 0

def main():
    # example:
    # feat(apikey): added the ability to add api key to configuration
    pattern = r'(build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*'
    filename = sys.argv[1]
    ss = open(filename, 'r').read()
    m = re.match(pattern, ss)
    if m == None: raise Exception("Conventional commit validation failed. Did you forget to add one of the allowed prefixes? (build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)")

if __name__ == "__main__":
    main()

Signing Artifacts

Since version 4.3, when we publish artifacts we now sign them. This is designed so that the build will still pass if you don't have the signing keys available, this way pull requests and forked repos will still work as before.

Before github workflow can sign the artifacts generated during build, we first need to generate pgp keys (you will have to do this again when the key expires. once a year is a good timeframe) and upload them to the servers. See https://www.gnupg.org/faq/gnupg-faq.html#starting_out for more details.

That means github needs the following secrets:

SIGNING_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----..."
SIGNING_PASSWORD = password

where secrets.SIGNING_KEY is the in-memory ascii-armored keys (you get this by running gpg --armor --export-secret-keys <EMAIL>) and secrets.SIGNING_PASSWORD is the password you used when generating the key.

Gradle is configured to use these to generate the private key in memory so as to minimize our risk of the keys being found and used by someone else.

Copyright

Copyright © 2019-present SpotBugs Team