scalafmt
A formatter ends the argument about where a brace or a space goes by deciding once, in a file, for the whole project. scalafmt 3.11.5 is the formatter of the Scala ecosystem: it reads a .scalafmt.conf, rewrites every .scala and .sbt file to that style, and can check a folder without writing anything, which is what a build does before it accepts a change.
The configuration
Three lines are the whole configuration of this course. version pins the formatter itself, so two machines format the same way; runner.dialect = scala3 turns on the Scala 3 syntax, without which then and a significant-indentation block are read as errors; and maxColumn is the width after which a line is broken:
.scalafmt.conf
version = 3.11.5
runner.dialect = scala3
maxColumn = 100
scalafmt --version
scalafmt 3.11.5
Check, and the diff it prints
Greeting below is correct Scala and poor style: no space after a colon, a four-space indent under def, and no spaces around =. scalafmt --check . changes nothing and exits 1, and prints a unified diff of what it would write. The two header lines of the diff name the folder of the run, so the quote starts at the hunk:
Greeting.scala
object Greeting:
def greet(name:String,surname:String):String =
val full=s"$name $surname"
s"Hello, $full!"
scalafmt --check . 2>&1
@@ -1,4 +1,4 @@
object Greeting:
- def greet(name:String,surname:String):String =
- val full=s"$name $surname"
- s"Hello, $full!"
+ def greet(name: String, surname: String): String =
+ val full = s"$name $surname"
+ s"Hello, $full!"
error: --test failed
scalafmt . writes the change in place and prints nothing when it succeeds. The same file afterwards has the two lines the diff proposed, and the check is silent:
scalafmt .
cat Greeting.scala
object Greeting:
def greet(name: String, surname: String): String =
val full = s"$name $surname"
s"Hello, $full!"
scalafmt --check .
All files are formatted with scalafmt :)
An editor runs the formatter on save, so the diff above is a thing a reader sees once, in a project that has no formatter yet. A build runs --check instead, because a build must not rewrite the files it is judging: the same command that fails here fails a pull request, and the fix is scalafmt . on the author's machine.
Related
- Scalafix: the tool that rewrites what a formatter leaves alone, such as an unused import.
- WartRemover: the compiler plugin that refuses a construct rather than reformatting it.
- The finishing project: a project whose check is this command.
- Blocks, indentation, packages and imports: the indentation the formatter moves, explained once.
Article author: Arthur Isaev