Thomas S.
Thomas S.

Reputation: 6335

ANT: copy certain parts of a text file

I have a property file that contains several properties. Multiple are valid for multiple (of our) products, some only for one product (not distinguishable by property name). Hence, during the ANT-based build process for one product, I want to copy the original file containing all properties to a product specific file skipping the sections that apply to other products. I can imagine to use some begin and end markers, e.g.

foo.bar=hello

# begin-product1
foo.bazz=world
# end-product1

# begin-product2
woohoo.bart=bla-bla
# end-product2

For product 1 I want to get the file

foo.bar=hello

foo.bazz=world

and for product 2

foo.bar=hello

woohoo.bart=bla-bla

Is something like that possible with ANT or should I write my own Java helper class?

Upvotes: 1

Views: 734

Answers (1)

martin clayton
martin clayton

Reputation: 78105

You might be able to use this as a "vanilla Ant" starting point and adjust to suit your needs.

Assumptions here are that you want to process one product at a time, and given the product number, load the properties for that product into the current build.

The approach is to implement a macro that does this. The attributes supplied are the propertyfile name and the product number. The macro reads the file twice extracting the common part and then product-specific part, these are then concatenated and loaded as Ant properties.

You could adapt this macro to, for example, fetch the file snippets needed for a product and write out a product-specific property file (using the Ant <echo> task). The strings delimiting the various sections could also be abstracted into properties or parameters of the macro if needed. In the example I have included the begin/end markers in the product-specific string passed into the <loadproperties> task.

<macrodef name="loadProductProperties">
  <attribute name="propertiesFile" />
  <attribute name="product" />

  <sequential>
    <local name="config.common" />
    <local name="config.product" />

    <loadfile property="config.common" srcFile="@{propertiesFile}">
      <filterchain>
        <tokenfilter>
          <filetokenizer/>
             <replaceregex pattern="^(.*?)# begin-product.*" replace="\1" flags="s" />
        </tokenfilter>
      </filterchain>
    </loadfile>

    <loadfile property="config.product" srcFile="props.txt">
      <filterchain>
        <tokenfilter>
          <filetokenizer/>
             <replaceregex
                pattern="^.*(# begin-product@{product}\b.*?# end-product@{product}\b).*"
                replace="\1" flags="s" />
        </tokenfilter>
      </filterchain>
    </loadfile>

    <loadproperties>
        <string value="${config.common}${config.product}" />
    </loadproperties>
  </sequential>
</macrodef>

<loadProductProperties propertiesFile="props.txt" product="2" />

Upvotes: 1

Related Questions