Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 710
Timothy Perrigo Avatar asked Oct 19 '25 07:10

Timothy Perrigo


2 Answers

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.

like image 105
stefanobaghino Avatar answered Oct 21 '25 01:10

stefanobaghino


val runSomeShTask = TaskKey[Unit]("runSomeSh", " run some sh")
    lazy val startrunSomeShTask = TaskKey[Unit]("runSomeSh", " run some sh")
    startrunSomeShTask := {
      val s: TaskStreams = streams.value
      val shell: Seq[String] = if (sys.props("os.name").contains("Windows")) Seq("cmd", "/c") else Seq("bash", "-c")
      // watch out for those STDOUT , SDERR redirection, otherwise this one will hang after sbt test ... 
      val startMinioSh: Seq[String] = shell :+ " ./src/sh/some-script.sh"
      s.log.info("set up run some sh...")
      if (Process(startMinioSh.mkString(" ")).! == 0) {
        s.log.success("run some sh setup successful!")
      } else {
        throw new IllegalStateException("run some sh setup failed!")
      }
    }

    // or only in sbt test 
    // test := (test in Test dependsOn startrunSomeShTask).value
    (compile in Compile) := ((compile in Compile) dependsOn startrunSomeShTask).value
like image 21
Yordan Georgiev Avatar answered Oct 21 '25 01:10

Yordan Georgiev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!