Ant Contrib If for optional JAR META-INF

I have a scenario where I try to reuse the same build.xml file for multiple projects. In each case, the ultimate goal is to dist that the JARs are all up. The only difference is that some of the projects have a src/main/java/META-INF/* , while others do not (and just have a src/main/java/* directory).

I want to use the Ant -Contrib <if/> task to optionally define the META-INF/ directory if the assembly sees the src/main/java/META-INF/* . So something like this:

 <jar jarfile="myapp.jar"> <if> <available file="src/main/java/META-INF" /> <then> <!-- Copy everything from src/main/java/META-INF into the JAR META-INF directory. But how?!? --> <echo message="I'm trying to copy META-INF!" /> </then> </if> </jar> 

But I'm choking on two things here:

  • When I run this target, I get an assembly exception, stating that I cannot nest <if/> inside the <jar/> task; and
  • I'm not sure how to configure the <jar/> task to create the META-INF at the root of the class path and copy the entire contents of src/main/java/META-INF .

Any thoughts? Thanks in advance.

+4
source share
3 answers

It looks like you want to use a more modular build configuration. What about two goals:

 <target name="jar"> <!-- Normal JAR tasks like you currently have (sans the metainf stuff). --> </target> <target name="jar-with-metainf"> <jar destfile="test.jar"> <fileset dir="classes"/> <metainf dir="src/main/java/META-INF"/> </jar> </target> 

Then, when you want to create your META-INF/ -containing projects, you simply run jar-with-metainf .

+1
source

You make it harder than necessary. Just use the following task and the META-INF folder will be included in the jar if it exists, and ignored if it is not:

 <target name="dist"> <jar destfile="test.jar"> <fileset dir="classes"/> <-- or whatever directory you want to put in the jar --> <metainf dir="src/main/java/META-INF" erroronmissingdir="false"/> </jar> </target> 
+4
source

The message is correct because <if> is a task in itself, and you cannot attach other tasks to the <jar> task. However, what you can do is use the <if> task to determine the appropriate set of files with an identifier, and then use refid to include this in the JAR:

 <if> <available file="src/main/java/META-INF" /> <then> <fileset id="src.metainf" dir="src/main/java/META-INF" /> </then> <else> <fileset id="src.metainf" dir="." excludes="**/*" /> </else> </if> <jar destfile="myapp.jar"> <metainf refid="src.metainf" /> </jar> 

As JB Nizet points out, you really don't need this to answer this specific question, but it is a useful trick you need to know for other situations. I find this more useful when defining <path> elements rather than file sets.

+1
source

All Articles