Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally invoke a task in sbt?

Tags:

scala

sbt

Say taskA is a heavy task which should only be invoked if it's enabled and taskAEnabled is the corresponding setting key.

A naive approach would be:

val taskAConditional = Def.task {
  (taskAEnabled, taskA) map { (taskAEnabled, taskA) => 
    if (taskAEnabled) taskA.value
  }
}

This won't work due to sbt design. As taskA now becomes the dependency of taskAConditional, it will be executed regardless of the if logic (i.e. taskAEnabled will be ignored).

Is there a way that I can achieve what I want? (I can't change taskA as it's imported from somewhere else)

like image 996
NSF Avatar asked Feb 11 '23 13:02

NSF


1 Answers

In sbt 0.13.x you can use dynamic computations Def.taskDyn:

val taskAConditional = Def.taskDyn {
  if (taskAEnabled.value) Def.task {
     taskA.value // this `.value` macro will extract result of taskA (execute it) only if taskAEnabled.value == true
  } 
}
like image 177
dk14 Avatar answered Feb 16 '23 02:02

dk14