SBT apply Task after Compile

2020-03-08 09:08发布

问题:

I am able to automatically execute a task before compilation with:

compile in Compile <<= (compile in Compile).dependsOn(myTask)

How do I do the same but after compile?

I know I can do:

compile in Compile <<= (compile in Compile) map{x=>
  // post-compile work
  doFoo()
  x
}

to execute arbitrary Scala code, but I need to automatically execute the target task itself when a compile event occurs

Doing something like:

val foo = TaskKey[Unit]("foo", "...")
val fooTask = foo <<= scalaInstance map {si =>
...
} dependsOn(compile in Compile)

works if I type "foo" from sbt> prompt; i.e. task is executed after compile, but the goal is to hook into compile task itself, so anytime a compilation occurs, the foo task is automatically called after compilation completes.

Is this possible, or am I going about things in the wrong way to hook into the built-in compile task?

回答1:

In general, there is some task that depends on your task.

If compile is being used to mean "compile and set things up for Grunt", then create a prepareGrunt task that depends on compile and myTask and run that instead.

If myTask should run before the project's classes and resources are used by something else, then make it a dependency of exportedProducts. Tasks like run and test and tasks in dependent projects will get the exported classpath entries from that task.

The danger in "run sometime after compile" is that myTask won't be run before the task that actually needs it. There is the triggeredBy method on Initialize[Task[T]], but it is easily abused and should only be used when the output of the task is known to be used only after all tasks execute.