根据设置重新定义sbt任务

时间:2017-03-20 23:30:38

标签: scala sbt

我想根据设置的值重新定义一个sbt任务。在默认情况下,它应该执行原始任务,在另一种情况下,我想运行自定义任务。

给定任务和设置:

val someSetting = Def.settingKey[Boolean]("some setting")
val fooTask = Def.taskKey[String]("foo task")

someSetting := true

fooTask := {
  println("** foo effect **")
  "foo value"
}

尝试重新定义fooTask:

fooTask := {
  if( someSetting.value ) fooTask
  else Def.task("whatever")
}.value

给出了编译错误:

build.sbt:39: error: Illegal dynamic dependency
  if( someSetting.value ) fooTask
      ^

使用Def.task任务编译......

fooTask := Def.task {
  if( someSetting.value ) fooTask.value
  else Def.task("whatever").value
}.value

...但即使someSetting为假,也会被执行!

> set someSetting := false
[info] Defining *:someSetting
[info] The new value will be used by *:fooTask
[info] Reapplying settings...
> fooTask
** foo effect **
[success] Total time: 1 s, completed Mar 20, 2017 11:40:13 PM

尝试使用Def.taskDyn而不是......

fooTask := Def.taskDyn {
  if( someSetting.value ) fooTask
  else Def.task("whatever")
}.value

...结果"在运行时参考未定义的设置":

> set someSetting := true
[info] Defining *:someSetting
[info] The new value will be used by *:fooTask
[info] Reapplying settings...
[info] Set current project to sbt-task-games (in build file:/Users/jast/playspace/untitled8/)
> fooTask
[trace] Stack trace suppressed: run last *:fooTask for the full output.
[error] (*:fooTask) sbt.Init$RuntimeUndefined: References to undefined settings at runtime.
[error] setting(ScopedKey(Scope(Select(ProjectRef(file:/Users/jast/playspace/untitled8/,untitled8)),Global,Global,Global),fooTask)) at RangePosition(/Users/jast/playspace/untitled8/build.sbt,LineRange(43,47)) referenced from ScopedKey(Scope(Select(ProjectRef(file:/Users/jast/playspace/untitled8/,untitled8)),Global,Global,Global),fooTask)
[error] Total time: 0 s, completed Mar 20, 2017 11:49:59 PM

1 个答案:

答案 0 :(得分:7)

你需要"保存"在返回执行它的任务之前对实际任务的引用。这是taskValue的用途:

fooTask := Def.taskDyn {
  val default = fooTask.taskValue
  if (someSetting.value) Def.task(default.value)
  else Def.task("whatever")
}.value