teryret
teryret

Reputation: 577

How can I prepend filenames to the files themselves in Ant?

Is there any way to use Ant to prepend each file's name to it? So foo.txt would go from

bar

to

// foo.txt
bar

This needs to work on a set of files that cannot be hard-coded into the ant script.

Upvotes: 0

Views: 457

Answers (1)

joescii
joescii

Reputation: 6533

Since you want to dynamically determine the files to work with, I recommend that you get the ant-contrib.jar and utilize its for task. I should point out that this will write out the full path to the file in the comment.

<!-- Sample usage -->
<target name="run">
  <prepend>
    <!-- Assuming you are interested in *.txt files in the resource directory -->
    <fileset dir="resource">
        <include name="**/*.txt"/>
    </fileset>
  </prepend>
</target>

<!-- Import the definitions from ant-contrib -->
<taskdef resource="net/sf/antcontrib/antlib.xml">
  <classpath>
    <pathelement location="../ant-contrib*.jar"/>
  </classpath>
</taskdef>

<!-- Create the prepend task -->
<macrodef name="prepend">
  <!-- Declare that it contains an element named "files".  Implicit means it needn't be named -->
  <element name="files" implicit="yes"/>
  <sequential>
    <!-- For loop, assigning the value of each iteration to "file" -->
    <for param="file">
      <!-- Give the for loop the files -->
      <files/>
      <sequential>
        <!-- Load the contents of the file into a property -->
        <loadfile property="@{file}-content" srcfile="@{file}"/> 
        <!-- Echo the header you want into the file -->
        <echo message="// @{file}${line.separator}" file="@{file}"/>
        <!-- Append the original contents to the file -->
        <echo message="${@{file}-content}" append="true" file="@{file}"/>
      </sequential>
    </for>
  </sequential>
</macrodef>

Upvotes: 1

Related Questions