Run custom task automatically before/after standard task

后端 未结 2 1203
南笙
南笙 2020-11-29 07:20

I often want to do some customization before one of the standard tasks are run. I realize I can make new tasks that executes existing tasks in the order I want, but I find t

相关标签:
2条回答
  • 2020-11-29 07:37

    As an update for the previous answer by @Paul Butcher, this could be done in a bit different way in SBT 1.x versions since <<== is no longer supported. I took an example of a sample task to run before the compilation that I use in one of my projects:

    lazy val wsdlImport = TaskKey[Unit]("wsdlImport", "Generates Java classes from WSDL")
    
    wsdlImport := {
      import sys.process._
      "./wsdl/bin/wsdl_import.sh" !
      // or do whatever stuff you need
    }
    
    (compile in Compile) := ((compile in Compile) dependsOn wsdlImport).value
    

    This is very similar to how it was done before 1.x.

    Also, there is another way suggested by official SBT docs, which is basically a composition of tasks (instead of dependencies hierarchy). Taking the same example as above:

    (compile in Compile) := {
      val w = wsdlImport.value
      val c = (compile in Compile).value
      // you can add more tasks to composition or perform some actions with them
      c
    }
    

    It feels like giving more flexibility in some cases, though the first example looks a bit neater, as for me.

    Tested on SBT 1.2.3 but should work with other 1.x as well.

    0 讨论(0)
  • 2020-11-29 07:58

    Extending an existing task is documented the SBT documentation for Tasks (look at the section Modifying an Existing Task).

    Something like this:

    compile in Compile <<= (compile in Compile) map { _ => 
      // what you want to happen after compile goes here 
    }
    

    Actually, there is another way - define your task to depend on compile

    prepareAppTask := (whatever you want to do) dependsOn compile
    

    and then modify packageBin to depend on that:

    packageBin <<= packageBin dependsOn prepareAppTask
    

    (all of the above non-tested, but the general thrust should work, I hope).

    0 讨论(0)
提交回复
热议问题