简体   繁体   English

如何在 build.sbt 中定义自己的设置或变量?

[英]How can I define my own setting or variable in build.sbt?

I try to define my own setting that calculated by using value of name setting in build.sbt我尝试定义自己的设置,该设置通过使用 build.sbt 中的名称设置值计算得出

// ...

val projectName_ = "project_name"
val projectName = projectName_.replace("_", "")

lazy val main_class = settingKey[String]("")
main_class := s"ru.company.${projectName}.${name.value}.Main"

lazy val commonSettings = Seq(
// ...
  Compile / mainClass  := Some(main_class.value),
  assembly / mainClass := Some(main_class.value)
// ...
)

lazy val rollout = taskKey[File](s"rollout_${projectName_}") := {
// Other using of main_class.value
}

lazy val root = (project in file("."))
  .aggregate(stg, dm)
  .settings(
    name := "root"
  )

lazy val core = project
  .settings(
    name := "core",
    //...
  )

lazy val stg = project.dependsOn(core)
  .settings(
    name := "stg",
    commonSettings,
    rollout
  )

lazy val dm = project.dependsOn(core)
  .settings(
    name := "dm",
    commonSettings,
    rollout
  )

But i get error when i try to get value of my setting:但是当我尝试获取我的设置值时出现错误:

Some(main_class.value)

Reference to undefined settings引用未定义的设置

How can I define variable with name setting that I will be able to use in settings?如何定义可以在设置中使用的名称设置的变量?

When you do当你这样做

lazy val main_class = settingKey[String]("")
main_class := s"ru.company.${projectName}.${name.value}.Main"

you're defining settingKey for any place which can access it, but setting its value only for the current project (which is root ).您正在为任何可以访问它的地方定义settingKey ,但仅为当前项目(即root )设置其值。 For subprojects the value is undefined.对于子项目,该值未定义。 So you have to set it for all projects.所以你必须为所有项目设置它。

Do something like this:做这样的事情:

Global / main_class := s"ru.company.${projectName}.${name.value}.Main"

or或者

ThisBuild / main_class := s"ru.company.${projectName}.${name.value}.Main"

and main_class.value should not longer complain.并且main_class.value不应该再抱怨了。

See the differences between Global and ThisBuild here .此处查看GlobalThisBuild之间的区别。

It's a two step process: first define the key, then assign it a value.这是一个两步过程:首先定义键,然后为它分配一个值。

  1. Create a new setting:创建一个新设置:
// String is the type, the parameter is a useful description.
val scalaVersion = settingKey[String]("The version of Scala used for building.")
  1. Give a setting a value:给一个设置一个值:
scalaVersion := "type suitable for key"

Then you can reference you setting elsewhere with scalaVersion.value .然后您可以使用scalaVersion.value在其他地方引用您的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM