sbt task to start Scala REPL with project's classes on the classpath and some initial commands

564 Views Asked by At

I want to define an sbt task that would start the scala console with project's compiled classes on the classpath and some initial commands executed.

I want to start that REPL session like this

sbt session

Here is my sorry attempt that I put together based on other answers, but it neither puts the project's classes on the classpath, nor doesn't execute the initial commands:

// extend Test in hope to include compiled sources on the classpath.
val ReplSession = config("repl-session") extend(Test)

val root = project.in(file("."))
  .configs(ReplSession)
  .settings(inConfig(ReplSession)(initialCommands := """
    | import foo._
    | """.stripMargin))

// define task that starts the REPL session
lazy val session = TaskKey[Unit]("session")
session <<= Seq(
  console in (root, ReplSession)
).dependOn
1

There are 1 best solutions below

0
On

Note: If someone has a better solution, I will mark it as the correct answer.

What somewhat worked for me was changing

inConfig(ReplSession)(initialCommands := ...)

in my original snippet to

inConfig(Test)(initialCommands := ...)

or, alternatively,

initialCommands in (Test, console) := ...

For completeness, here's what I use now:

val ReplSession = config("repl-session") extend(Test)

val root = project.in(file("."))
  .configs(ReplSession)

lazy val session = TaskKey[Unit]("session")
session <<= Seq(
  console in (root, ReplSession)
).dependOn

initialCommands in (Test, console) := """
  | import foo._
  | """.stripMargin

I don't find this optimal, because I'm setting initialCommands in config Test (which my ReplSession extends), instead of setting initialCommands only in config ReplSession.