SBT TaskKey If Statement

pau*_*ies 1 if-statement sbt

我正在使用SBT 0.13.我遇到了一个问题,以下玩具示例展示了这个问题:

lazy val nativeOne = TaskKey[Unit]( "nativeOne", "One" )
lazy val nativeTwo = TaskKey[Unit]( "nativeTwo", "Two" )

lazy val testProj = Project(
    id = "testProj",
    base = file( "." ),
    settings = Defaults.defaultSettings ++ Seq(
        scalaVersion := "2.10.2",
        nativeOne :=
        {
            println( "Native one"
        },  
        nativeTwo :=
        {
            if ( true )
            {
                println( "Native two" )
            }
            else
            {
                val n1 = nativeOne.value
            }
        }
    )
)
Run Code Online (Sandbox Code Playgroud)

如果我进入sbt并运行nativeTwo:

> nativeTwo
Native one
Native two
Run Code Online (Sandbox Code Playgroud)

为什么会这样?为什么要对false分支进行评估?是不允许在TaskKeys中分支?

jsu*_*eth 6

在sbt中,所有依赖项在任务运行之前并行计算.如果你要构建一个你拥有的图表,它将是:

nativeOne
   ^
   |
nativeTwo
Run Code Online (Sandbox Code Playgroud)

你要做的是订购任务.在sbt中,我们尝试促进返回其他任务直接使用的结果的任务,因此.value.这样做不是直接运行任务,而是说"给我这个其他任务的结果".

了解sbt语法的最佳方法是作为scala-async项目的模仿.您的代码类似于以下异步代码:

nativeOne = async {
  println( "Native one")
}
nativeTwo = async {
  if(true) println("Native Two")
  else await(nativeOne)
}
Run Code Online (Sandbox Code Playgroud)

在那里,你只是说"等待价值,如果它还没有计算出来,那就更明显了.

如果你想有选择地执行一个Task,你需要在Task[_]sbt层执行此操作,这有点冗长.我们正在使用"动态任务".这是选择在运行时实际运行哪些任务的选择.

因此,您需要使用Def.taskDyn允许您按照定义的顺序组合任务的方法.您将使用s 的toTask方法自行处理任务TaskKey.这不是处理任务产生的.这是一个例子build.sbt:

val taskOne = taskKey[Int]("test")

val taskTwo = taskKey[Int]("test2")

val taskThree = taskKey[Int]("test3")

val switchEm = settingKey[Boolean]("switch 'em")

switchEm := true

taskOne := { println("taskOne"); 1 }

taskTwo := { println("taskTwo"); 2 }

taskThree := Def.taskDyn({
  if(switchEm.value) taskTwo.toTask
  else taskOne.toTask
}).value
Run Code Online (Sandbox Code Playgroud)

然后在sbt控制台中:

> reload
[info] Loading project definition from /home/jsuereth/projects/sbt/test-projects/project
[info] Set current project to test-projects (in build file:/home/jsuereth/projects/sbt/test-projects/)
> taskThree
2
Run Code Online (Sandbox Code Playgroud)

另请注意,您不会在inspect命令中看到更正的依赖项,因为依赖项是动态添加的:

> inspect taskThree
[info] Task: Int
[info] Description:
[info]  test3
[info] Provided by:
[info]  {file:/home/jsuereth/projects/sbt/test-projects/}test-projects/*:taskThree
[info] Defined at:
[info]  /home/jsuereth/projects/sbt/test-projects/build.sbt:15
[info] Dependencies:
[info]  *:switchEm
[info]  *:settingsData        <- TaskOne + TaskTwo are missing, this replaces
[info] Delegates:
[info]  *:taskThree
[info]  {.}/*:taskThree
[info]  */*:taskThree
Run Code Online (Sandbox Code Playgroud)