Search code examples
javamaven-2jarpackagingbuildr

buildr: package dependencies into a single jar


I have a java project that is built with buildr and that has some external dependencies:

repositories.remote << "http://www.ibiblio.org/maven2"
repositories.remote << "http://packages.example/"

define "myproject" do
  compile.options.target = '1.5'
  project.version = "1.0.0"
  compile.with 'dependency:dependency-xy:jar:1.2.3'
  compile.with 'dependency2:dependency2:jar:4.5.6'

  package(:jar)
end

I want this to build a single standalone jar file that includes all these dependencies.

How do I do that?

(there's a logical followup question: How can I strip all the unused code from the included dependencies and only package the classes I actually use?)


Solution

  • This is what I'm doing right now. This uses autojar to pull only the necessary dependencies:

    def add_dependencies(pkg)
      tempfile = pkg.to_s.sub(/.jar$/, "-without-dependencies.jar")
      mv pkg.to_s, tempfile
    
      dependencies = compile.dependencies.map { |d| "-c #{d}"}.join(" ")
      sh "java -jar tools/autojar.jar -baev -o #{pkg} #{dependencies} #{tempfile}"
    end
    

    and later:

    package(:jar)
    package(:jar).enhance { |pkg| pkg.enhance { |pkg| add_dependencies(pkg) }}
    

    (caveat: I know little about buildr, this could be totally the wrong approach. It works for me, though)