在函数调用中使用sbt settingKey

时间:2019-01-15 03:40:01

标签: scala sbt

我们有一个build.sbt文件,如下所示:

name := "Foo"
version := "0.1"
scalaVersion := "2.12.8"

def aws(module: String): ModuleID = "com.amazonaws" % module % "1.11.250"

lazy val Core = project
  .settings(
    libraryDependencies ++= Seq(
      aws("aws-java-sdk-s3"),
      aws("aws-java-sdk-dynamodb"),
    )
  )

基本上,该项目具有一些AWS开发工具包库依赖性,我们希望避免键入多个groupID(例如“ com.amazonaws”)和revision(例如“ 1.11.250”)时间,这就是为什么我们有这行:

def aws(module: String): ModuleID = "com.amazonaws" % module % "1.11.250"

但是,由于我们有许多这样的存储库,因此我们希望将此定义移至自定义sbt-plugin。首先,我们尝试这样做:

name := "Foo"
version := "0.1"
scalaVersion := "2.12.8"

val awsVersion = settingKey[String]("The version of aws SDK used for building.") // line 5
def aws(module: String): ModuleID = "com.amazonaws" % module % awsVersion.value // line 6

awsVersion := "1.11.250"

lazy val Core = project
  .settings(
    libraryDependencies ++= Seq(
      aws("aws-java-sdk-s3"),
      aws("aws-java-sdk-dynamodb"),
    )
  )

但是,第6行产生了错误:

  

错误:value仅可用于任务或设置宏,例如:=,+ =,++ =,Def.task或Def.setting。

我们的想法是最终将上面的第5行和第6行移到我们的插件中,以便我们可以像这样使用它:

name := "Foo"
version := "0.1"
scalaVersion := "2.12.8"
awsVersion := "1.11.250"

lazy val Core = project
  .settings(
    libraryDependencies ++= Seq(
      aws("aws-java-sdk-s3"),
      aws("aws-java-sdk-dynamodb"),
    )
  )

任何解决方案还是可以解决上述错误?


我们也尝试过:

def aws(module: String, version: String): ModuleID = "com.amazonaws" % module % version

...然后像这样使用:

awsVersion := "1.11.250"

lazy val Core = project
  .settings(
    libraryDependencies ++= Seq(
      aws("aws-java-sdk-s3", awsVersion.value),
      aws("aws-java-sdk-dynamodb", awsVersion.value),
    )
  )

虽然使用起来有点烦人,但效果很好,并且违背了使用settingKey开始的目的。

1 个答案:

答案 0 :(得分:0)

您不能在setting之类的本地定义的方法中使用taskaws值。这些值只能在其他settingtask定义中使用,即错误消息such as :=, +=, ++=, Def.task, or Def.setting.

这是您可以做的。

AutoPlugin文件夹中创建project

import sbt.{AutoPlugin, Def, ModuleID, settingKey}
import sbt.PluginTrigger.AllRequirements
import sbt._

object AwsPlugin extends AutoPlugin {

  override def trigger = AllRequirements

  type GetAWS = String => ModuleID

  object autoImport {
    val awsVersion =
      settingKey[String]("The version of aws SDK used for building.")
    val awsLibrary = settingKey[GetAWS]("Builds given AWS library")
  }

  import autoImport._

  override def projectSettings: Seq[Def.Setting[_]] = Seq(
    awsLibrary := { id =>
      "com.amazonaws" % id % awsVersion.value
    }
  )
}

build.sbt

中以这种方式使用
awsVersion in ThisBuild := "1.11.250"

lazy val Core = project
  .settings(
    libraryDependencies ++= Seq(
      awsLibrary.value("aws-java-sdk-s3"),
      awsLibrary.value("aws-java-sdk-dynamodb"),
    )
  )