Adding sbt native packager plugin in SBT - sbt

I have a very organized build file that is composed of the following scala files:
Build.scala - the main Build file
Dependencies.scala - where I define the dependencies and the versions
BuildSettings.scala - where I define the build settings
plugins.sbt
A snippet of the Build.scala is as below:
import sbt._
import Keys._
object MyBuild extends Build {
import Dependencies._
import BuildSettings._
import NativePackagerHelper._
// Configure prompt to show current project
override lazy val settings = super.settings :+ {
shellPrompt := { s => Project.extract(s).currentProject.id + " > " }
}
// Define our project, with basic project information and library dependencies
lazy val project = Project("my-project", file("."))
.settings(buildSettings: _*)
.settings(
libraryDependencies ++= Seq(
Libraries.scalaAsync
// Add your additional libraries here (comma-separated)...
)
).enablePlugins(JavaAppPackaging, DockerPlugin)
}
All the 4 files that I mentioned above are in the same directory which is inside the project directory. But when I run this build file, I get the following error:
not found value: NativePackagerHelper
Any clues why his this?

I figured out what the problem was. I had to use the following in my build.properties
sbt.version=0.13.11
I originally had 0.13.6 and it was causing the import statements to fail!

Related

Best place to declare own settings so I can access them from sbt shell and my .sbt and .scala build files?

My settings are declared in project/Utils.scala in an object BuildSupport and are made available in .sbt and .scala files with import BuildSupport._.
However, this doesn't work for sbt shell as seen in above screenshot since I can't import them there. For completeness sake, I have tried eval import BuildSupport._ but all that got me was <eval>:1: error: illegal start of simple expression.
How do I have to define own settings and tasks so I can access them from:
project/*.scala,
*.sbt and
sbt shell?
I assume defining them in an AutoPlugin would work, but I'd rather not have to go to that length. Is there any other way?
Declaring an adhoc AutoPlugin (https://www.scala-sbt.org/1.x/docs/Plugins.html) is the way to go.
Auto plugins ...
can define autoImport object, which is automatically included into build.sbt. This can be used for keys.
can define globalSettings, buildSettings, or projectSettings to inject settings and tasks either at the build-level or at the subproject level. This should become available in sbt shell.
A plugin doesn't have to be a published on its own. You can declare one inside project/*.scala like any other Scala object.
The plugin in the linked documentation is great for copy-pasting:
package sbthello
import sbt._
import Keys._
object HelloPlugin extends AutoPlugin {
override def trigger = allRequirements
object autoImport {
val helloGreeting = settingKey[String]("greeting")
val hello = taskKey[Unit]("say hello")
}
import autoImport._
override lazy val globalSettings: Seq[Setting[_]] = Seq(
helloGreeting := "hi",
)
override lazy val projectSettings: Seq[Setting[_]] = Seq(
hello := {
val s = streams.value
val g = helloGreeting.value
s.log.info(g)
}
)
}

Additional resource generator with sbt native packager

I have a submodule, that is compiled by invoking external command. I would like to include generated file into jar. So I wrote a task:
```
myTask := {
import sys.process.stringSeqToProcess
Seq("my", "command") !
}
unmanagedResourceDirectories in Compile += baseDirectory.value / "dist"
cleanFiles <+= baseDirectory { base => base / "dist" }
Keys.`package` <<= (Keys.`package` in Compile) dependsOn npmBuildTask.toTask
and when I invoke mySubmodule/package task it works well. But when I invoke stage task from sbt-native-packager my task is ignored(is not executed).
There are a couple of options to solve this issue. I assume you want to add the dist folder to your resulting application jar.
Your configuration doesn't work because stage doesn't depend on package. This results npmBuildTask not being called.
1. Add dependency to stage
The easiest way to fix this is by simply adding the npmBuildTask as a dependency to stage
stage <<= stage dependsOn npmBuildTask.toTask
I wouldn't recommend this approach.
2. Resource generators
SBTs Resoure Generators are exactly defined for this purpose. An inline version could look like this
resourceGenerators in Compile += Def.task {
streams.value.log.info("running npm generator")
val base = (resourceManaged in Compile).value / "dist"
// A resource generator returns a Seq[File]. This is just an example
List("index.js", "test.js").map { file =>
IO.writeLines(base / file, List("var x = 1"))
base / file
}
}.taskValue
Or you could extract this in an AutoPlugin to separate the "what" and "how.
3. AutoPlugin and resource generators
Create project/NpmPlugin.scala and add the following content
import sbt._
import sbt.Keys._
import sbt.plugins.JvmPlugin
object NpmPlugin extends AutoPlugin {
override val requires = JvmPlugin
override val trigger = AllRequirements
object autoImport {
val npmBuildTask = TaskKey[Seq[File]]("npm-build-task", "Runs npm and builds the application")
}
import autoImport._
override def projectSettings: Seq[Setting[_]] = Seq(
// define a custom target directory for npm
target in npmBuildTask := target.value / "npm",
// the actual build task
npmBuildTask := {
val npmSource = (target in npmBuildTask).value
val npmTarget = (resourceManaged in Compile).value / "dist"
// run npm here, which generates the necessary values
streams.value.log.info("running npm generator")
// move generated sources to target folder
IO.copyDirectory(npmSource, npmTarget)
// recursively get all files in the npmTarget
(npmTarget ***).get
},
resourceGenerators in Compile += npmBuildTask.taskValue
)
}
The build.sbt will then look like this
name := "resource-gen-test"
version := "1.0"
enablePlugins(JavaAppPackaging)
Pretty clean :)
4. Use mappings
Last but not least you could use mappings. They are the low level detail that drives a lot of the package-generation in sbt. The main idea of this solution is to
Create a task that returns a mapping definition ( Seq[(File, String)] )
Append this to the appropriate mappings
The advantage of this approach is that you are more flexible where you want to put your mappings.
import sbt._
import sbt.Keys._
import sbt.plugins.JvmPlugin
import com.typesafe.sbt.SbtNativePackager.Universal
import com.typesafe.sbt.SbtNativePackager.autoImport.NativePackagerHelper._
object NpmMappingsPlugin extends AutoPlugin {
override val requires = JvmPlugin
override val trigger = AllRequirements
object autoImport {
val npmBuildTask = TaskKey[Seq[(File, String)]]("npm-build-task", "Runs npm and builds the application")
}
import autoImport._
override def projectSettings: Seq[Setting[_]] = Seq(
// define a custom target directory for npm
target in npmBuildTask := target.value / "npm" / "dist",
// the actual build task
npmBuildTask := {
val npmTarget = (target in npmBuildTask).value
// run npm here, which generates the necessary values
streams.value.log.info("running npm generator")
// recursively get all files in the npmTarget
// contentOf(npmTarget) would skip the top-level-directory
directory(npmTarget)
},
// add npm resources to the generated jar
mappings in (Compile, packageBin) ++= npmBuildTask.value,
// add npm resources to resulting package
mappings in Universal ++= npmBuildTask.value
)
}
As you can see in this approach we can easily add the resulting files to different mappings.
However I only recommend this approach if you need this kind of flexibility as it requires a bit more knowledge of native-packager.

How to execute task that calls clean on subprojects without using aggregation?

I want make a take cleanAll that executes the clean task on a number of subprojects. I don't want to use aggregation just for the sake of clean.
We've run into issues with play's asset routes when we've been using submodules.
It's well documented how to create a new task, but how do I call a task on a subproject?
Based on the example by Jacek Laskowski I've come up with the following plugin that should be placed in your /project folder:
import sbt._
import sbt.AutoPlugin
import sbt.Keys._
import sbt.plugins.JvmPlugin
object CleanAllPlugin extends AutoPlugin {
val cleanAll = taskKey[Unit]("Cleans all projects in a build, regardless of dependencies")
override def requires = JvmPlugin
override def projectSettings = Seq(
cleanAllTask
)
def cleanAllTask = cleanAll := Def.taskDyn {
val allProjects = ScopeFilter(inAnyProject)
clean.all(allProjects)
}.value
}
The plugin can now be added to the root project for usage:
val main = Project("root", file("."))
.enablePlugins(CleanAllPlugin)
It can be executed in SBT by calling: cleanAll
Use the following build.sbt:
val selectDeps = ScopeFilter(inDependencies(ThisProject))
clean in Compile := clean.all(selectDeps).value
It assumes that the build.sbt file is in the project that has clean executed on itself and dependsOn projects.
If you need it in project/Build.scala, just add the following:
val selectDeps = ScopeFilter(inDependencies(ThisProject))
val cleanInSubprojects = Seq(
clean in Compile := clean.all(selectDeps).value
)
and add cleanInSubprojects to settings of every project:
// definition of a project goes here
.settings(cleanInSubprojects: _*)

How does one build a custom Bootstrap WebJar with sbt?

I want to build a WebJar that contains a brand-customized version of Bootstrap from LESS source. I have sbt.version=0.13.5-M4 in project/build.properties and addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.0.0-M2a") in project/plugins.sbt. My build.sbt looks like this:
import com.typesafe.web.sbt.WebPlugin
import com.typesafe.jse.sbt.JsEnginePlugin
import com.typesafe.web.sbt.WebPlugin.WebKeys
name := "brand-assets"
organization := "com.example"
version := "0.0.1-SNAPSHOT"
WebPlugin.webSettings
JsEnginePlugin.jsEngineSettings
lazy val root = (project in file(".")).addPlugins(SbtWeb)
excludeFilter in Assets := new PatternFilter("""[^_].*\.less""".r.pattern)
The errors I get are:
build.sbt:1: error: object web is not a member of package com.typesafe
import com.typesafe.web.sbt.WebPlugin
^
build.sbt:2: error: object sbt is not a member of package com.typesafe.jse
import com.typesafe.jse.sbt.JsEnginePlugin
^
build.sbt:15: error: value addPlugins is not a member of sbt.Project
lazy val root = (project in file(".")).addPlugins(SbtWeb)
^
sbt.compiler.EvalException: Type error in expression
What am I missing?
So far i unserstand your question, you should add the following line to plugin.sbt:
resolvers += Resolver.typesafeRepo("releases")
as disused at https://github.com/sbt/sbt-less/issues/31

How configure aspectj compilation in playframework 2.1.1

I have added to plugins.sbt this declaration
addSbtPlugin("com.typesafe.sbt" % "sbt-aspectj" % "0.9.0")
Now I would like to configure this plugin to compile my java controller classes using aspect library org.springframework:spring-aspects:3.1.4 as with aspectj-maven-plugin
I have set this configuration :
import sbt._
import Keys._
import play.Project._
import com.typesafe.sbt.SbtAspectj._
import com.typesafe.sbt.SbtAspectj.AspectjKeys._
object ApplicationBuild extends Build {
val appDependencies = Seq(javaCore)
val main = play.Project(appName, appVersion, appDependencies).settings(
AspectjKeys.verbose in Aspectj := true,
AspectjKeys.showWeaveInfo in Aspectj := true,
AspectjKeys.inputs in Aspectj <+= compiledClasses
)
}
But it does fail.
[error] Reference to undefined setting:
[error]
[error] aspectj:inputs from aspectj:inputs
I am really a newbie with the sbt thing.
The plugin github page : https://github.com/sbt/sbt-aspectj
Ok, I make it works, thanks to sbt mailing list, cf. https://groups.google.com/forum/?fromgroups=#!topic/simple-build-tool/MUXyfKigC7w
and the playframework mailing list also, cf. https://groups.google.com/forum/?fromgroups=#!topic/play-framework/RfJFEwVbUUk
It was not very hard in fact but something you can't see things.
import sbt._
import Keys._
import play.Project._
import com.typesafe.sbt.SbtAspectj._
import com.typesafe.sbt.SbtAspectj.AspectjKeys._
object ApplicationBuild extends Build {
val appDependencies = Seq(javaCore, filters)
val main = play.Project(appName, appVersion, appDependencies)
.settings(aspectjSettings: _*)
.settings(
libraryDependencies += "org.springframework" % "spring-aspects" % "3.1.4.RELEASE",
libraryDependencies += "org.springframework.security" % "spring-security-aspects" % "3.1.4.RELEASE",
sourceLevel := "-1.7",
verbose in Aspectj := false,
showWeaveInfo in Aspectj := false,
inputs in Aspectj <+= compiledClasses,
binaries in Aspectj <++= update map { report =>
report.matching(
moduleFilter(organization = "org.springframework", name = "spring-aspects")
|| moduleFilter(organization = "org.springframework.security", name = "spring-security-aspects")
)
},
products in Compile <<= products in Aspectj,
products in Runtime <<= products in Compile
)
}
Don't forget to add this in in plugins.sbt, with a new line separator between declaration
addSbtPlugin("com.typesafe.sbt" % "sbt-aspectj" % "0.9.0")

Resources