To run scalafix on your project, you must first install the Scalafix sbt plugin or command line interface. Currently, Scalafix does not provide any IDE integrations with IntelliJ/ENSIME.

sbt-scalafix

The sbt-plugin is the recommended integration for semantic rules.

// ===> project/plugins.sbt
addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.5.3")

// ===> build.sbt
scalaVersion := "2.12.3" // 2.11.11 is also supported.
// if scalacOptions is defined with append `++=`, do nothing.
// if scalacOptions is defined like this: scalacOptions := List(...),
// then do one of the following
scalacOptions ++= List(...) // change := to ++=
// or
scalacOptions := List(...)                    // keep unchanged
scalacOptions ++= scalafixScalacOptions.value // add this line

// ===> sbt shell (example usage)
> scalafix                               // Run .scalafix.conf rules
> scalafix RemoveUnusedImports           // Run specific rule
> myProject/scalafix RemoveUnusedImports // Run rule in one project only
> test:scalafix RemoveUnusedImports      // Run rule in single configuration
> scalafix ExplicitR<TAB>                // use tab completion
> scalafix replace:com.foobar/com.buzbaz // refactor (experimental)
> scalafix file:rules/MyRule.scala       // run local custom rule
> scalafix github:org/repo/v1            // run library migration rule

Verify installation

To verify the installation, check that the scalacOptions include -Xplugin-require:semanticdb

> show scalacOptions
[info] * -Yrangepos                   // required
[info] * -Xplugin-require:semanticdb  // recommended
[info] * -P:semanticdb:sourceroot:/x  // recommended
> show libraryDependencies
[info] * org.scalameta:semanticdb-scalac:2.0.1:plugin->default(compile)

Example project

For a minimal example project using sbt-scalafix, see the scalacenter/scalafix-sbt-example repository.

git clone https://github.com/olafurpg/scalafix-sbt-example
cd scalafix-sbt-example
sbt "scalafix RemoveUnusedImports"
git diff // should produce a diff

Settings and tasks

Name Type Description
scalafix <rule>.. Unit Run scalafix on project sources. See Rules or use tab completion to explore supported rules.
sbtfix <rule>.. Unit Run scalafix on the build sources, *.sbt and project/*. Note: Requires semanticdb-sbt enabled globally for semantic rules.
scalafixEnabled Boolean true by default. If false, then sbt-scalafix will not enable the semanticdb-scalac plugin.
scalafixSourceRoot File The root directory of this project.
scalafixScalacOptions Seq[String] Necessary Scala compiler settings for scalafix to work.
scalafixVersion String Which version of scalafix-cli to run.
scalafixScalaVersion String Which Scala version of scalafix-cli to run.
scalafixSemanticdbVersion String Which version of org.scalameta:semanticdb-scalac to run.
scalafixVerbose Boolean If true, print out debug information.

semanticdb-sbt

⚠️ Experimental

semanticdb-sbt is a Scala 2.10 compiler plugin that extracts semantic information from the sbt compiler. To enable semanticdb-sbt,

// ~/.sbt/0.13/plugins/plugins.sbt
addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.5.3")
// ~/.sbt/0.13/build.sbt
import scalafix.sbt.ScalafixPlugin.autoImport._
sbtfixSettings // enable semanticdb-sbt for sbt metabuilds.

Note. This integration is new, you can expect to face problems from enabling sbt-scalafix globally. In particular, sbt-scalafix does not at the moment support older versions of 2.11 than 2.11.11 and 2.12 than 2.12.3. It’s possible to disable sbt-scalafix with scalafixEnabled := false. Please report back on your experience.

scalafix-cli

The recommended way to install the scalafix command-line interface is with coursier.

Coursier

// coursier
coursier bootstrap ch.epfl.scala:scalafix-cli_@:0.5.3 -f --main scalafix.cli.Cli -o scalafix
./scalafix --help

Homebrew

// homebrew
brew install --HEAD olafurpg/scalafmt/scalafix
scalafix --help

wget

// wget
wget -O scalafix https://github.com/scalacenter/scalafix/blob/master/scalafix?raw=true
./scalafix --help

Once the scalafix cli is installed, consult the –help page for further usage instructions.

–help

scalafix 0.5.3-6-ff5ebd38
Usage: scalafix [options] [<file>...]
  --usage  
        Print usage and exit
  --help | -h  
        Print help message and exit
  --version | -v  
        Print version number and exit
  --verbose  
        If set, print out debugging inforation to stderr.
  --config | -c  <.scalafix.conf>
        File path to a .scalafix.conf configuration file.
  --config-str | -c  <imports.organize=false>
        String representing scalafix configuration
  --sourceroot  </foo/myproject>
        Absolute path passed to semanticdb with
	-P:semanticdb:sourceroot:<path>. Relative filenames persisted in the
	Semantic DB are absolutized by the sourceroot. Defaults to current
	working directory if not provided.
  --classpath  <entry1.jar:entry2.jar:target/scala-2.12/classes>
        java.io.File.pathSeparator separated list of directories or jars
	containing '.semanticdb' files. The 'semanticdb' files are emitted by
	the semanticdb-scalac compiler plugin and are necessary for semantic
	rules like ExplicitResultTypes to function.
  --classpath-auto-roots  <target:project/target>
        Automatically infer --classpath starting from these directories.
	Ignored if --classpath is provided.
  --no-strict-semanticdb  
        Disable validation when loading semanticdb files.
  --rules | -r  <ProcedureSyntax OR file:LocalFile.scala OR scala:full.Name OR https://gist.com/.../Rule.scala>
        Scalafix rules to run.
  --stdout  
        If set, print fix to stdout instead of writing to file.
  --test  
        Exit non-zero code if files have not been fixed. Won't write to files.
  --out-from  </shared/>
        Regex that is passed as first argument to
	fileToFix.replaceAll(outFrom, outTo)
  --out-to  </custom/>
        Replacement string that is passed as second argument to
	fileToFix.replaceAll(outFrom, outTo)
  --exclude  <core Foobar.scala>
        Space separated list of regexes to exclude which files to fix. If a
	file match one of the exclude regexes, then it will not get fixed.
	Defaults to excluding no files.
  --single-thread  
        If true, run on single thread. If false (default), use all available
	cores
  --no-sys-exit  
        If true, does not sys.exit at the end. Useful for example in
	sbt-scalafix
  --quiet-parse-errors  
        Don't report parse errors for non-explictly passed filepaths.
  --bash  
        Print out bash completion file for scalafix. To install on scalafix
	--bash > /usr/local/etc/bash_completion.d/scalafix # Mac scalafix
	--bash > /etc/bash_completion.d/scalafix # Linux
  --zsh  
        Print out zsh completion file for scalafix. To install: scalafix --zsh
	> /usr/local/share/zsh/site-functions/_scalafix
  --non-interactive  
        Don't use fancy progress bar.
  --project-id  <value>
        String ID to prefix reported messages with
Available rules: DottyKeywords, NoValInForComprehension, RemoveXmlLiterals, VolatileLazyVal, ProcedureSyntax, ExplicitUnit, DottyVolatileLazyVal, DottyVarArgPattern, NoInfer, Sbt1, ExplicitResultTypes, ExplicitReturnTypes, RemoveUnusedImports, RemoveUnusedTerms, NoAutoTupling, Disable

NOTE. The command line tool is mostly intended to be invoked programmatically
from build-tool integrations such as sbt-scalafix. The necessary fixture to run
semantic rules is tricky to setup manually.

Scalafix chooses which files to fix according to the following rules:
- scalafix <directory> <rule> finds *.scala files in <directory>
- when <rule> is semantic
  - if --classpath and --sourceroot are provided, then those are used to find .semanticdb files
  - otherwise, Scalafix will automatically look for META-INF/semanticdb directories from the
    current working directory.

Examples (semantic):
  $ scalafix # automatically finds .semanticdb files and runs rule configured in .scalafix.conf.
  $ scalafix <directory> # same as above except only run on files in <directory>
  $ scalafix --rules RemoveUnusedImports # same as above but run RemoveUnusedImports.
  $ scalafix --classpath <foo.jar:target/classes> # explicitly pass classpath, --sourceroot is cwd.
  $ scalafix --classpath <foo.jar:target/classes> --sourceroot <directory>
  $ cat .scalafix.conf
  rules = [ProcedureSyntax]
  $ scalafix Code.scala # Same as --rules ProcedureSyntax

Exit status codes:
 Ok=0
 UnexpectedError=1
 ParseError=2
 ScalafixError=4
 InvalidCommandLineOption=8
 MissingSemanticApi=16
 StaleSemanticDB=32
 TestFailed=64
 LinterError=128

scalafix-core

Scalafix can be used as a library to run custom rules.

// ===> build.sbt
libraryDependencies += "ch.epfl.scala" %% "scalafix-core" % "0.5.3"
// (optional) Scala.js is also supported
libraryDependencies += "ch.epfl.scala" %%% "scalafix-core" % "0.5.3"

Example usage of the syntactic API.

import scalafix._
import scala.meta._

case object Uppercase extends Rule("Uppercase") {
  override def fix(ctx: RuleCtx): Patch =
    ctx.tree.collect {
      case name @ Name(value) => ctx.replaceTree(name, value.toUpperCase())
    }.asPatch
}

println(Uppercase("object Hello { println('world) }"))
// object HELLO { PRINTLN('world) }

The semantic API requires a more complicated setup. Please see Rule Authors.