我有以下关于build.sbt配置的问题。我需要在编译前生成一些代码。这就是它现在的工作方式。
lazy val rootProject = project.in(file("."))
lazy val rootSourceGenerator = Def.task {
val f: File = (sourceManaged in Compile).value / "com" / "myproject" / "Version.scala"
IO.write(
f,
s"""package com.myproject
|
|object Version {
| some code ...
|}
|""".stripMargin
)
Seq(f)
}
inConfig(Compile)(
Seq(
sourceGenerators += rootSourceGenerator
))现在,我需要为一个新的子模块做同样的事情。
lazy val rootProject = project.in(file(".")).dependsOn(submodule)
lazy val submodule = project.in(file("submodule"))
lazy val submoduleSourceGenerator = Def.task {
val f: File = (sourceManaged in (submodule, Compile)).value / "com" / "myproject" / "SubmoduleVersion.scala"
IO.write(
f,
s"""package com.myproject
|
|object SubmoduleVersion {
| some code ...
|}
|""".stripMargin
)
Seq(f)
}
inConfig(submodule / Compile)(
Seq(
sourceGenerators += submoduleSourceGenerator
))而且inConfig(submodule / Compile)也不能工作。错误是关于/的未知语法。有什么建议如何解决这个问题吗?
发布于 2021-02-17 19:05:47
有多种解决方案,但在我看来,最干净的解决方案如下。
在project/GenerateVersion.scala中创建一个包含以下内容的AutoPlugin
import sbt.Keys._
import sbt._
object GenerateVersion extends AutoPlugin {
override def trigger = noTrigger
override def projectSettings: Seq[Def.Setting[_]] = {
Seq(
sourceGenerators in Compile += Def.task {
val f: File =
(sourceManaged in Compile).value / "com" / "myproject" / "Version.scala"
IO.write(
f,
s"""package com.myproject
|
|object Version {
|}
|""".stripMargin
)
Seq(f)
}.taskValue
)
}
}为所有需要生成Version.scala的项目/子模块启用新创建的插件GenerateVersion。在build.sbt中可以按如下所示完成
lazy val sub = project
.in(file("sub"))
.enablePlugins(GenerateVersion)
lazy val root = project
.in(file("."))
.enablePlugins(GenerateVersion)
.aggregate(sub)当根任务被触发时,在sub模块中添加aggregate(sub)来运行任务。例如,sbt compile将同时运行两个sbt "root/compile" "sub/compile"
这个解决方案更容易以SBT插件的形式在多个SBT项目中共享。
此外,您可能会对sbt-builtinfo插件感兴趣
发布于 2021-02-18 01:16:47
谢谢,伊万·斯坦尼斯拉夫西乌克!但我找到了另一个解决方案。只需将以下所有内容添加到/subproject/build.sbt
lazy val submoduleSourceGenerator = Def.task {
val f: File = (sourceManaged in Compile).value / "com" / "myproject" / "SubmoduleVersion.scala"
IO.write(
f,
s"""package com.myproject
|
|object SubmoduleVersion {
| some code ...
|}
|""".stripMargin
)
Seq(f)
}
inConfig(Compile)(
Seq(
sourceGenerators += submoduleSourceGenerator
))https://stackoverflow.com/questions/66238432
复制相似问题