Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generic SBT root project with varying sub projects

Tags:

scala

sbt

I'm working on the Scala track in Exercism which means I have a lot of SBT projects in a root folder. I'd like to create a root SBT project which will automatically add new sub-projects as I download new exercises. Currently I have to add them manually, so my root build.sbt looks like this:

lazy val root = (project in file("."))
    .aggregate(
        hello_world,
        sum_of_multiples,
        robot_name)

lazy val hello_world = project in file("hello-world")
lazy val sum_of_multiples = project in file("sum-of-multiples")
lazy val robot_name = project in file("robot-name")

...but I'd like to avoid having to add every project manually. Is there a way to add new projects automatically?

like image 339
uzilan Avatar asked Mar 06 '23 03:03

uzilan


1 Answers

I'd like to avoid having to add every project manually. Is there a way to add new projects automatically?

Sure. It's a bit advanced use of sbt, but you can create an ad-hoc plugin that generates subprojects programmatically.

build.sbt

ThisBuild / scalaVersion     := "2.12.8"
ThisBuild / version          := "0.1.0-SNAPSHOT"
ThisBuild / organization     := "com.example"
ThisBuild / organizationName := "example"

project/build.properties

sbt.version=1.2.8

project/SubprojectPlugin.scala

import sbt._

object SubprojectPlugin extends AutoPlugin {
  override val requires = sbt.plugins.JvmPlugin
  override val trigger = allRequirements
  override lazy val extraProjects: Seq[Project] = {
    val dirs = (file(".") * ("*" -- "project" -- "target")) filter { _.isDirectory }
    dirs.get.toList map { dir =>
      Project(dir.getName.replaceAll("""\W""", "_"), dir)
    }
  }
}

Now if you start up sbt, any directories that are not named target or project will result to a subproject.

sbt:generic-root> projects
[info] In file:/private/tmp/generic-root/
[info]   * generic-root
[info]     hello_world
[info]     robot_name
[info]     sum_of_multiple

hello-world/build.sbt

To add further settings you can create build.sbt file under the directory as follows:

libraryDependencies += "commons-io" % "commons-io" % "2.6"
like image 113
Eugene Yokota Avatar answered May 08 '23 23:05

Eugene Yokota