我正在编写一个添加命令的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
变量提供?
答案 0 :(得分: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.sbt 中为newSetting
设置提供自己的值:
newSetting := "light"
修改强>
这是另一个例子,更接近你的目标:
Build.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)
}
使用此配置,您可以在sbt提示符下运行my-task
,并且您将看到newSetting: default
已打印到控制台。
您可以在 build.sbt :
中覆盖此设置newSetting := "modified"
现在,当您在sbt提示符处运行my-task
时,您会看到newSetting: modified
已打印到控制台。
编辑2
以上是上述示例的独立版本:https://earldouglas.com/ext/stackoverflow.com/questions/17038663/
答案 1 :(得分:2)
我接受了@ James的回答,因为它真的帮助了我。我放弃使用命令支持任务(参见this mailing list thread)。最后,我的插件看起来像这样:
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)
}
}
要覆盖使用此插件的项目的newSetting
中的build.sbt
:
import packge.to.my.plugin.MyKeys._
newSetting := "Something else"
缺少的导入声明让我陷入了一段时间!