Tag: Jenkins

Using static code analysis tools with Jenkins Pipeline jobs

I’ve been using Jenkins 2 more and more in my projects and I’ve found that the Pipeline feature is a great fit for the jobs that I am writing. However, the documentation isn’t fantastic for the older plugins. One example of this is static code analysis tools such as PMD, CheckStyle and FindBugs. In old Jenkins, there would be a screen to configure how the results of these plugins affected the results of the build:screen-shot-2016-12-28-at-11-21-28

Obviously, in a Pipeline job, you have to configure this via code rather than on a web page, but it’s not documented how (that I could find). I wanted the build to be UNSTABLE if any warnings were generated. After a bit of digging, I figured out it should look like this:

step([$class: 'hudson.plugins.checkstyle.CheckStylePublisher', pattern: '**/target/checkstyle-result.xml', unstableTotalAll:'0'])

PMD and FindBugs are very similar as they are based on the same Publisher class.

step([$class: 'hudson.plugins.checkstyle.CheckStylePublisher', pattern: '**/target/checkstyle-result.xml', unstableTotalAll:'0'])
step([$class: 'PmdPublisher', pattern: '**/target/pmd.xml', unstableTotalAll:'0'])
step([$class: 'FindBugsPublisher', pattern: '**/findbugsXml.xml', unstableTotalAll:'0'])

The more complicated configuration options that are listed on the web page above can be found in this class. All the static code analysis tools extend HealthAwareRecorder and so the configuration is the same. Use the setters to push configuration via properties in the step definition. For example, if I wanted to set the healthy threshold to 20 and the unhealthy threshold to 100, then by looking at the class, I find

    /**
     * Returns the healthy threshold, i.e. when health is reported as 100%.
     *
     * @return the 100% healthiness
     */
    @Override
    @CheckForNull
    public String getHealthy() {
        return healthy;
    }

    /**
     * @see {@link #getHealthy()}
     */
    @DataBoundSetter
    public void setHealthy(final String healthy) {
        this.healthy = healthy;
    }

    /**
     * Returns the unhealthy threshold, i.e. when health is reported as 0%.
     *
     * @return the 0% unhealthiness
     */
    @Override
    @CheckForNull
    public String getUnHealthy() {
        return unHealthy;
    }

    /**
     * @see {@link #getUnHealthy()}
     */
    @DataBoundSetter
    public void setUnHealthy(final String unHealthy) {
        this.unHealthy = unHealthy;
    }

so I would use

step([$class: 'hudson.plugins.checkstyle.CheckStylePublisher', pattern: '**/target/checkstyle-result.xml', healthy:'20', unHealthy:'100'])

An example of this can be found on my GitHub account here.

Clearly this is more complicated that just filling in the values on the web site, so it will be interesting to see if a snippet generator pops up for this.

Advertisements