Conditional libraries in build.sbt

浪尽此生 提交于 2020-01-15 23:38:15

问题


Using buildsbt. I'm trying to do something like this:

if (condition) {
  libraryDependencies += ... // library from maven
}
else {
  unmanagedJars in Compile += ... // local library instead
}

However, build.sbt doesn't like this at all. I've been able to accomplish this using side effects, but that's obviously undesirable. Any advice would be appreciated. Thanks.


回答1:


This might be easier to do using a Build.scala build definition.

Here is an example build.sbt file (this is optional):

import sbt._
import sbt.Keys._

libraryDependencies ++= Seq(
   "org.postgresql" % "postgresql" % "9.3-1101-jdbc41",
   "redis.clients" % "jedis" % "2.5.2"
)

Then create another file your_project_home/project/Build.scala

import sbt._
import Keys._

object BuildSettings {
    val condition = false

    val buildSettings = Defaults.defaultSettings ++ Seq(
        version := "1.0.0",
        if(condition) libraryDependencies ++= Seq("commons-codec" % "commons-codec" % "1.9")
        else unmanagedJars in Compile += file("/tmp/nil")
    )
}

object MyBuild extends Build {
    import BuildSettings._
    lazy val root: Project = Project("root", file("."), settings = buildSettings)
}

Your project structure should look like this:

.
├── build.sbt
├── project
│   └── Build.scala
└── target

You can make the "condition" to be whatever what you need (here I just set it to false). The libraryDependencies defined inside build.sbt will always be included. The ones defined in Build.scala will depend on the "condition."

Verify that everything works as expected from the command line using:

sbt "inspect libraryDependencies"



回答2:


You can do the following:

val additionalLibraryDependencies = Seq(...)
val additionalUnmanagedJars  = Seq(...)

libraryDependencies ++=(
  if (condition) {
    additionalLibraryDependencies
  }
)

unmanagedJars in Compile ++= (
  if (!condition) {
    additionalUnmanagedJars
  }
)

To set the condition from command line you should add the following lines:

val someValueFromCommandLine = System.getProperty("key.of.the.value", "false")
if (someValueFromCommandLine.equals("true")){
    ...
}

You can pass it like sbt -Dkey.of.the.value=true



来源:https://stackoverflow.com/questions/30337672/conditional-libraries-in-build-sbt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!