Search code examples
scalasbtsbt-plugin

SBT plugin -- execute custom task before compilation


I've just written my first SBT Autoplugin which has a custom task that generates a settings file (if the file is not already present). Everything works as expected when the task is explicitly invoked, but I'd like to have it automatically invoked prior to compilation of the project using the plugin (without having the project modify it's build.sbt file). Is there a way of accomplishing this, or do I somehow need to override the compile command? If so, could anyone point me to examples of doing so? Any help would be extremely appreciated! (My apologies if I'm missing something simple!) Thanks!


Solution

  • You can define dependencies between tasks with dependsOn and override the behavior of a scoped task (like compile in Compile) by reassigning it.

    The following lines added to a build.sbt file could serve as an example:

    lazy val hello = taskKey[Unit]("says hello to everybody :)")
    
    hello := { println("hello, world") }
    
    (compile in Compile) := ((compile in Compile) dependsOn hello).value
    

    Now, every time you run compile, hello, world will be printed:

    [IJ]sbt:foo> compile
    hello, world
    [success] Total time: 0 s, completed May 18, 2018 6:53:05 PM
    

    This example has been tested with SBT 1.1.5 and Scala 2.12.6.