16

I'm trying to generate some sources as described in Generating files.

When I put the following in my build.sbt, everything works:

sourceGenerators in Compile += Def.task {
  val file = (sourceManaged in Compile).value / "demo" / "Test.scala"
  IO.write(file, """object Test extends App { println("Hi") }""")
  Seq(file)
}.taskValue

But when I attempt to do the same thing in a plugin, the task never runs:

object MyPlugin extends AutoPlugin {
  override lazy val projectSettings = Seq(
    sourceGenerators in Compile += Def.task {
      val file = (sourceManaged in Compile).value / "demo" / "Test.scala"
      IO.write(file, """object Test extends App { println("Hi") }""")
      Seq(file)
    }.taskValue
  )
}

Everything else I put in my plugin seems to work fine, but the source file is never generated.

Am I missing something important?

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
codefinger
  • 10,088
  • 7
  • 39
  • 51

1 Answers1

24

You have to load your plugin after the JvmPlugin, which resets sourceGenerators in projectSettings (see sbt.Defaults.sourceConfigPaths).

You can do that by adding it as a requirements to your plugin, e.g.

override def requires = JvmPlugin

Your complete example should look as follows:

import sbt._
import Keys._
import plugins._

object MyPlugin extends AutoPlugin {
  override def requires = JvmPlugin
  override lazy val projectSettings = Seq(
    sourceGenerators in Compile += Def.task {
      val file = (sourceManaged in Compile).value / "demo" / "Test.scala"
      IO.write(file, """object Test extends App { println("Hi") }""")
      Seq(file)
    }.taskValue
  )
}
Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
lpiepiora
  • 13,659
  • 1
  • 35
  • 47