SBT插件——编译前执行自定义任务

SBT plugin -- execute custom task before compilation

我刚刚编写了我的第一个 SBT Autoplugin,它有一个生成设置文件的自定义任务(如果该文件不存在)。当显式调用任务时,一切都按预期工作,但我希望在使用插件编译项目之前自动调用它(无需项目修改它的 build.sbt 文件)。有没有办法做到这一点,或者我是否需要以某种方式覆盖 compile 命令?如果是这样,谁能指出我这样做的例子?任何帮助将不胜感激! (如果我遗漏了一些简单的东西,我深表歉意!)谢谢!

您可以使用 dependsOn 定义任务之间的依赖关系,并通过 重新分配 覆盖范围任务(如 compile in Compile)的行为。

添加到 build.sbt 文件的以下行可以作为示例:

lazy val hello = taskKey[Unit]("says hello to everybody :)")

hello := { println("hello, world") }

(compile in Compile) := ((compile in Compile) dependsOn hello).value

现在,每次你运行compilehello, world都会被打印出来:

[IJ]sbt:foo> compile
hello, world
[success] Total time: 0 s, completed May 18, 2018 6:53:05 PM

此示例已通过 SBT 1.1.5 和 Scala 2.12.6 测试。

val runSomeShTask = TaskKey[Unit]("runSomeSh", " run some sh")
    lazy val startrunSomeShTask = TaskKey[Unit]("runSomeSh", " run some sh")
    startrunSomeShTask := {
      val s: TaskStreams = streams.value
      val shell: Seq[String] = if (sys.props("os.name").contains("Windows")) Seq("cmd", "/c") else Seq("bash", "-c")
      // watch out for those STDOUT , SDERR redirection, otherwise this one will hang after sbt test ... 
      val startMinioSh: Seq[String] = shell :+ " ./src/sh/some-script.sh"
      s.log.info("set up run some sh...")
      if (Process(startMinioSh.mkString(" ")).! == 0) {
        s.log.success("run some sh setup successful!")
      } else {
        throw new IllegalStateException("run some sh setup failed!")
      }
    }

    // or only in sbt test 
    // test := (test in Test dependsOn startrunSomeShTask).value
    (compile in Compile) := ((compile in Compile) dependsOn startrunSomeShTask).value