如何阅读我自己的sbt插件中定义的修改设置

时间:2016-01-14 07:57:21

标签: sbt

我尝试按照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]

1 个答案:

答案 0 :(得分:2)

配置范围

override val projectSettings =
  inConfig(Compile)(baseSettings)

这会将baseSettings中的所有设置范围限定为Compile配置。所以它与说法相同:

  1. 定义greeting in Compile设置。
  2. 请参阅greeting in Compile任务中的obfuscate in Compile设置。
  3. 所以在build.sbt中你应该自定义为

    greeting in Compile := "Hello"
    

    您可以从shell访问此设置:

    > compile:greeting
    

    如果您不想要这种行为,请不要将baseSettings放入inConfig(...)

    任务和配置范围

    greeting in obfuscate是任务范围。因此与inConfig(...)相结合,

    需要

    greeting in (Compile, obfuscate) := "Hello"
    

    自定义。

    有关详细信息,请参阅Scopes