在SBT 0.13中习惯性地定义动态任务?

时间:2013-10-07 12:26:30

标签: scala sbt

我正在将一个SBT插件从0.12移到0.13。在我的插件的各个点上,我将一组动态任务安排到SBT构建图上。

以下是我的旧代码。这仍然是表达这一点的惯用方式,还是可以利用宏来使一切变得更漂亮?

import sbt._
import Keys._

object Toplevel extends Build
{
    lazy val ordinals = taskKey[Seq[String]]("A list of things")
    lazy val times = taskKey[Int]("Number of times to list things")
    lazy val inParallel = taskKey[Seq[String]]("Strings to log in parallel")

    lazy val Foo = Project( id="Foo", base=file("foo"),
        settings = Defaults.defaultSettings ++ Seq(
            scalaVersion    := "2.10.2",

            ordinals := Seq( "First", "Second", "Third", "Four", "Five" ),

            times := 3,

            inParallel <<= (times, ordinals, streams) flatMap
            { case (t, os, s) =>
                os.map( o => toTask( () =>
                {
                    (0 until t).map( _ => o ).mkString(",")
                } ) ).join
            }

        )
    )
}

为完全做作的例子道歉!

修改

因此,考虑到Mark的建议,我有以下更整洁的代码:

import sbt._
import Keys._

object Toplevel extends Build
{
    lazy val ordinals = taskKey[Seq[String]]("A list of things")
    lazy val times = taskKey[Int]("Number of times to list things")
    lazy val inParallel = taskKey[Seq[String]]("Strings to log in parallel")

    def parTask = Def.taskDyn
    {
        val t = times.value
        ordinals.value.map(o => ordinalTask(o, t)).join
    }

    def ordinalTask(o: String, t: Int) = Def.task
    {
        (0 until t).map(_ => o).mkString(",")
    }

    lazy val Foo = Project( id="Foo", base=file("foo"),
        settings = Defaults.defaultSettings ++ Seq(
            scalaVersion    := "2.10.2",

            ordinals := Seq( "First", "Second", "Third", "Four", "Five" ),

            times := 3,

            inParallel := parTask.value
        )
    )
}

这似乎几乎就在那里,但是在构建时失败了:

[error] /home/alex.wilson/tmp/sbt0.13/project/build.scala:13: type mismatch;
[error]  found   : sbt.Def.Initialize[Seq[sbt.Task[String]]]
[error]  required: sbt.Def.Initialize[sbt.Task[?]]
[error]         ordinals.value.map(o => ordinalTask(o, t)).join

1 个答案:

答案 0 :(得分:3)

您可以使用Def.taskDyn,它为flatMap提供新语法。与Def.task的区别在于,预期的返回类型是一个任务Initialize[Task[T]],而不仅仅是T。翻译你的例子,

inParallel := parTask.value

def parTask = Def.taskDyn {
   val t = times.value
   ordinals.value.map(o => ordinalTask(o, t)).joinWith(_.join)
}

def ordinalTask(o: String, t: Int) = Def.task {
   (0 until t).map(_ => o).mkString(",")
}