Ant – Stop the script without failing the build

We can use the <fail> Ant task to exit the Ant script but this will fail the build.

Sometimes we may have some checking during the build such that it could exit peacefully without build failure in certain cases. So in this case, we can’t use the <fail> Ant task.

A workaround is to use the <if> Ant-contrib task to create a boolean variable and whether continue or not could be determined by checking this boolean in the <target> if attribute.

Here is an example:
build.xml

<project name="test" default="" basedir="." xmlns:artifact="antlib:org.apache.maven.artifact.ant">

  <!-- Load the ant contrib lib -->
  <taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
      <pathelement location="${basedir}/ant-lib/ant-contrib-1.0b3.jar"/>
    </classpath>
  </taskdef>

  <target name="step1">
    <echo message="Step 1 is running"/>
    <if>
      <equals arg1="${var1}" arg2="${var2}" />
      <then>
        <property name="continue" value="true"/>
      </then>
      <else>
        <property name="continue" value="false"/>
      </else>
    </if>
  </target>
  
  <target name="step2" depends="step1" if="${continue}">
    <echo message="Step 2 is running"/>
  </target>

</project>

 

Results:
ant step2
stop-ant-script-without-failing-the-build-1
 

ant step2 -Dvar1=abc -Dvar2=def
stop-ant-script-without-failing-the-build-2
 

ant step2 -Dvar1=abc -Dvar2=abc
stop-ant-script-without-failing-the-build-3
 

As you can see above, step2 will run only if var1 = var2 and all three builds are successful .

Done =)

Reference:

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.