Yo,

i know this isn't exactly canon, but attached is an ExecTask subclass which 
may be useful for any Unix froods out there. It allows you to write inline 
scripts for arbitrary scripting tools:

<taskdef name="shellscript" 
classname="net.sf.antcontrib.logic.ShellScriptTask"/>


<shellscript>
        echo This is my inline shell script
        echo PWD=$PWD
        echo user=$USER
</shellscript>
(defaults to using shell /bin/bash)

<shellscript executable="/bin/sed">
        <arg value="-n"/>
        <arg line="-e 's/FOO/BAR/gp'"/>
one two
FOO bar bar bar bar FOO FOO bar
three four
</shellscript>

<shellscript executable="/usr/bin/make">
        <arg value="-f"/>
default: all
foo = this is a makefile
all:
        @echo foo=$(foo)
</shellscript>

<shellscript executable="/usr/bin/perl"><![CDATA[
        print "Hello, World!\n";
        open IN, "</etc/hosts" or die "Error opening build file!\n";
        @foo=<IN>;
#       print join( "",@foo ),"\n";
]]></shellscript>


     [bash] This is my inline shell script
     [bash] PWD=/home/stephan/cvs/einsurance
     [bash] user=stephan
      [sed] BAR bar bar bar bar BAR BAR bar
     [make] make[1]: Entering directory `/home/stephan/cvs/einsurance'
     [make] foo=this is a makefile
     [make] make[1]: Leaving directory `/home/stephan/cvs/einsurance'
     [perl] Hello, World!


Tested against ant 1.4.1.
It's a subclass of ExecTask, so it supports all of the <exec> options as well.


----- stephan
[EMAIL PROTECTED] - http://www.einsurance.de
Office: +49 (89)  552 92 862 Handy:  +49 (179) 211 97 67
"I didn't give in to the Nazis and I won't give in to the bladder." 
- The Queen Mum
/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 Ant-Contrib project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:  
 *       "This product includes software developed by the 
 *        Ant-Contrib project (http://sourceforge.net/projects/ant-contrib)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The name Ant-Contrib must not be used to endorse or promote products 
 *    derived from this software without prior written permission. For
 *    written permission, please contact
 *    [EMAIL PROTECTED]
 *
 * 5. Products derived from this software may not be called "Ant-Contrib"
 *    nor may "Ant-Contrib" appear in their names without prior written
 *    permission of the Ant-Contrib project.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 THE ANT-CONTRIB PROJECT OR ITS
 * CONTRIBUTORS 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.
 * ====================================================================
 */

package net.sf.antcontrib.logic;

import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.ProjectHelper;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.ExecTask;
import java.lang.StringBuffer;
import java.io.*;

/**
A generic front-end for passing "shell lines" to any application which can
accept a filename containing script input (bash, perl, csh, tcsh, etc.). Tested 
against Ant 1.4.1.
An example:

<tt>
&lt;taskdef name="shellscript" classname="net.sf.antcontrib.logic.ShellScriptTask"/&gt;<br>
&lt;shellscript tempdir="/foo/tmp" shell="/bin/bash"&gt;<br>
ls -1 /tmp<br>
cd /home<br>
pwd<br>
&lt;/shellscript&gt;<br>
</tt>
Attributes:
<pre>
scriptname = name of temporary file to contain script code. Not required.
shell = name of executable used to run script code. Defaults to /bin/bash.
tmpdir = name of temp dir to write script code to. Defaults to /tmp.
failonerror = If true, any error will cause a bail-out. Defaults to true.
</pre>
It may be interesting to note that if output from the script does not 
include a trailing newline, that line of text may not appear in the 
Ant logger :/.
<br>
@author [EMAIL PROTECTED]
$Revision: 1.10 $
*/
public class ShellScriptTask extends org.apache.tools.ant.taskdefs.ExecTask {

    private StringBuffer script = new StringBuffer();
    private String scriptname = null;
    private String tmpdir = "/tmp";
    private boolean failonerror = true;
    private boolean replaceproperties = false;
    private String property = null;
    private boolean deletetmp = true;
    private boolean passscriptname = true;
    private String executable = null;

    public ShellScriptTask()
    {
        super();
    }


    public void execute() throws BuildException {
        if( this.getExecutable() == null ) {
            this.setExecutable( "/bin/bash" );
        }
        if( this.getScriptname() == null ) {
            this.setScriptname( "ant."+this.getTaskName()+".script" );
        }

	String scr = this.getText();
	String tmp = this.getTempdir();

	if( ! new java.io.File( tmp ).isDirectory() ) {
	    throw new BuildException( "Temporary dir ["+tmp+"] does not exist!" );
	}

	String sname = this.getScriptFullName();

        if( scr != null ) {
            this.writeScript();
        }
        if( this.getPassscriptname() ) {
            this.createArg().setValue( sname );
        }

        super.execute();
        if( this.getDeletetemp() && !new java.io.File( sname ).delete() ) {
	    log( "Non-fatal error: could not delete temporary file ["+sname+"]!" );
        }

    }


    public void setExecutable( String s ) {
        super.setExecutable( s );
        this.executable = s;
        this.setTaskName( new java.io.File(s).getName() );
    }
    // Ant core tasks never have getters :`(
    public String getExecutable() {
        return this.executable;
    }

    /**
       Writes the script lines to a temp file.
    */
    protected void writeScript() throws BuildException {
	String scr = this.getReplaceproperties() ? ProjectHelper.replaceProperties( this.getProject(), this.getText(), this.getProject().getProperties() ) : this.getText();
	String sname = this.getScriptFullName();
	try {
	    java.io.FileOutputStream os = new java.io.FileOutputStream( sname );
	    os.write( scr.getBytes(), 0, scr.length() );
	}
	catch( Exception e ) {
	    throw new BuildException( e );
	}
    }

    /**
       Adds s to the lines of script code.
    */
    public void addText( String s ) {
	script.append( s );
    }

    /**
       Sets script code to s.
    */
    public void setText( String s ) {
	script = new StringBuffer( s );
    }

    /**
       Returns the script code.
    */
    public String getText() {
	return this.script.toString();
    }

    /**
       Sets the temp dir to write the script to.
    */
    public void setTempdir( String s ) {
	this.tmpdir = s;
    }

    public String getTempdir() {
	return this.tmpdir;
    }

    public void setDeletetemp( boolean b ) {
	this.deletetmp = b;
    }

    public boolean getDeletetemp() {
	return this.deletetmp;
    }


    /**
       If set to false, the temp script name is not passed on the command line. Defaults to true.
       This is useful if you need to specify other arugments in a specific order and need to pass the
       script name to one of them.
    */
    public void setPassscriptname( boolean b ) {
	this.passscriptname = b;
    }

    public boolean getPassscriptname() {
	return this.passscriptname;
    }


    /**
       If set to true then all ${property}-format strings in getText() will be replaced with
       their Ant values. Use with care, since ${foo} is a valid construct in bash code.
    */
    public void setReplaceproperties( boolean b ) {
	this.replaceproperties = b;
    }

    public boolean getReplaceproperties() {
	return this.replaceproperties;
    }


    /**
       Sets the name of the temporary script. Defaults to something
       reasonably absurd. This is only used if the character data for this node is set
       (i.e., addText() or setText() is called).
    */
    public void setScriptname( String s ) {
	this.scriptname = s;
    }

    public String getScriptname() {
	return this.scriptname;
    }

    /**
       Returns the full path to the temporary script.
    */
    public String getScriptFullName() {
	String sname = this.getScriptname();
	return this.getTempdir() + System.getProperty("file.separator") + sname;
    }

    

} // end class ShellScriptTask org.apache.tools.ant.Task

--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to