Using ‘resourceGenerators’ in sbt

My current project deploys in OpenShift as a fat-jar (it means a runnable jar file packed together with all its classpath dependencies) . It also uses sbt (Scala Build Tool).

There was a need to add a special file in the resulted fat-jar which had to be generated at the compile time. So after hours of searchings I decided to use resourceGenerators in sbt.

This plug-in makes it easy to generate almost any resources and add them to the final jar. I’ve needed to add custom pom.properties file with a few lines of parameters like groupId, artifactId and version. Don’t even ask me why I wanted such functionality 🙂

My final implementation looks like following:

resourceGenerators in Compile += Def.task {
      val file = ((resourceDirectory in Compile).value / "META-INF" /  "pom.properties")
      val contents = groupId=%s\nartifactId=%s\nversion=%s".format("com.sample","Triad", "1.0.0-SNAPSHOT")
      IO.write(file, contents)
      Seq(file)
    }

So here I defined a file pom.properties in the /resources/META-INF folder and filled it with a content stored in contents.

As a result we see pom.properties in the META-INF folder of the final built jar:

Conclusion

resourceGenerators is a powerful sbt feature which allows you to generate almost any resources and put them to the final result.