The sbt project layout
sbt 2.1.1 is the build tool of the Scala ecosystem. A project is a folder with a build.sbt at the top, the version of sbt itself in project/build.properties, the compiled sources under src/main/scala and the tests under src/test/scala. The layout is a convention: the build finds the sources without a list of files, which is why an added file is compiled and an added test is run with no change to the build.
The four files of a project
build.sbt is a Scala file: scalaVersion selects the compiler, name names the artifact, and the explicit root project makes the name independent of the folder the project is checked out into. project/build.properties pins the sbt version, so every machine builds with the same one:
build.sbt
scalaVersion := "3.10.1"
name := "hello-sbt"
lazy val root = (project in file("."))
.settings(name := "hello-sbt")
project/build.properties
sbt.version=2.1.1
The program is an ordinary @main file under src/main/scala. The test is a MUnit suite under src/test/scala, and its file name ends in .test.scala, which is the convention sbt and scala-cli share:
src/main/scala/Main.scala
@main def hello(): Unit =
println("Hello from sbt")
src/test/scala/MainSuite.test.scala
//> using test.dep org.scalameta::munit::1.3.6
class MainSuite extends munit.FunSuite:
test("the greeting names the sbt build") {
assertEquals("Hello from sbt".contains("sbt"), true)
}
find . -type f -not -path '*/target/*' -not -path '*/.bsp/*' | sort
./build.sbt
./project/build.properties
./src/main/scala/Main.scala
./src/test/scala/MainSuite.test.scala
That is the whole project: four files, and the folder names do the rest. The build itself is in target/, which a version control ignore file keeps out.
Compile and run
sbt compile compiles the main sources; the first call of a sbt build starts a JVM and prints its welcome banner, and later calls reuse the work it has cached. sbt run compiles what changed and starts the program, and the line [info] running names the class it started:
sbt --server --batch compile
sbt --server --batch run
[info] running hello
Hello from sbt
--server --batch keeps sbt in a single process and turns off the interactive shell, which is the form a continuous integration job uses. A reader at a terminal types sbt once and then compile, run and test inside it; each of those words is a task, and the next lesson writes one of its own.
Related
- build.sbt, settings and tasks: the contents of the file this layout puts at the top.
- sbt tests and multiple modules: the same layout once a build grows a second module.
- MUnit: the suite under src/test/scala, run by the build.
- scala-cli, directives and scripts: the runner that needs no build file at all.
Автор статьи: Arthur Isaev