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. A construct that must not be written at all is a different question, and the WartRemover plugin refuses it before the formatter ever sees it.

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. The finishing project is a project whose check is this command.

Автор статьи: Arthur Isaev