Dogil
Dogil

Reputation: 107

how to write a sbt file in multiple projects?

I am trying to construct a top-level project that is divided into several projects. The respective projects are not related, and the output of the build I want is the jar files that built each project.

There are a number of ways to build with the sbt command, but all I want is an environment where I can build each project separately, or build all at once.

For example, there are three independent projects, I can use the following virtual command.

sbt assembly all -> (output) 3 jars.
sbt assembly project-A -> (output) 1 project-A jar.
sbt assembly project-B -> (output) 1 project-B jar.
sbt assembly project-C -> (output) 1 project-C jar.

I would appreciate it if you could write the basics of build.sbt.

In addition, each project can have a dependency on a common library. (For example, a library such as scala-logging)

Thank you.

Upvotes: 0

Views: 594

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

Basically you create build.sbt and declare all of those projects:

lazy val root = (project in file("."))
   // task dependency e.g.:
   // root/assembly triggers projectA/assembly and projectB/assembly and projectC/assembly
   // root/test triggers projectA/test and projectB/test and projectC/test
   // etc
  .aggregate(projectA, projectB, projectC)

lazy val projectA = project in file("project-a")

lazy val projectB = project in file("project-b")

lazy val projectC = project in file("project-c")

Then, once you add sbt-assembly to your plugins.sbt you will be able to run sbt assembly, which will assembly all of those 3 projects and puts the results in each projects respective target/scala-[version]/[sth].jar. Of course e.g. sbt projectA/assembly would assembly only projectA, etc.

As for common settings, you can store them in a variable, like:

val commonSettings = Seq(
  organization := "my-organization",
  version := "1.2.3-SNAPSHOT",
  libraryDependencies += "organization" %% "library" % "version"
)

and then apply it:

lazy val projectA = (project in file("project-a"))
   // some project-specific settings
  .settings(
    name := "project-a-module",
    description := "a module of sth sth project"
  )
   // here we take the Seq and use it like vararg
  .settings(commonSettings: _*)

One needs some time to grasp it, but sbt allows for plain old Scala in many places. Under the hood .sbt files just add some imports (e.g. content of each plugins autoImport object) and attach "rouge" settings to (not in any project.settings() clause) to current project (so root project for .sbt files in root directory, submodule if .sbt files are in submodule root directory).

Upvotes: 4

Related Questions