How to abstract with SBT?

142 Views Asked by At

I have a build.sbt file with the following snippet:

scalastyleConfig in Compile := baseDirectory.value / "project" / "scalastyle_config.xml"
scalastyleConfig in Test := baseDirectory.value / "project" / "scalastyle_config.xml"

When I use IntelliJ to extract variable, I get:

val scalaStyleConfig: File = baseDirectory.value / "project" / "scalastyle_config.xml"
scalastyleConfig in Compile := scalaStyleConfig
scalastyleConfig in Test := scalaStyleConfig

which does not evaluate.

I tweaked things to get 2 possible alternatives that evaluate:

val scalastyleConfigFile = SettingKey[File]("scalaStyleConfig")
scalastyleConfigFile := baseDirectory.value / "project" / "scalastyle_config.xml"
scalastyleConfig in Compile := scalastyleConfigFile.value
scalastyleConfig in Test := scalastyleConfigFile.value

or:

def scalastyleConfigFile(baseDir: File) = baseDir / "project" / "scalastyle_config.xml"
scalastyleConfig in Compile := scalastyleConfigFile(baseDirectory.value)
scalastyleConfig in Test := scalastyleConfigFile(baseDirectory.value)

I'm not happy with either of my alternatives. I'm using the second alternative at the moment because it's shorter. It's annoying to have to pass the baseDirectory.value as a parameter to the function.

I tried various versions using lazy val—none of which worked :(. There must be a better way to abstract with SBT!

Can you help?

1

There are 1 best solutions below

0
On BEST ANSWER

Use Def.setting { } around your original example:

val scalaStyleConfig: File = Def.setting { baseDirectory.value / "project" / "scalastyle_config.xml" }
scalastyleConfig in Compile := scalaStyleConfig.value
scalastyleConfig in Test := scalaStyleConfig.value

The reason is that := and Def.setting are compile-time macros that only work in the correct setting.

See http://www.scala-sbt.org/0.13/docs/ChangeSummary_0.13.0.html#New+task%2Fsetting+syntax for more explanations.