tg44
tg44

Reputation: 850

How do I call a dependent library function from an sbt task?

I have a CLI tool written in Java which can modify some source with the added params. For example, it can rename an enum value across a whole project.

I want to write an sbt task that can run this tool from my project dir with the given params, like sbt 'enums -rename A B'. My tool can be injected to the project through the sbt dependencies.

I skimmed through the book sbt in Action looking for an answer, but those examples are not this specific.

My build.sbt (far from working):

name := """toolTestWithActivator"""

version := "1.0-SNAPSHOT"

resolvers += "Local Repository" at "file://C:/Users/torcsi/.ivy2/local"

lazy val root = (project in file(".")).enablePlugins(PlayJava)

scalaVersion := "2.11.6"

libraryDependencies ++= Seq(
    "tool" % "tool_2.11" % "1.0",
    javaJdbc,
    javaEbean,
    cache,
    javaWs
)

val mytool = taskKey[String]("mytool")
mytool := {
    com.my.tool.Main
}

Can sbt handle this type of task/dependency structure, or do I need to do this another way?

Upvotes: 1

Views: 645

Answers (1)

Olivier Samyn
Olivier Samyn

Reputation: 1115

SBT is recursive: it compiles .sbt files and .scala files under the project folder and use those to execute your build (in fact you can see sbt as a library that helps you producing builds).

So, as you need your library to define a task, that one is a dependency of your build.sbt file (and not a dependency of your project).

To declare that the build.sbt file depends on your library, just create a ".sbt" file in the project folder; example:

project/dependencies.sbt

libraryDependencies += "tool" %% "tool" % "1.0"

and in build.sbt add:

val mytool = taskKey[Unit]("mytool")
mytool := {
    com.my.tool.main(Array())
}

Some comments:

  • be careful with the scala version used: as sbt 0.13 is compiled with scala 2.10; your library should also be compiled for scala 2.10 (the package should be tools_2.10 ). And the new sbt 1.0 is compiled with scala 2.12.
  • I used the %% notation, so that sbt adds by itself the expected scala version.
  • I supposed your cli tool defines a classic java main method (or the scala equivalent). So, the argument should be an Array of String (here an empty one) and it returns Unit (void in java).

Some reference to understand the solution: http://www.scala-sbt.org/0.13/docs/Organizing-Build.html

Upvotes: 2

Related Questions