Scopes
We learned what settings and tasks are. Scopes ( aka Configurations ) are namespaces for settings and tasks. We use these namespaces to reuse existing tasks.
SBT provides a bunch of Scopes by default.
Compile
- compilation scopeTest
- test scopeIntegrationTest
- integration test scope. Not configured by defaultThisBuild
- configures this setting or task everywhere in your build
Every scope has a string representation, which can be used in the SBT shell to access a setting or task in a specific scope.
Using scopes in the shell
The compile
task is defined in the Compile
and Test
scope. The compile
task in the Compile
scope only compiles your sources files in src/main/scala
. The compile
task in the Test
scope depends on the compile
task in the Compile
scope and compiles your sources in src/test/scala
.
Start the SBT shell
$ sbt
Compile the test sources
> test:compile
From the command you can see the general structure
<scope>:<task>
The scope is on the left side of the colon and the task or setting on the right.
Scope task and settings
We can access the output of a setting or task with the .value
operator. To access the the output in a specific scope we can use the in
operator. The same operator is used when defining settings or task in a specific scope. As an example, we will change to target
setting in the Test scope. The target setting returns a java.io.File
directory where tasks can put generated content into.
target in Test := target.value / "test-output"
We can see our changes when we start the SBT shell
$ sbt
And inspect the different target values.
> show target
[info] /home/sbt/myproject/target
> show test:target
[info] /home/sbt/myproject/target/test-output
Accessing works the same way
(target in Test).value
Scope axes
Configurations are not the only way to scope a setting or task. Projects and settings/tasks themselves can be used to scope settings and tasks. The API show before is only a special case of the general scoping API:
taskOrSetting in (aProject, aScope, aTaskOrSetting)
Exercise
The run
task runs your application if there is a single main class or you explicitly configure the mainClass
setting.
Beginner
Set the mainClass
for Test
scope to the mainClass
detected in the Compile
scope. You should be able to run
> test:run
Advanced
The run
task runs your application if there is a single main class or you explicitly configure the mainClass
setting. By default it uses the sbt jvm process to run your application. With the fork
setting this behaviour can be changed.
Change the fork
setting to true in the Compile
scope and only for the run
task. In the sbt shell
run
should create a new jvm process.