SBT 插件 - 通过他们的 build.sbt 用户定义的命令配置 [英] SBT plugin - User defined configuration for Command via their build.sbt
问题描述
我正在编写一个添加命令的 SBT 插件,并希望用户能够通过在其 build.sbt
中设置变量来配置此命令.实现这一目标的最简单方法是什么?
I'm writing an SBT Plugin that adds a Command and would like users to be able to configure this Command by setting variables in their build.sbt
. What is the simplest way to achieve this?
这是插件外观的简化示例:
Here is an simplified example of what the Plugin looks like:
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
文件中:
I would like someone to be able to add the follow to their build.sbt
file:
newSetting := "light"
如何从上面的 myCommand
命令中将其作为 String
变量提供?
How do I make this available as a String
variable from inside the myCommand
Command above?
推荐答案
看看这里的例子:http://www.scala-sbt.org/release/docs/Extending/Plugins.html#example-plugin
在本例中,定义了一个任务和设置:
In this example, a task and setting are defined:
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
设置提供他们自己的值:
A user of your plugin could then provide their own value for the newSetting
setting in their build.sbt:
newSetting := "light"
编辑
这是另一个例子,更接近你的目标:
Here's another example, closer to what you're going for:
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
打印到控制台.
With this configuration, you can run my-task
at the sbt prompt, and you'll see newSetting: default
printed to the console.
您可以在 build.sbt 中覆盖此设置:
You can override this setting in build.sbt:
newSetting := "modified"
现在,当您在 sbt 提示符下运行 my-task
时,您会看到 newSetting: modified
打印到控制台.
Now, when you run my-task
at the sbt prompt, you'll see newSetting: modified
printed to the console.
编辑 2
这是上述示例的独立版本:https://earldouglas.com/ext/stackoverflow.com/questions/17038663/
Here's a stand-alone version of the example above: https://earldouglas.com/ext/stackoverflow.com/questions/17038663/
这篇关于SBT 插件 - 通过他们的 build.sbt 用户定义的命令配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!