the sbt task documentation shows an example of usage dependencies. It is very simple, artificial but it works! So I reproduced it in my project/scala.build without problem.
Note that I choose global scope to make tasks available for any project and any configuration
import sbt._
import Keys._
object TestBuild extends Build {
lazy val sampleTask = taskKey[Int]("A sample task")
lazy val intTask = taskKey[Int]("An int task")
override lazy val settings = super.settings ++ Seq(
intTask := 1 + 2 ,
sampleTask := intTask.value + 1
)
}
Now I'm trying to do something useful and enrich existing sbt key definitions with task that collects compiled class names
import sbt._
import Keys._
import sbt.inc.Analysis
import xsbti.api.ClassLike
import xsbt.api.Discovery.{isConcrete, isPublic}
object TestBuild extends Build {
lazy val debugAPIs = taskKey[List[String]]("list of all top-level definitions")
override lazy val settings = super.settings ++ Seq(
debugAPIs := getAllTop( compile.value )
)
private def getAllTop(analysis : Analysis) : List[String] =
Tests.allDefs(analysis).toList collect {
case c : ClassLike if isConcrete(c) && isPublic(c) => c.name
}
}
Now I get error from sbt:
Reference to undefined setting:
{.}/*:compile from {.}/*:debugAPIs (/home/sbt/project/build.scala:11)
So I have two questions:
How should I define debugAPIs properly so that it task would be available for all projects and all configurations?
How can I reproduce this error in synthetic configuration?
I'm more interested in the second question actually. I look for deep understanding of how sbt works because I'd like to write a plugin for it.
The problem is that you try to access a key value without a proper Scope.
The documentation gives us some hint here.
By default, all the keys associated with compiling, packaging, and
running are scoped to a configuration and therefore may work
differently in each configuration. The most obvious examples are the
task keys compile, package, and run; but all the keys which affect
those keys (such as source-directories or scalac-options or
full-classpath) are also scoped to the configuration.
Let's first focus on a very simple example, which maybe doesn't make much sense, but illustrates the problem. Lets assume that you want to redefine the compile task to itself.
override lazy val settings = super.settings ++ Seq (
compile := { compile.value }
)
Running this in SBT will give you an error, which is more or less like this
[error] {.}/*:compile from {.}/*:compile (/tmp/q-23723818/project/Build.scala:12)
[error] Did you mean compile:compile ?
We didn't specify the scope so SBT picked some defaults. The project was set to ThisBuild (meaning no specific project) and configuration set to Global. The setting was undefined in that context. However it's important to understand that a key is not a setting. The key can exist without scope, but the value of a key is attached to a scope. Note also that, if SBT won't find the value in the requested scope it can delegate to other scopes, but this is another topic.
How can we check this? Turns out that quite simple. Let's ignore the error, and let the SBT start.
If you type inspect compile you'll see that the inspect will look in compile:compile, where the value is defined. We can force it to look in a specific scope, e.g. inspect {.}/*:compile, will look in scope that gave us the error.
> inspect {.}/*:compile
[info] No entry for key.
Indeed it's undefined.
How to solve the issue? You have to give SBT the scope you're looking for. Naively you could try to add a configuration scope.
// this will NOT work
override lazy val settings = super.settings ++ Seq (
compile in Compile := { (compile in Compile).value }
)
Well but there is no global compile, there is only compile per project. You could overcome the issue by not overriding global settings, but the settings for a specific project, and specifying Compile configuration there.
lazy val root = project.in(file(".")).settings(Seq(
compile in Compile := {(compile in Compile).value}
): _*)
This would work,but what if you want to get the compile value regardless of where it is? This is where ScopeFilter comes in handy. Back to your original example. I assume you want to get compile's Analysis object from all the projects.
import sbt._
import Keys._
import sbt.inc.Analysis
import xsbti.api.ClassLike
import xsbt.api.Discovery.{isConcrete, isPublic}
object TestBuild extends Build {
val debugAPIs = taskKey[Seq[String]]("list of all top-level definitions")
val compileInAnyProject = ScopeFilter(inAnyProject, inConfigurations(Compile))
override lazy val settings = super.settings ++ Seq(
debugAPIs := {
getAllTop(compile.all(compileInAnyProject).value)
}
)
private def getAllTop(analyses : Seq[Analysis]) : Seq[String] =
analyses.flatMap { analysis =>
Tests.allDefs(analysis) collect { case c : ClassLike if isConcrete(c) && isPublic(c) => c.name }
}
}
What we created is a ScopeFilter filtering for any project, and in that projects for Compile configuration. Then we looked for all compile values.
You can configure the ScopeFilter to match your needs, and only filter for specific projects/configurations or even tasks. But the key to understand the problem is to remember that in SBT settings are always scoped.
Edit
You have asked how it comes that the compile is not defined globally but is available to every project. This is because there is Defaults.defaultSettings which define it. And each project include it. If you removed super.settings from your Build definition you'd see that among others compile is undefined.
And as if you should do it this way. Well overriding settings in your plugin is in general discouraged in Plugin Best Practices. However I recommend that you read it, together with Plugins chapter. It should give you an idea of how to proceed.
You can also get multiple values from multiple scopes by defining new task returning them. For example to get analyses with a project, you could use following piece of code.
object TestBuild extends Build {
val debugAPIs = taskKey[Seq[(String, String)]]("list of all top-level definitions")
val compileInAnyProject = ScopeFilter(inAnyProject, inConfigurations(Compile))
override lazy val settings = super.settings ++ Seq(
debugAPIs := {
getAllTop(analysisWithProject.all(compileInAnyProject).value)
}
)
lazy val analysisWithProject = Def.task { (thisProject.value, compile.value) }
private def getAllTop(analyses : Seq[(ResolvedProject, Analysis)]) : Seq[(String, String)] =
analyses.flatMap { case (project, analysis) =>
Tests.allDefs(analysis) collect { case c : ClassLike if isConcrete(c) && isPublic(c) => (project.id, c.name) }
}
}
Related
It is easy to get all instances of TestDefinition in IntegrationTest:
val tests: Seq[TestDefinition] = (definedTests in IntegrationTest).value
But how do I get all instances of xsbti.api.Definition in IntegrationTest? It used to be possible to do this:
val defs: Seq[Definition] = {
val analysis = (compile in IntegrationTest).value
analysis.apis.internal.values.flatMap(_.source.api.definitions)
}
(for example, for filtering tests based on the suite annotations: say, #RequiresCassandra or #RequiresCluster and so on). But analysis.apis has been removed--not sure when, but it's absent in SBT 1.3.8. I haven't found any documentation on what to use instead.
One of SBT's chief strengths, compared to such XML-based tools like Maven, is the ability to define build settings programmatically. It should be possible to filter tests based on anything in the test code itself, not only on test names. I can't believe something so useful—something that really places SBT above competitors—could be just removed.
Any suggestions?
Tests.allDefs returns Definitions given CompileAnalysis. For example,
val analysis: CompileAnalysis = (compile in IntegrationTest).value
val definitions: Seq[Definition] = Tests.allDefs(analysis)
val annotations: Seq[Annotation] = definitions.flatMap(_.annotations())
There was a change back in 2016 from
val compile = TaskKey[Analysis]("compile", "Compiles sources.", APlusTask)
to
val compile = TaskKey[CompileAnalysis]("compile", "Compiles sources.", APlusTask)
where
trait Analysis extends CompileAnalysis {
...
val apis: APIs
...
}
so now we have to cast to Analysis
analysis match { case analysis: Analysis => ... }
which is what allDefs does.
By trial and probably error, as a plugin author I've fallen into using the following style, which seems to work:
object AmazingPlugin extends AutoPlugin {
object autoImport {
val amaze = TaskKey[Amazement]("Do something totally effing amazing")
}
import autoImport._
lazy val ethDefaults : Seq[sbt.Def.Setting[_]] = Seq(
amaze in Compile := { amazeTask( Compile ).value },
amaze in Test := { amazeTask( Test ).value }
)
def amazeTask( config : Configuration ) : Initialize[Task[Amazement]] = Def.task {
???
}
}
Unfortunately, I do not actually understand how all of these constructs work, why it is an Initialize[Task[T]] I generate rather than a Task[T], for example. I assume that this idiom "does the right thing", which I take to mean that the amazeTask function generates some wrapper or seed or generator of an immutable Task for each Configuration and binds it just once to the appropriate task key. But it is entirely opaque to me how this might work. For example, when I look up Initialize, I see a value method that requires an argument, which I do not supply in the idiom above. I assume in designing the SBT configuration DSL tricks with implicits and/or macros were used, and shrug it off.
However, recently I've wanted to factor out some logic from my tasks into what are logically private functions, but which also require access to the value of tasks and settings. If just used private functions, gathering all the arguments would become repetitive boilerplate of the form
val setting1 = (setting1 in config).value
val setting2 = (setting2 in config).value
...
val settingN = (settingN in config).value
val derivedValue = somePrivateFunction( setting1, setting2 ... settingN )
everywhere I need to use get the value derived from settings. So it's better to factor all this into a derivedValue task, and I can replace all of the above with
derivedValue.value
Kewl.
But I do want derivedValue to be private, so I don't bind it to a task key. I just do this:
private def findDerivedValueTask( config : Configuration ) : Initialize[Task[DerivedValue]] = Def.task {
val setting1 = (setting1 in config).value
val setting2 = (setting2 in config).value
...
val settingN = (settingN in config).value
somePrivateFunction( setting1, setting2 ... settingN )
}
Now it works fine to implement my real, public task as...
def amazeTask( config : Configuration ) : Initialize[Task[Amazement]] = Def.task {
val derivedValue = findDerivedValueTask( config ).value
// do stuff with derivedValue that computes and Amazement object
???
}
Great! It really does work just fine.
But I have a hard time presuming that there is some magic by which this idiom does the right thing, that is generate an immutable Task object just once per config and reuse it. So, I think to myself, I should memoize the findDerivedValueTask function, so that after it generates a task, the task gets stored in a Map, whose keys are Configurations but whose values are logically Tasks.
But now my nonunderstanding of what happens behind the scenes bites. Should I store Initialize[Task[DerivedValue]] or just Task[DerivedValue], or what? Do I have to bother, does sbt have some clever magic that is already taking care of this for me? I really just don't know.
If you have read this far, I am very grateful. If you can clear this up, or point me to documentation that explains how this stuff works, I'll be even more grateful. Thank you!
Can someone help me create a SBT task that can support property-like arguments from command line?
lazy val myTask = inputKey[Unit]("my task")
myTask := {
if (directoryOpt.isEmpty) // directoryOpt comes from an optional command line argument: directory="~/downloads"
fullRunInputTask(inputKey, Compile, "example.MyTaskClass")
else
fullRunInputTask(inputKey, Compile, "example.MyTaskClass", directoryOpt.get)
}
Where the task can be run from command line like:
sbt myTask directory="~/downloads"
I did read the sbt doc at http://www.scala-sbt.org/0.13/docs/Input-Tasks.html. But it only explains how to create a task parser like sbt myTask option1 option2 which does not quite meet my need.
UPDATE:
I used jazmit's solution since that was an easy change. It works well! I will also try Mariusz's solution and update here.
You can use project/Build.scala along your build.sbt with your inputs. You can also use Commands instead of Tasks. Below, an example:
import sbt._
import Keys._
object CustomBuild extends Build {
def myTask = Command.args("myTask", "<name>"){ (state, args) =>
val argMap = args.map { s =>
s.split("=").toList match {
case n :: v :: Nil => n -> v
}
}.toMap
//println(argMap) //to see all argument pairs
//react on name in params list
println("Hi "+ argMap.getOrElse("name", "Unknown"))
state //Command can modify state, so you must to return it.
}
}
Now You have to add this command to you project, in build.sbt add
commands += myTask
Now you can use it:
> sbt "myTask name=Mario"
> Hi Mario
> sbt myTask
> sbt Hi Unknown
Hope, it'll help You!
more about commands:
you can find here
You can use environmental properties to achieve what you want quickly.
From the command line, set a property as follows:
sbt myTask -Ddirectory="~/downloads"
From the task, you can retrieve the value as follows:
val directory = System.getProperty("directory");
If you want to do something more solid with syntax checking, tab completion, etc, you can define an input task as detailed here. If you need property=value syntax, you can define this using the parser combinator library, eg:
import sbt.complete.DefaultParsers._
val myArgs: Parser[String] = "directory=" ~> StringEscapable
I want to create a new custom InputTask (testOnlyCustom)
that calls testOnly with the same arguments as given to testOnlyCustom and
that maybe, based on a SBT setting (condition), calls another task (let's call it pre) before calling testOnly. Here, I have to force "sequential" execution.
Thus:
If condition is true
testOnlyCustom com.dummy.TestSuite calls
pre and then
testOnly com.dummy.TestSuite
If condition is false
testOnlyCustom com.dummy.TestSuite calls
testOnly com.dummy.TestSuite
While I was able to achieve a solution with testCustom referring to pre and test (and thus having no arguments), I'm not able to solve the problem for testOnlyCustom, as InputTask used
Here is my code:
import sbt._
import sbt.Keys._
import sbt.Def._
import sbtsequential.Plugin._
object Simple extends sbt.Plugin {
import SimpleKeys._
object SimpleKeys {
lazy val condition = SettingKey[Boolean]("mode", "The mode.")
lazy val pre = TaskKey[Unit]("test-with-pre", "Do some pre step.")
lazy val testWithPre = TaskKey[Unit]("test-with-pre", "Run pre task beforehand")
lazy val testCustom = TaskKey[Unit]("test-custom", "Run pre (depending on condition) and then test.")
lazy val testOnlyWithPre = InputKey[Unit]("test-only-with-pre", "Run selected tests (like test-only in SBT) with pre executed before.")
lazy val testOnlyCustom = InputKey[Unit]("test-only-configured", "Run pre (depending on condition) and then call test-only.")
}
lazy val baseSettings: Seq[sbt.Def.Setting[_]] = Seq(
// this is working
testWithPre := test.value,
testWithPre <<= testWithPre.dependsOn( pre ),
testCustom := Def.taskDyn {
val c = condition.value
if (c) {
testWithPre
} else {
test
}
}.value,
//
// this is the part, where my question focuses on
//
testOnlyWithPre := testOnly.evaluated,
testOnlyWithPre <<= testOnlyWithPre.dependsOn( pre ),
// is this the correct approach?
testOnlyCustom := Def.inputTaskDyn {
// ???????????????????????????????
Def.task()
}.evaluated
)
lazy val testSimpleSettings: Seq[sbt.Def.Setting[_]] = baseSettings
}
Is inputTaskDyn the way to go? What exactly does it? I have just chosen it, because it seems to be dynamic version for InputTasks. Unfortunately, documentation is very rare on inputTaskDyn.
Is it okay to force "sequential" execution via dependsOn, like I did? I already have seen tha SBT 0.13.8 contains Def.sequantial. But this does not seem to be applicable to InputTasks?
How to convert an InputTask into a Task (to be used with taskDyn / inputTaskDyn) but still sticking to evaluated instesd of using an explicit parser? Or is there a way to reuse the testOnly parser?
Could someone illustrate a little more on .evaluated and .parsed of InputTask. What exactly does InputTask.parse do under the hood?
It would be great if someone could provide a working solution!
Many thanks in advance
Martin
Just for the record, the SBT 1 equivalent is
testOnlyWithPre := test.dependsOn(pre).value
and
testOnlyWithPre := testOnly.dependsOn(pre).evaluated
the best solution I could come up with is
testOnlyCustom := Def.inputTaskDyn {
val args: Seq[String] = spaceDelimited("").parsed
val c = condition.value
if (c) {
testOnlyWithPre.toTask(" " + args.head)
} else {
testOnly.toTask(" " + args.head)
}
}.evaluated
But still, this forces me to use a new parser (spaceDelimited) and I am not able to (re-)use the testOnly parser.
Any ideas how to reuse the parser?
Additional comments
First, OlegYch_ indicated on Freenode # sbt that coming up with SBT 0.13.9 the execution of Inputtasks will be possible via
def runInputTask[T](key: InputKey[T], input: String, state: State): (State, T)
in sbt.Extracted.scala.
Second, the testOnly parsers can be reused via sbt.Defaults#inputTests.
I have the following example build.sbt that uses sbt-assembly. (My assembly.sbt and project/assembly.sbt are set up as described in the readme.)
import AssemblyKeys._
organization := "com.example"
name := "hello-sbt"
version := "1.0"
scalaVersion := "2.10.3"
val hello = taskKey[Unit]("Prints hello")
hello := println(s"hello, ${assembly.value.getName}")
val hey = taskKey[Unit]("Prints hey")
hey <<= assembly map { (asm) => println(s"hey, ${asm.getName}") }
//val hi = taskKey[Unit]("Prints hi")
//hi <<= assembly { (asm) => println(s"hi, $asm") }
Both hello and hey are functionally equivalent, and when I run either task from sbt, they run assembly first and print a message with the same filename. Is there a meaningful difference between the two? (It seems like the definition of hello is "slightly magical", since the dependency on assembly is only implied there, not explicit.)
Lastly, I'm trying to understand why hey needs the map call. Obviously it results in a different object getting passed into asm, but I'm not quite sure how to fix this type error in the definition of hi:
sbt-hello/build.sbt:21: error: type mismatch;
found : Unit
required: sbt.Task[Unit]
hi <<= assembly { (asm) => println(s"hi, $asm") }
^
[error] Type error in expression
It looks like assembly here is a [sbt.TaskKey[java.io.File]][2] but I don't see a map method defined there, so I can't quite figure out what's happening in the type of hey above.
sbt 0.12 syntax vs sbt 0.13 syntax
Is there a meaningful difference between the two?
By meaningful difference, if you mean semantic difference as in observable difference in the behavior of the compiled code, they are the same.
If you mean, any intended differences in code, it's about the style difference between sbt 0.12 syntax sbt 0.13 syntax. Conceptually, I think sbt 0.13 syntax makes it easier to learn and code since you deal with T instead of Initialize[T] directly. Using macro, sbt 0.13 expands x.value into sbt 0.12 equivalent.
anatomy of <<=
I'm trying to understand why hey needs the map call.
That's actually one of the difference macro now is able to handle automatically.
To understand why map is needed in sbt 0.12 style, you need to understand the type of sbt DSL expression, which is Setting[_]. As Getting Started guide puts it:
Instead, the build definition creates a huge list of objects with type Setting[T] where T is the type of the value in the map. A Setting describes a transformation to the map, such as adding a new key-value pair or appending to an existing value.
For tasks, the type of DSL expression is Setting[Task[T]]. To turn a setting key into Setting[T], or to turn a task key into Setting[Task[T]], you use <<= method defined on respective keys. This is implemented in Structure.scala (sbt 0.12 code base has simpler implementation of <<= so I'll be using that as the reference.):
sealed trait SettingKey[T] extends ScopedTaskable[T] with KeyedInitialize[T] with Scoped.ScopingSetting[SettingKey[T]] with Scoped.DefinableSetting[T] with Scoped.ListSetting[T, Id] { ... }
sealed trait TaskKey[T] extends ScopedTaskable[T] with KeyedInitialize[Task[T]] with Scoped.ScopingSetting[TaskKey[T]] with Scoped.ListSetting[T, Task] with Scoped.DefinableTask[T] { ... }
object Scoped {
sealed trait DefinableSetting[T] {
final def <<= (app: Initialize[T]): Setting[T] = setting(scopedKey, app)
...
}
sealed trait DefinableTask[T] { self: TaskKey[T] =>
def <<= (app: Initialize[Task[T]]): Setting[Task[T]] = Project.setting(scopedKey, app)
...
}
}
Note the types of app parameters. Setting key's <<= takes Initialize[T] whereas the task key's <<= takes Initialize[Task[T]]. In other words, depending on the the type of lhs of an <<= expression the type of rhs changes. This requires sbt 0.12 users to be aware of the setting/task difference in the keys.
Suppose you have a setting key like description on the lhs, and suppose you want to depend on name setting and create a description. To create a setting dependency expression you use apply:
description <<= name { n => n + " is good." }
apply for a single key is implemented in Settings.scala:
sealed trait Keyed[S, T] extends Initialize[T]
{
def transform: S => T
final def apply[Z](g: T => Z): Initialize[Z] = new GetValue(scopedKey, g compose transform)
}
trait KeyedInitialize[T] extends Keyed[T, T] {
final val transform = idFun[T]
}
Next, instead of description, suppose you want to create a setting for jarName in assembly. This is a task key, so rhs of <<= takes Initialize[Task[T]], so apply is not good. This is where map comes in:
jarName in assembly <<= name map { n => n + ".jar" }
This is implemented in Structure.scala as well:
final class RichInitialize[S](init: Initialize[S]) {
def map[T](f: S => T): Initialize[Task[T]] = init(s => mktask(f(s)) )
}
Because a setting key extends KeyedInitialize[T], which is Initialize[T], and because there's an implicit conversion from Initialize[T] to RichInitialize[T] the above is available to name. This is an odd way of defining map since maps usually preserves the structure.
It might make more sense, if you see similar enrichment class for task keys:
final class RichInitializeTask[S](i: Initialize[Task[S]]) extends RichInitTaskBase[S, Task] {...}
sealed abstract class RichInitTaskBase[S, R[_]] {
def map[T](f: S => T): Initialize[R[T]] = mapR(f compose successM)
}
So for tasks, map maps from a task of type S to T. For settings, we can think of it as: map is not defined on a setting, so it implicitly converts itself to a task and maps that. In any case, this let's sbt 0.12 users to think: Use apply for settings, map for tasks. Note that apply ever goes away for task keys as they extend Keyed[Task[T], Task[T]]. This should explain:
sbt-hello/build.sbt:21: error: type mismatch;
found : Unit
required: sbt.Task[Unit]
Then there's the tuple issue. So far I've discussed dependencies to a single setting. If you want to depend on more, sbt implicitly adds apply and map to Tuple2..N to handle it. Now it's expanded to 15, but it used to be up till only Tuple9. Seeing from a new user's point of view, the idea of invoking map on a Tuple9 of settings so it generates a task-like Initialize[Task[T]] would appear alien. Without changing the underlying mechanism, sbt 0.13 provides much cleaner surface to get started.