Search code examples
javascriptantfailonerror

ant javascript failonerror


I have an ant task that includes embedded javascript. I'd like to have the target fail or succeed based on some logic I run in the javascript:

<target name="analyze">
    <script language="javascript">
    <![CDATA[
            importClass(java.io.File);
            importClass(java.io.FileReader)
            importClass(java.io.BufferedReader)

            String.prototype.startsWith = function(str) {
                return (this.indexOf(str) === 0);
            }

            String.prototype.endsWith = function(str) {
                var lastIndex = this.lastIndexOf(str);
                return (lastIndex != -1) && (lastIndex + str.length == this.length);
            }

            //setup the source directory
            srcDir = project.getProperty("MY_HOME") + "/foo/src";

            if(srcDir.startsWith("/foo") { 
            //TARGET SHOULD PASS
            } else { 
            //TARGET SHOULD FAIL
            }

    ]]>
    </script>
</target>

Solution

  • You could make Ant exit via the Exit API, but that throws a build exception which will lead to a messy stack trace. The cleanest method would be to set a property in the javascript then test it using the fail task:

    Javascript:

    project.setProperty( "javascript.fail.message", "There was a problem" );
    

    Ant, immediately after the script task:

    <fail if="javascript.fail.message" message="${javascript.fail.message}" />