views:

388

answers:

3

I am trying to customize my build by using a configuration file with ant. What I intend to do is that use config file which has the following pattern: file path, pattern to match, pattern to replace

I want it such that I just add things to the configuration file and the ant build script reads up these values and makes the required changes.

I already know how to do a regex find and replace in files. What I am looking for is a way to read the values from such a configration file.

A: 

There are various ways to read information from a file in Ant.

The generic one is the LoadFile Ant Task. I would however recommend the loadProperties Task. You could use this task to read properties such as: toReplace=string_to_replace with=replacement_string

and then use the properties "toReplace" and "with" in your regexes.

Daniel Gill
But then wouldn't this result in immutable variables toReplace and with? I want to loop to through the file and make all the changes.
Prashast
You're absolutely right, sorry. I'm not actually sure of a nice way of doing this, I'm sure the more experienced in Ant would have an 'ant-way' of doing this. Only thing I can suggest is to have a look at ant contrib's <foreach> task - it may prove helpful.
Daniel Gill
A: 

If I understand you correctly, you want to generate a set of configuration files for various environments.

The solution I'm currently using is a Groovy script called by an Ant task. Since Ant won't let you redefine a property that was already set, it's quite tricky to use it to generate several files with different values.

If you want to explore this, just take a look at Groovy and especially the Template Engine.

Vladimir
A: 

I would use the filterset feature in ant. You can create a parameterized version of the config file with strings you want replace using the pattern @replace_me@. Then define a properties file to define the replacement values. You can

<copy toDir="${dist.dir}/docs">
  <fileset file="config.xml"/>
  <filterset>
    <filtersfile file="path/to.properties"/>
  </filterset>
</copy>

Then the properties file is simply name=value lines.

You have lots of flexibility in specifying both the fileset and the filterset, see the Ant docs for these.