2

我正在编写一个添加命令的 SBT 插件,并希望用户能够通过在build.sbt. 实现这一目标的最简单方法是什么?

这是插件外观的简化示例:

import sbt.Keys._
import sbt._

object MyPlugin extends Plugin {

  override lazy val settings = Seq(commands += Command.args("mycommand", "myarg")(myCommand))

  def myCommand = (state: State, args: Seq[String]) => {

    //Logic for command...

    state
  }
}

我希望有人能够将以下内容添加到他们的build.sbt文件中:

newSetting := "light"

如何String从上面的命令中将其作为变量提供myCommand

4

2 回答 2

6

看看这里的例子:http ://www.scala-sbt.org/release/docs/Extending/Plugins.html#example-plugin

在此示例中,定义了一个任务和设置:

val newTask = TaskKey[Unit]("new-task")
val newSetting = SettingKey[String]("new-setting")

val newSettings = Seq(
  newSetting := "test",
  newTask <<= newSetting map { str => println(str) }
)

然后,您插件的用户可以为他们的build.sbtnewSetting中的设置提供他们自己的值:

newSetting := "light"

编辑

这是另一个示例,更接近您的目标:

构建.scala

import sbt._                                                
import Keys._                                               

object HelloBuild extends Build {                           

    val newSetting = SettingKey[String]("new-setting", "a new setting!")

    val myTask = TaskKey[State]("my-task")                  

    val mySettings = Seq(                                   
      newSetting := "default",                              
      myTask <<= (state, newSetting) map { (state, newSetting) =>  
        println("newSetting: " + newSetting)                
        state
      }
    )

    lazy val root =
      Project(id = "hello",
              base = file("."),
              settings = Project.defaultSettings ++ mySettings)            
}

使用此配置,您可以my-task在 sbt 提示符下运行,您将看到newSetting: default打印到控制台。

您可以在build.sbt中覆盖此设置:

newSetting := "modified"

现在,当您my-task在 sbt 提示符下运行时,您会看到newSetting: modified打印到控制台。

编辑 2

这是上面示例的独立版本:https ://earldouglas.com/ext/stackoverflow.com/questions/17038663/

于 2013-06-14T03:21:35.113 回答
2

我接受了@James 的回答,因为它确实帮助了我。我不再使用命令来支持任务(请参阅此邮件列表线程)。最后我的插件看起来像这样:

package packge.to.my.plugin

import sbt.Keys._
import sbt._

object MyPlugin extends Plugin {

  import MyKeys._

  object MyKeys {
    val myTask = TaskKey[Unit]("runme", "This means you can run 'runme' in the SBT console")
    val newSetting = SettingKey[String]("newSetting")
  }

  override lazy val settings = Seq (
    newSetting := "light",
    myTask <<= (state, newSetting) map myCommand
  )

  def myCommand(state: State, newSetting: String) {
    //This code runs when the user types the "runme" command in the SBT console
    //newSetting is "light" here unless the user overrides in their build.sbt (see below)
    state.log.info(newSetting)
  }
}

要覆盖使用此插件的项目的newSettingin :build.sbt

import packge.to.my.plugin.MyKeys._

newSetting := "Something else"

缺少的导入语句让我停留了一段时间!

于 2013-06-18T23:31:20.920 回答