Sbt:如何为所有项目定义任务?

时间:2018-07-17 08:48:42

标签: scala sbt

我希望能够为我的sbt.build中的所有项目定义一个任务:

lazy val project1 = project.in(`.` /  "project1)
   ...
lazy val project2 = 
   ...

lazy val upload = taskKey[Unit]("upload a config file from project to server)
upload := { 
   val file = baseDirectory.value / "config.json"
   ...
}

问题在于该定义仅在我调用sbt upload时有效,但是我希望能够为每个子项目sbt project1/uploadsbt project2/upload调用它。

有没有不使用inputKey的方法?

2 个答案:

答案 0 :(得分:3)

请参见Organizing the build

  

对于更高级的用户,组织构建的另一种方法是在project/*.scala中定义一次性auto plugins。通过定义触发的插件,自动插件可以用作在所有子项目中注入自定义任务和命令的便捷方式。

project / UploadPlugin.scala

package something

import sbt._
import Keys._

object UploadPlugin extends AutoPlugin {
  override def requires = sbt.plugins.JvmPlugin
  override def trigger = allRequirements

  object autoImport {
    val upload = taskKey[Unit]("upload a config file from project to server")
  }
  import autoImport._

  override lazy val projectSettings = Seq(
    upload := {
      val n = name.value
      println(s"uploading $n..")
    }
  )
}

build.sbt

这是使用方法:

ThisBuild / organization := "com.example"
ThisBuild / scalaVersion := "2.12.5"
ThisBuild / version      := "0.1.0-SNAPSHOT"

lazy val root = (project in file("."))
  .aggregate(project1, project2)
  .settings(
    name := "Hello"
  )

lazy val project1 = (project in file("project1"))

lazy val project2 = (project in file("project2"))

build.sbt不必提及UploadPlugin,因为它是一个触发插件。从外壳中,您可以调用:

sbt:Hello> project1/upload
uploading project1..
[success] Total time: 0 s, completed Jul 20, 2018
sbt:Hello> project2/upload
uploading project2..
[success] Total time: 0 s, completed Jul 20, 2018

答案 1 :(得分:-1)

您可以将任务添加为所需项目的设置:

lazy val uploadTask = {
   lazy val upload = taskKey[Unit]("upload a config file from project to server)
upload := { 
   val file = baseDirectory.value / "config.json"
   ...
   }
}

project.in(`.` /  "project1).settings(uploadTask)