mogli
mogli

Reputation: 1609

Multiple jars for multiple test packages in sbt

Is there any way in sbt (custom task or plugin) to pack packages in separate jars.

alt

For example :- In this sample project, there should be 6 jar files generated for packages eg1, eg2, eg3, eg4, eg49, eg50

Given, there is no inter dependency of any package on each other. Simplified project for reference :- https://github.com/moglideveloper/MultipleSpecJars


Final Edit :-

I managed to create jar file with the regex name (where regex pointing to some package name) with below task :-

sbt createCompactJar

Now, I am stuck how to reuse this for a sequence of regexes.

Below is the simplified logic for createCompactJar :-

lazy val multipleSpecJars = (project in file("."))
  .settings(libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.2")

//A different configuration which would redefine the packageBin task within this new configuration
//so it does not change the original definition of packageBin
lazy val CompactJar = config("compactJar").extend(Compile)
inConfig(CompactJar)(Defaults.compileSettings)

val allRegexes = List("eg1", "eg2", "eg3", "eg4", "eg49", "eg50")

/*
Below logic only works for one regex (regexToInclude),
How to convert this logic for a sequence of regexes(allRegexes) ?
 */
val regexToInclude = "eg3"

lazy val createCompactJar = taskKey[Unit]("create compact jar based on regex")

/*
createCompactJar
1. Depends on packageBin sbt task.
2. call packageBin and then rename jar that is generated by
   packageBin in same directory to <regex>.jar
 */
createCompactJar := {
  println("now creating jar for regex : " + regexToInclude)
  (packageBin in CompactJar).value

  //Logic to rename generated jar file to <regex>.jar
  val jarFileDir = (baseDirectory).value + "/target/scala-2.12"
  val jarFilePath = jarFileDir + "/multiplespecjars_2.12-0.1.0-SNAPSHOT-compactJar.jar"
  val sourceFile = new File(jarFilePath)
  val destinationFile = new File(jarFileDir + "/" + regexToInclude + ".jar")
  println(s"renaming $sourceFile to $destinationFile")
  sourceFile.renameTo(destinationFile)
}

mappings in(CompactJar, packageBin) := {
  val original = (mappings in(CompactJar, packageBin)).value
  original.filter { case (file, toPath) => toPath.startsWith(regexToInclude) }
}

unmanagedSourceDirectories in CompactJar := (unmanagedSourceDirectories in Compile).value

Upvotes: 2

Views: 231

Answers (1)

agilesteel
agilesteel

Reputation: 16859

I would go for subprojects. I have to admit I don't understand your use case entirely (why would you want to package tests in the first place?), but subprojects allow you to package things independently from each other. You even get parallel compilation out of the box and you could even have dependencies between the subprojects, but you don't seem to be needing any.

Here is a larger example.

Hope this helps. Cheers and happy coding! :)

Upvotes: 3

Related Questions