Improving Scala code with sbt

Improving Scala code with sbt

We’ve previously discussed the Scala Build Tool, sbt, and how easy it is to extend its abilities using plugins. Now, we’re going to review a few of the plugins that can help us follow coding best practices in our Scala projects. By embracing best practices, we’ll write more efficient code and produce increasingly secure applications.

Code coverage plugins

scct:

The Scala Code Coverage Tool offers line level coverage. It can generate separate reports of your multi-module projects and integrates with Coveralls, Gradle, and Jenkins.

How to use it:

  1. Add the plugin to project/plugins.sbt:

     addSbtPlugin("com.sqality.scct" % "sbt-scct" % "0.3")
    
  2. Add the plugin settings to your project as a val in Build.scala. Here, you can define the settings and dependencies of each module of your project:

     val myModule = Project(id = "my-module", base = file("modules/my-module"))
         .settings(ScctPlugin.instrumentSettings: _*)
    
  3. Run the unit tests:

     $ sbt clean scct:test
    
  4. After the tests finish, the generated report will be available here:

     ./target/scala-2.10/coverage-report/index.html
    

Website: https://github.com/sqality/scct

scoverage

This plugin is a fork of scct and provides statement and branch coverage which can be more useful in languages like Scala, where multiple statements or even branches can be included on a single line. Scoverage checks whether all codes paths are covered and shows the result as a percentage of the total branches. The following are considered as branch statements:

  • If / else statements
  • Match statements
  • Partial function cases
  • Try / catch / finally clauses

How to use it:

To use scoverage you need to use one of the build plugins in your project as well:

scoverage is available for sbt, maven, and gradle.

Website: https://github.com/scoverage/scalac-scoverage-plugin

sbt-scoverage:

sbt-scoverage integrates with the scoverage code coverage library and is one of the plugins needed to use this library.

How to use it:

  1. Add the plugin in project/plugins.sbt:

     addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.3.3")
    
  2. Run the tests with enabled coverage:

     $ sbt clean coverage test
    

or if you have integration tests as well use:

    $ sbt clean coverage it:test
  1. To enable coverage directly in your build, use:

     coverageEnabled := true
    
  2. To generate the coverage reports run:

     $ sbt coverageReport
    
  3. The generated reports can be found:

     ./target/scoverage-report
    

You can exclude classes, packages, and even sections in the code and set a minimum coverage. It integrates with Coveralls using the sbt-coveralls plugin and with SonarQube using the sonar-scoverage-plugin.

Website: https://github.com/scoverage/sbt-scoverage

sbt-coveralls:

sbt-coveralls uses scoverage to generate the code coverage metrics and uploads them to Coveralls. Sbt-coveralls also integrates with Travis CI.

How to use it:

  1. Add the following to your project build.sbt:

     resolvers += Classpaths.sbtPluginReleases
        
     addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.3.3")
        
     addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.0.3")
    
  2. Specify your Repo Token from Coveralls using one of these options:

    • Save your repo token into a file and add the following to your build.sbt:

        import org.scoverage.coveralls.Imports.CoverallsKeys._
              
        coverallsTokenFile := "/path/to/my/repo/token.txt"
      
    • Use your repo token directly in your build.sbt:

        import org.scoverage.coveralls.Imports.CoverallsKeys._
              
        coverallsToken := Some("my-token")
      
    • Create an environment variable:

        export COVERALLS_REPO_TOKEN=my-token
      
  3. For manual usage, in the SBT console, run coverage then your tests finishing with coverall.

  4. It can be used with Travis CI when you add the following to your travis.yml:

     script: "sbt clean coverage test"
     after_success: "sbt coveralls"
    

Website: https://github.com/scoverage/sbt-coveralls

jacoco4sbt:

JaCoCo is a Java code coverage library that provides branch coverage and, as it’s bytecode-based, works for Scala too.

jacoco4sbt is an sbt plugin for code coverage analysis using JaCoCo.

How to use it:

  1. Add the plugin in project/plugins.sbt:

     addSbtPlugin("de.johoop" % "jacoco4sbt" % "2.1.6")
    
  2. Add the plugin settings to Build.scala:

     val myModule = Project(id = "my-module", base = file("modules/my-module"))
         .settings(jacoco.settings: _*)
    
  3. Run the plugin with:

     sbt jacoco:cover
    
  4. View the HTML report in the jacoco/html subdirectory.

The JaCoCo wiki illustrates more ways to generate the reports as well as how to use it in integration testing.

Website: https://github.com/sbt/jacoco4sbt

Static code analysis plugins

wartremover:

WartRemover is a flexible Scala code linting tool. This Scala static analysis tool allows you to choose which kind of errors and warnings you want to receive and exclude files or pieces of code. There are even ways to use WartRemover as a command-line tool, a macro, or a compiler plugin.

Using warts gives you the opportunity to be even more selective. There is a detailed explanation of all of the available warts on the plugin page.

How to use it:

  1. Add the following to your project/plugins.sbt:

     addSbtPlugin("org.brianmckenna" % "sbt-wartremover" % "0.14")
    
  2. Now you can configure the linter in your build.sbt. By default, all errors and warnings are turned off. To turn on all currently stable checks, use:

    wartremoverErrors ++= Warts.unsafe
    

Website: https://github.com/puffnfresh/wartremover

cpd4sbt:

With cpd4sbt, you can analyze your code using the PMD Copy/Paste Detector tool that looks for duplicated code in your project.

There’s an abundance of settings available on the plugin page that you can use to customize this tool to be more specific to your project.

How to use it:

  1. Add the following to your project/plugins.sbt:

     addSbtPlugin("de.johoop" % "cpd4sbt" % "1.1.5")
    
  2. Then add this to your project/build.sbt:

     import de.johoop.cpd4sbt.CopyPasteDetector._
     seq(cpdSettings : _*)
    

Website: https://github.com/sbt/cpd4sbt

scalastyle:

This plugin can help find potential problems in your code using Scalastyle.

How to use it:

  1. Add to project/plugins.sbt:

     addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "0.8.0")
    
  2. To generate a configuration file scalastyle-config.xml with the default settings, execute the following:

     sbt scalastyleGenerateConfig
    
  3. Check your code with:

     sbt scalastyle
    
  4. The list of errors will appear on the console and in the file:

     target/scalastyle-result.xml
    

It is also possible to run scalastyle on your test sources or as part of another task.

Website: https://github.com/scalastyle/scalastyle-sbt-plugin

sbt-scapegoat:

sbt-scapegoat analyzes code using the scapegoat library. Scapegoat is a Scala static code analyzer, and the full list of inspections can be viewed on the scapegoat homepage. You can disable inspections, ignore files, suppress warnings by method or class, and change the warning level of an inspection.

How to use it:

  1. Add the plugin to project/plugins.sbt:

     addSbtPlugin("com.sksamuel.scapegoat" %% "sbt-scapegoat" % "1.0.3")
    
  2. Set the version of scapegoat in your build sbt:

     scapegoatVersion := "1.1.0"
    
  3. Generate the scapegoat reports using:

     scapegoat
    
  4. Check the reports in the console and in:

     target/scala-2.x/scapegoat-report
    

Website: https://github.com/sksamuel/sbt-scapegoat

sbt-stats:

sbt-stats provides source code statistics and analytics for your project and gives information about files, lines, and characters in raw numbers and percentages by default.

How to use it:

  1. Add the following to your project/plugins.sbt file:

     addSbtPlugin("com.orrsella" % "sbt-stats" % "1.0.5")
    
  2. Enter the next command in the sbt console:

     stats
    

The default analyzers are FilesAnalyzer, LinesAnalyzer, and CharsAnalyzer, but you can configure which analyzers will be used with:

import com.orrsella.sbtstats._

statsAnalyzers := Seq(new FilesAnalyzer())

It is even possible to create your own analyzers or to implement the existing ones in a different way.

Website: https://github.com/orrsella/sbt-stats

sbt-scalariform:

sbt-scalariform is a tool that allows you to format source code using Scalariform, a library with an extensive selection of preferences to help format Scala source code, access tokens, and syntax trees.

How to use it:

  1. Add this setting to your project/plugins.sbt file:

     resolvers += "Sonatype OSS Releases" at "https://oss.sonatype.org/service/local/staging/deploy/maven2"
        
     addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0")
    
  2. After adding the above lines, you will be able to use the command scalariformFormate and have automatic formatting on compile and test:compile activated. You can also use scalariformFormat or test:scalariformFormat whenever you need to explicitly format your source.

Website: https://github.com/sbt/sbt-scalariform

Conclusion

We can conclude that there are many options to analyze, improve, and increase the security of our code using any combination of these plugins. You have no excuse not to use them.

blog comments powered by Disqus

Ensure the success of your project

47 Degrees can work with you to help manage the risks of technology evolution, develop a team of top-tier engaged developers, improve productivity, lower maintenance cost, increase hardware utilization, and improve product quality; all while using the best technologies.