Question

I want to do something like the following in SBT:

CrossVersion.partialVersion(scalaVersion.value) match {
  case Some((2, 11)) =>
  case Some((2, 10)) => 
}

But I don't want to assign that to anything, I simply want to run some code based on the value of the current cross version.

I could create a Task and then execute the task, but can I do this without needing the task?

Was it helpful?

Solution

I know you've said you didn't want to create a task, but I would say that's the cleanest way of doing it, so I'll post it as one of the solutions anyway.

Depends on Compile

val printScalaVersion = taskKey[Unit]("Prints Scala version")

printScalaVersion := {
  CrossVersion.partialVersion(scalaVersion.value) match {
    case Some((2, 11)) => println("2.11")
    case Some((2, 10)) => println("2.10")
    case _ => println("Other version")
  }
}

compile in Compile := ((compile in Compile) dependsOn printScalaVersion).value

Override the Compile Task

If you really wouldn't like to create new task, you could redefine the compile task and add your code there (I think it's not as clean as the solution above).

compile in Compile := {
  val analysis = (compile in Compile).value
  CrossVersion.partialVersion(scalaVersion.value) match {
    case Some((2, 11)) => println("2.11")
    case Some((2, 10)) => println("2.10")
    case _ => println("Other version")
  }
  analysis
}

OTHER TIPS

Just a small "enhancement" to what @lpiepiora offered.

There could be a setting that'd hold the value of CrossVersion.partialVersion(scalaVersion.value) as follows:

lazy val sv = settingKey[Option[(Int, Int)]]("")

sv := CrossVersion.partialVersion(scalaVersion.value)

With the setting:

> sv
[info] Some((2,10))
> ++ "2.9.3"
[info] Setting version to 2.9.3
[info] Set current project to projectA (in build file:/C:/dev/sandbox/scalaVersionSetting/)
> sv
[info] Some((2,9))
> ++ "2.10.4"
[info] Setting version to 2.10.4
[info] Set current project to projectA (in build file:/C:/dev/sandbox/scalaVersionSetting/)
> sv
[info] Some((2,10))
> ++ "2.11"
[info] Setting version to 2.11
[info] Set current project to projectA (in build file:/C:/dev/sandbox/scalaVersionSetting/)
> sv
[info] Some((2,11))

...and so on.

That would give a setting to case upon.

lazy val printScalaVersion = taskKey[Unit]("Prints Scala version")

printScalaVersion := {
  sv.value foreach println
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top