Jenkins : Ant Job Clone script

Ant target to clone a Template Hudson Job remotely

If you have a subversion repository that conforms to the suggestions laid down by the pragmatic programmers, then this ant target should allow you to trivially create Jobs on Hudson based on a template job and the current branch that your working copy is in.

I hope someone out there finds this useful.  There are no dependencies on anything other than Ant and Subversion, but unfortunately due to the lack of a decent POST task there is a dependancy on a Java+Ant combination that supports script tasks of type javascript (sorry).

 This script could probably be improved especially around the regular expression replacements, a filter chain would probably be better.

<!--
Copyright (c) 2009, Ciaran Jessup
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY CIARAN JESSUP ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL CIARAN JESSUP BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<project name="OurProject" default="build" basedir=".">
    <property name="hudsonServer" value="http://hudsonServer/hudson"/>
    <property name="ciTemplate" value="CITemplateJobName"/>
    <property name="hudson_config_file" value="temp_hudson_ci_config_file.xml" />
    <target name="build">
        <exec executable="svn" outputproperty="svnlog_out">
            <arg line="info"/>
        </exec>
		<script language="javascript"><![CDATA[
			branchURLPattern= /^\sURL:\s+(.+\/branches\/([^\s\/]+))\/?.*/m
                        matches= svnlog_out.match(branchURLPattern);
			project.setNewProperty("branchURL", matches[1] );
			project.setNewProperty("branchName", matches[2] );
		]]></script>

        <!-- test to see if the CI build for this branch has been created yet -->
        <delete file="${hudson_config_file}" failonerror="false"/>
        <get src="${hudsonServer}/job/${branchName}/config.xml" dest="${hudson_config_file}" ignoreerrors="true"/>
        <available file="${hudson_config_file}" type="file" property="branch.already.present"/>
        <fail if="branch.already.present" message="${branchName} already has a CI Build on Hudson"/>
        <echo message=""/>
        <echo message=""/>
        <echo message ="Found URL TO SVN: ${branchURL}"/>
        <echo message ="Determined Branch name to be: ${branchName}"/>
        <echo message=""/>
        <!-- Ask the user to see if they really do want to carry on -->
        <input message="Are you sure you want to create a CI build on hudson for ${branchName} (y/n)?"
                 validargs="y,n"
                 addproperty="do.delete"/>
        <condition property="do.abort">
                <equals arg1="n" arg2="${do.delete}"/>
        </condition>
        <fail if="do.abort">CI Build creation aborted by user.</fail>

        <!-- Create the new job based on the templated job -->
        <antcall target="_doPost">
            <param name="url" value="${hudsonServer}/createItem?name=${branchName}&amp;mode=copy&amp;from=${ciTemplate}"/>
        </antcall>

        <!-- Update the job configuration -->
        <get src="${hudsonServer}/job/${branchName}/config.xml" dest="${hudson_config_file}"/>
        <replaceregexp file="${hudson_config_file}" match="&lt;description&gt;.+&lt;/description&gt;" replace="&lt;description&gt;The ${branchName} branch&lt;/description&gt;"/>
        <replaceregexp file="${hudson_config_file}" match="&lt;remote&gt;.+&lt;/remote&gt;" replace="&lt;remote&gt;${branchURL}&lt;/remote&gt;"/>
        <replaceregexp file="${hudson_config_file}" match="&lt;local&gt;.+&lt;/local&gt;" replace="&lt;local&gt;${branchName}&lt;/local&gt;"/>

        <!-- post our modified configuration back to hudson -->
        <loadfile property="hudson_ci_config" srcFile="${hudson_config_file}"/>
        <antcall target="_doPost">
            <param name="url" value="${hudsonServer}/job/${branchName}/config.xml"/>
            <param name="data" value="${hudson_ci_config}"/>
        </antcall>

        <!-- Finally enable the job -->
        <antcall target="_doPost">
            <param name="url" value="${hudsonServer}/job/${branchName}/enable"/>
        </antcall>

        <!-- Be a good citizen and delete our temp file -->
        <delete file="${hudson_config_file}" failonerror="false"/>
    </target>

    <target name="_doPost">
        <script language="javascript"><![CDATA[
            importPackage(java.net);
            importPackage(java.io);
            importClass(java.lang.StringBuffer);

            url= new URL(project.getProperty("url"));
            conn = url.openConnection();
            conn.setRequestMethod( "POST" );
            conn.setDoOutput(true);

            data= project.getProperty("data");
            if( data ) {
                conn.setRequestProperty("Content-Length", "" +data.getBytes().length);
            }
            wr = new OutputStreamWriter(conn.getOutputStream());
            if( data ) {
                wr.write(data);
            }
            wr.flush();
            wr.close();

            // Get the response
            try {
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                stringBuffer= new StringBuffer();
                var line;
                while ((line = rd.readLine()) != null) {
                    stringBuffer.append(line+"\n"); // Gonna mess with linebreaks here..shame.
                }
                // None of the targets above care about the response so just forget about it :)
            }catch( e ) {} //swallowed, hudson really doesn't like these empty posts..

        ]]></script>
    </target>
</project>