【问题标题】:How to (automatically) inherit settings/tasks from an sbt plugin?如何(自动)从 sbt 插件继承设置/任务?
【发布时间】:2023-03-26 23:25:02
【问题描述】:

我有一个 sbt 插件,它定义了我希望在 Play 项目或其他一般 sbt 项目中可用的任务。虽然这可能不是最佳实践,但我更愿意让这些任务在 Play 项目中自动可用,所以我需要做的就是通过 plugins.sbt 添加 sbt 插件。但在我能做到这一点之前,我根本无法导入任务。

如果插件的build.sbt如下:

name := "sbt-task-test"

version := "1.0.0-SNAPSHOT"

scalaVersion := "2.10.3"

scalaBinaryVersion := "2.10"

organization := "com.example"

sbtPlugin := true

lazy val testTask = taskKey[Unit]("Run a test task.")

testTask := {
    println("Running test task..")
}

如何使testTask 在另一个 sbt 项目的 build.sbt 或 Build.scala 中可用?我试过关注this 示例,但无济于事。

我的最终目标是使用blog post 中定义的任务,但我希望至少先获得一些更简单的示例。在这种情况下,我会在 build.sbt 中添加类似 registerTask("testTask", "com.example.tasks.Test", "Run a test task") 的内容,但是我遇到了与上述相同的问题。

【问题讨论】:

  • 您是否按照bottom of the example page 中的步骤之一使插件可识别,并且您是否将其作为依赖项添加到您的项目中? libraryDependencies += "com.example" ...
  • 我不想在那个链接中制作一个全局插件。我在 plugins.sbt 和 Build.scala 中都添加了插件作为库依赖。 testTask 在包括插件在内的项目中仍然不是有效的密钥。

标签: scala playframework sbt


【解决方案1】:

首先,您应该将任务定义放在插件的source 中,而不是build.sbt。所以试试这个:

  • build.sbt 的插件(它只定义了如何构建插件):

    name := "sbt-task-test"
    
    version := "1.0.0-SNAPSHOT"
    
    scalaVersion := "2.10.3"
    
    // scalaBinaryVersion := "2.10" // better not to play with this
    
    organization := "com.example"
    
    sbtPlugin := true
    
  • src/main/scala/MyPlugin.scala(在插件项目中)

    import sbt._
    
    object MyPlugin extends Plugin {
    
        lazy val testTask = taskKey[Unit]("Run a test task.")
    
        override def settings = Seq(
            testTask := { println("Running test task..") }
        )
    
    }
    

覆盖设置有助于将此任务的定义添加到项目范围。 现在您应该使用sbt publishLocal 构建和发布插件(例如在本地)。

然后在项目中,你要使用这个插件的地方:

  • project/plugins.sbt 应包含:

    addSbtPlugin("com.example" % "sbt-task-test" % "1.0.0-SNAPSHOT")
    

这将自动将testTask 键和定义添加到作用域中,以便您可以在项目目录中进行操作:

sbt testTask

它会打印Running test task..

【讨论】:

  • 一个问题。覆盖设置可能会产生任何不利影响吗?即导致事情以意想不到的方式破裂?
  • 嗯,设置/任务之间有依赖关系,你可以在 sbt 中用inspect testTask 看到它。因此,当您覆盖某些设置时,您会看到哪些其他键受到影响。您可以在 sbt set version := "42" 中尝试,您会看到一行 The new value will be used by ....,然后您可以使用 last 获取更多信息。
猜你喜欢
  • 2014-06-03
  • 2015-10-03
  • 2021-05-30
  • 1970-01-01
  • 2014-04-03
  • 2020-01-11
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
相关资源
最近更新 更多