tl;dr Use ivyConfigurations
添加自定义配置和resourceGenerators
处理每个环境的文件。
所有学分都归于尤金·横田 https://stackoverflow.com/users/3827/eugene-yokota的答案如何将环境配置文件配置添加到 SBT https://stackoverflow.com/q/17193795/1305344。有一些修改使我的解决方案......cough...cough...稍微好一些。
下列build.sbt
定义了两个新配置 -dev and qa。它还定义了resourceGenerators
每个配置有效地提供了一种访问新资源生成器执行配置的方法:
val Dev = config("dev") extend Runtime
val Qa = config("qa") extend Runtime
ivyConfigurations ++= Seq(Dev, Qa)
// http://www.scala-sbt.org/0.13.5/docs/Howto/generatefiles.html#resources
lazy val bareResourceGenerators: Seq[Setting[_]] = Seq(
resourceGenerators += Def.task {
val file = resourceManaged.value / "demo" / "myapp.properties"
println(s"Inside ${configuration.value}")
val contents = s"config=${configuration.value}"
IO.write(file, contents)
Seq(file)
}.taskValue
)
inConfig(Dev)(Defaults.configSettings ++ bareResourceGenerators)
inConfig(Qa)(Defaults.configSettings ++ bareResourceGenerators)
在新的资源生成器中,您可以做任何您想做的事情,并且可以使用以下命令进行每个配置的处理configuration
为您提供配置名称的设置:
> show dev:configuration
[info] dev
> show qa:configuration
[info] qa
现在当你执行show qa:resources
你会看到生成了两个文件target/scala-2.10/resource_managed/qa/demo/myapp.properties
包含特定于配置的内容:
> show qa:resources
Inside qa
[info] List(/Users/jacek/sandbox/envs/target/scala-2.10/resource_managed/qa/demo/myapp.properties, /Users/jacek/sandbox/envs/src/qa/resources)
现在的技巧是使用resourceGenerator来满足您的需求,并且由于您使用的是Scala代码,您可以做任何您想做的事情 - 只需使用configuration.value
作为特定于配置的代码的限定符。
假设您想使用qa
- 标准中的特定属性文件src/main/resources
目录。只需知道该值绑定到哪里(该值来自什么配置和设置)。只是compile:resourceDirectory
.
> show compile:resourceDirectory
[info] /Users/jacek/sandbox/envs/src/main/resources
只需使用resourceDirectory in Compile
每当你需要一个“稳定的”(aka配置固定)值如src/main/resources
.
val props = (resourceDirectory in Compile).value / s"${configuration.value.name}.properties"
println(s"Read files from $props")
通过以上几行你会得到:
> show qa:resources
Inside qa
Read files from /Users/jacek/sandbox/envs/src/main/resources/qa.properties
[info] List(/Users/jacek/sandbox/envs/target/scala-2.10/resource_managed/qa/demo/myapp.properties, /Users/jacek/sandbox/envs/src/qa/resources)
> show dev:resources
Inside dev
Read files from /Users/jacek/sandbox/envs/src/main/resources/dev.properties
[info] List(/Users/jacek/sandbox/envs/target/scala-2.10/resource_managed/dev/demo/myapp.properties, /Users/jacek/sandbox/envs/src/dev/resources)