How to Filter unwanted libs from your .war File in sbt

Nov 10, 2010 02:27 · 370 words · 2 minutes read Scala sbt

I use the Simple Build Tool for all my Scala Projects, including the Engine this Blog runs on. Obviously, the engine is a web project and the output of the build process a .war file. I noticed that the .war file is annoyingly large and when I had a peek inside I found a lot of jars that should not have been there. Strangely, sbt added the source and javadoc jars of all libs where possible and not only the binaries. Also some dependencies were added that where not necessary at runtime. E.g.: my own little utility lib has a compile dependency on scala-swing but if you use none of the swing utilities, it is unnecessary at runtime.

I quickly found the necessary def I had to overwrite to filter out ressources, but I found it a bit tricky to build the correct paths, so I thought I’d share my solution. In your project definition, add the following (adjust to the files you want to filter, of course):

/*add jars that should not appear in the final war here*/
override def webappUnmanaged = 
    temporaryWarPath / "WEB-INF" / "lib" * "*-sources.jar" +++
    temporaryWarPath / "WEB-INF" / "lib" * "*-javadoc.jar" +++  
    temporaryWarPath / "WEB-INF" / "lib" * "derby*.jar" +++
    temporaryWarPath / "WEB-INF" / "lib" * "h2*.jar" +++
    temporaryWarPath / "WEB-INF" / "lib" * "scala-swing*.jar"

The tricky part for me was to find out which path prefix to use to create the paths to exclude. The temporaryWarPath is the folder containing the exploded .war used for packing the resulting .war file and for running jetty from sbt. I tried the actual file path first, e.g.:

//This does not work!
managedDependencyPath / "compile" / "baselib_2.8.0-0.1-sources.jar"

That may seem logical, but the filtering is applied only after the intermediate folder for the web archive is built, so I had to exclude resources from that intermediate folder. As you can see, you can also supply wildcards, which was useful for me to filter out all source jars in one line. Also, I don’t have to change the filtering when a new version of scala-swing or the h2 database is added to the dependencies. Obviously, this works for any resource in the .war file, not only libs.