我尝试按照guide创建自己的sbt插件,并输入以下代码:
myplugin中的 build.sbt
sbtPlugin := true
lazy val plugin = (project in file(".")).
settings(
name := "myplugin",
version := "0.1-SNAPSHOT",
scalaVersion := "2.10.4"
)
myplugin中的 HelloPlugin.scala
package sbthello
import sbt._
import Keys._
object HelloPlugin extends AutoPlugin {
object autoImport {
val greeting = settingKey[String]("greeting")
val obfuscate = taskKey[String]("Obfuscates files.")
}
import autoImport._
lazy val baseSettings: Seq[Def.Setting[_]] = Seq(
greeting := "Hi!",
obfuscate := {
println(greeting.value)
greeting.value + " value"
}
)
override val projectSettings =
inConfig(Compile)(baseSettings)
}
测试项目中的build.sbt
是
lazy val usage = (project in file("."))
.enablePlugins(HelloPlugin).
settings(
name := "sbt-test",
version := "0.1",
scalaVersion := "2.10.4")
.settings(
greeting := "Hello"
)
使用上述文件,执行结果为:
> show obfuscate
Hi!
[info] Hi! value
> show greeting
[info] Hello
混淆任务无法读取“Hello”值
如果将greeting := "Hi!"
中的HelloPlugin.scala
修改为greeting in obfuscate := "Hi!",
混淆任务现在可以读取“Hello”值
> show greeting
[info] Hello
> show obfuscate
Hello
[info] Hello value
但现在我无法删除buildInDemo.sbt中的greeting := "Hello"
,否则会出现此类错误:
[error] References to undefined settings:
[error]
[error] compile:greeting from compile:obfuscate ((sbthello.HelloPlugin) HelloPlugin.scala:40)
[error] Did you mean compile:obfuscate::greeting ?
[error]
[error] compile:greeting from compile:obfuscate ((sbthello.HelloPlugin) HelloPlugin.scala:40)
[error] Did you mean compile:obfuscate::greeting ?
[error]
答案 0 :(得分:2)
override val projectSettings =
inConfig(Compile)(baseSettings)
这会将baseSettings
中的所有设置范围限定为Compile
配置。所以它与说法相同:
greeting in Compile
设置。greeting in Compile
任务中的obfuscate in Compile
设置。所以在build.sbt
中你应该自定义为
greeting in Compile := "Hello"
您可以从shell访问此设置:
> compile:greeting
如果您不想要这种行为,请不要将baseSettings
放入inConfig(...)
。
greeting in obfuscate
是任务范围。因此与inConfig(...)
相结合,
greeting in (Compile, obfuscate) := "Hello"
自定义。
有关详细信息,请参阅Scopes。