Skip to content

Instantly share code, notes, and snippets.

@jasonqu
Last active January 14, 2016 09:01
Show Gist options
  • Save jasonqu/830d311e5ccbbbea7566 to your computer and use it in GitHub Desktop.
Save jasonqu/830d311e5ccbbbea7566 to your computer and use it in GitHub Desktop.
how to use setting defined in sbt plugin
// build.sbt in myplugin
sbtPlugin := true
lazy val plugin = (project in file(".")).
settings(
name := "myplugin",
version := "0.1-SNAPSHOT",
scalaVersion := "2.10.4"
)
// build.sbt in the project that using myplugin
lazy val usage = (project in file("."))
.enablePlugins(HelloPlugin).
settings(
name := "sbt-test",
version := "0.1",
scalaVersion := "2.10.4")
.settings(
greeting := "Hello"
)
// source in plugin
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)
}
addSbtPlugin("mysite" % "mysite" % "0.1-SNAPSHOT")

此时执行的结果

> show obfuscate
Hi!
[info] Hi! value
> show greeting
[info] Hello

如果修改HelloPlugin.scala中的一句为:

from:
greeting := "Hi!",
to:
greeting in obfuscate := "Hi!",

则执行结果变为

> show greeting
[info] Hello
> show obfuscate
Hello
[info] Hello value

符合预期,但是此时如果去掉build.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]

with the files above, the execution result is:

> show obfuscate
Hi!
[info] Hi! value
> show greeting
[info] Hello

the obfuscate task cannot read the "Hello" value

if modify greeting := "Hi!" in HelloPlugin.scala to greeting in obfuscate := "Hi!",

the obfuscate task can read the "Hello" value now

> show greeting
[info] Hello
> show obfuscate
Hello
[info] Hello value

but we cannot remove greeting := "Hello" in buildInDemo.sbt now, or else it will have such errors:

[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]
@jasonqu
Copy link
Author

jasonqu commented Jan 14, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment