Best place to declare own settings so I can access them from sbt shell and my .sbt and .scala build files?

Viewed 25

sbt shell can't find setting

My settings are declared in project/Utils.scala in an object BuildSupport and are made available in .sbt and .scala files with import BuildSupport._. However, this doesn't work for sbt shell as seen in above screenshot since I can't import them there. For completeness sake, I have tried eval import BuildSupport._ but all that got me was <eval>:1: error: illegal start of simple expression.

How do I have to define own settings and tasks so I can access them from:

  • project/*.scala,
  • *.sbt and
  • sbt shell?

I assume defining them in an AutoPlugin would work, but I'd rather not have to go to that length. Is there any other way?

1 Answers

Declaring an adhoc AutoPlugin (https://www.scala-sbt.org/1.x/docs/Plugins.html) is the way to go.

Auto plugins ...

  • can define autoImport object, which is automatically included into build.sbt. This can be used for keys.
  • can define globalSettings, buildSettings, or projectSettings to inject settings and tasks either at the build-level or at the subproject level. This should become available in sbt shell.

A plugin doesn't have to be a published on its own. You can declare one inside project/*.scala like any other Scala object.

The plugin in the linked documentation is great for copy-pasting:

package sbthello

import sbt._
import Keys._

object HelloPlugin extends AutoPlugin {
  override def trigger = allRequirements

  object autoImport {
    val helloGreeting = settingKey[String]("greeting")
    val hello = taskKey[Unit]("say hello")
  }

  import autoImport._
  override lazy val globalSettings: Seq[Setting[_]] = Seq(
    helloGreeting := "hi",
  )

  override lazy val projectSettings: Seq[Setting[_]] = Seq(
    hello := {
      val s = streams.value
      val g = helloGreeting.value
      s.log.info(g)
    }
  )
}
Related