简体   繁体   中英

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

// ...

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 ). 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.

See the differences between Global and ThisBuild here .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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