【问题标题】:How to create a generic SBT root project with varying sub projects如何创建具有不同子项目的通用 SBT 根项目
【发布时间】:2019-01-06 13:48:09
【问题描述】:

我正在Exercism 的 Scala 轨道上工作,这意味着我在根文件夹中有很多 SBT 项目。我想创建一个根 SBT 项目,它会在我下载新练习时自动添加新的子项目。目前我必须手动添加它们,所以我的根build.sbt 看起来像这样:

lazy val root = (project in file("."))
    .aggregate(
        hello_world,
        sum_of_multiples,
        robot_name)

lazy val hello_world = project in file("hello-world")
lazy val sum_of_multiples = project in file("sum-of-multiples")
lazy val robot_name = project in file("robot-name")

...但我想避免手动添加每个项目。有没有办法自动添加新项目?

【问题讨论】:

    标签: scala sbt


    【解决方案1】:

    我想避免手动添加每个项目。有没有办法自动添加新项目?

    当然。 sbt 的使用有点高级,但是你可以创建一个 ad-hoc 插件,以编程方式生成子项目。

    build.sbt

    ThisBuild / scalaVersion     := "2.12.8"
    ThisBuild / version          := "0.1.0-SNAPSHOT"
    ThisBuild / organization     := "com.example"
    ThisBuild / organizationName := "example"
    

    project/build.properties

    sbt.version=1.2.8
    

    项目/SubprojectPlugin.scala

    import sbt._
    
    object SubprojectPlugin extends AutoPlugin {
      override val requires = sbt.plugins.JvmPlugin
      override val trigger = allRequirements
      override lazy val extraProjects: Seq[Project] = {
        val dirs = (file(".") * ("*" -- "project" -- "target")) filter { _.isDirectory }
        dirs.get.toList map { dir =>
          Project(dir.getName.replaceAll("""\W""", "_"), dir)
        }
      }
    }
    

    现在,如果您启动 sbt,任何未命名为 targetproject 的目录都将生成子项目。

    sbt:generic-root> projects
    [info] In file:/private/tmp/generic-root/
    [info]   * generic-root
    [info]     hello_world
    [info]     robot_name
    [info]     sum_of_multiple
    

    hello-world/build.sbt

    要添加更多设置,您可以在目录下创建build.sbt文件,如下所示:

    libraryDependencies += "commons-io" % "commons-io" % "2.6"
    

    【讨论】:

    • 太棒了!一旦我也将-- ".idea" 添加到忽略列表中,它就像一个魅力。非常感谢!
    • 预期可能是子项目包含src 目录 - 可以作为谓词添加。
    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2020-06-08
    • 2021-03-14
    • 2014-09-01
    • 1970-01-01
    • 2016-06-03
    • 2021-05-28
    • 1970-01-01
    相关资源
    最近更新 更多