ANT script to compile all (css) LESS files in a dir and subdirs with RHINO

Christian Steinmann picture Christian Steinmann · Aug 2, 2011 · Viewed 11.4k times · Source

I want do compile all *.less scripts in a specific folder and it subdirs with less-rhino-1.1.3.js.

There is an example on github for doing this for a specific file, which works perfect. But I want to do the same for a complete folder. I tried a lot, here is my last try.

It doesn't work, propertyregex seems not to be standard ANT, I don't want to use such things. I am not even sure if this code would work.

<project name="test" default="main" basedir="../../">
<property name="css.dir" location="public/css"/>
<property name="tool.less" location="bin/less/less-rhino-1.1.3.js"/>
<property name="tool.rhino" location="bin/tools/rhino/js.jar"/>
<macrodef name="lessjs">
    <attribute name="input" />
    <attribute name="output" />
    <sequential>
        <java jar="${tool.rhino}" fork="true" output="@{output}">
            <arg path="${tool.less}"/>
            <arg path="@{input}"/>
        </java>
        <echo>Lessjs: generated @{output}</echo>
    </sequential>
</macrodef>

<target name="main">
     <echo>compiling less css</echo>
     <fileset dir="${css.dir}" id="myfile">
          <filename name="**/*.less" />
     </fileset>
     <property name="lessfilename" refid="myfile"/>
     <propertyregex property="cssfilename"
          input="${lessfile}"
          regexp="^(.*)\.less$"
          replace="^\1\.css$" 
          casesensitive="true" />
     <lessjs input="lessfile" output="cssfilename"/>
</target>
</project>

Answer

steveyang picture steveyang · Nov 9, 2011

You could use the <fileset> to include all the less files need to be compiled. Later, you could use<mapper> to mark the corresponding detination css file.

<project name="test" default="main" basedir="../../">
<property name="css.dir" location="public/css"/>
<property name="tool.less" location="bin/less/less-rhino-1.1.3.js"/>
<property name="tool.rhino" location="bin/tools/rhino/js.jar"/>

  <target name="less" description="Convert LESS to CSS then concatenate and Minify any stylesheets">

  <echo message="Converting LESS to CSS..."/>
  <!-- Clear the former compiled css files -->
      <delete includeemptydirs="true">
            <fileset dir="${css.dir}" includes="*.css, **/*.css" defaultexcludes="false"/>
      </delete>

      <apply dir="${css.dir}" executable="java" parallel="false" failonerror="true">
  <!-- Give the input bundle of less files-->
          <fileset dir="${css.dir}">
              <include name="*.less"/>
          </fileset>
          <arg value="-jar" />
          <arg path="${tool.rhino}" />
          <arg path="${tool.less}" />
          <srcfile/>
  <!-- Output the compiled css file with corresponding name -->
          <mapper type="glob" from="*.less" to="${css.dir}/*.css"/>
          <targetfile/>
      </apply>

  </target>

</project>