Scala Quality Check for Play Framework projects with SonarQube

At openForce, we are using the popular SonarQube to check our code quality. Scala is not a first member of SonarQube, there is no „official“ plugin for it but there are 2 unofficial valuable plugins: one for scalastyle, a basic but solid scala linter and one for scoverage, a code coverage measurement tool.

Scoverage is measuring the statement coverage of unit tests. It checks which statement inside one line of code is executed. This is very interesting for Scala as Scala code is tending to be composed of one-liner making the line and branch code coverage values pretty biased.

Both plugins were written 2 years ago but are still working with SonarQube 5.3, the current LTS.

Additionally there is a sbt plugin for the Sonar Runner that will push the code quality data to SonarQube: https://github.com/aol/sbt-sonarrunner-plugin

 

sonar_raspberry_pi_3

 

Install the sonar plugins for scalastyle and scoverage to your sonar server

You have to build the plugins and copy the jars into the extension directory of your SonarQube installation:

https://github.com/NCR-CoDE/sonar-scalastyle

https://github.com/RadoBuransky/sonar-scoverage-plugin

 

Configure your application

The configuration described here is for projects built with the Scala Play Framework of our partner Lightbend.

project/plugins.sbt

build.sbt

Add the SonarRunnerPlugin to be able to push the quality data to SonarQube using sbt:

sonar-project.properties

Add the file sonar-project.properties to the root of your project:

 

sbt commands

scalastyle
For the first run, execute:

This will create a default configuration file for scalastyle. You can configure and persist it to suit your needs.

Check your code quality with:

 

scoverage

First run your tests:

Run scoverage:

Scoverage will create a html output of the result displaying the statement coverage:

Note that SonarQube is not able to mark the covered statements but only the lines.

 

Push the data to Sonar

Now your project should appear in Sonar.

Statement coverage on the SonarQube dashboard

SonarQube displays by default the line coverage. To display the statement coverage:
* go to Dashboards > Manage Dashboards
* then: „Configure widgets“ and add a „Custom Measures“
* set Metric 1, Metric 2, Metric 3 respectively to „Statement coverage“, „Covered statements“, „Total statements“

You now have a box looking like this:

statement_coverage

 

Scala linters

If Scalastyle is enough to fix automated Quality Gate in SonarQube, its development is not very active and it does not benefit from a large amount of rules like what you can find in the java world.
To complement scalastyle, we mostly use for our projects wartremover: https://github.com/wartremover/wartremover

For a list of linters and tools you can refer to this article form Codacy:
http://blog.codacy.com/2015/10/02/review-of-scala-static-analysis-tools/