Freitag, 20. Januar 2012

ANT: Replace string tokens

You can use ANT to copy files during the build process. In addition to that you can modify these files on the fly and change their content. This allows you to replace tokens in the original file.

I used this mechanism in my post yesterday to generate a configuration file for my webOS application. The original file contained the structure and a few tokens, such as the vendor name or application id. During the build the original file is copied into the source folder with the replaced tokens. Very convenient!

This is my package target. It copies the file appinfo.json.in from the base directory of my project into the src directory and replaces the tokens
  • id
  • version
  • title
  • vendor
with the values from the properties defined in the build file. After the copy operation the target executes the package command from the webOS SDK.

<property name="appinfo.id" value="codebrocken.test" />
  <property name="appinfo.version" value="1.0.0" />
  <property name="appinfo.title" value="TestProject" />
  <property name="appinfo.vendor" value="CodeBrocken" />

  <!-- ================================= 

    target: package              

    ================================= -->

  <target name="package" depends="depends" description="Package the application.">
    <copy file="appinfo.json.in" tofile="src/appinfo.json">
      <filterchain>
        <replacetokens>
          <token key="id" value="${appinfo.id}" />
          <token key="version" value="${appinfo.version}" />
          <token key="title" value="${appinfo.title}" />
          <token key="vendor" value="${appinfo.vendor}" />
        </replacetokens>
      </filterchain>
    </copy>

    <exec executable="cmd">
      <arg value="/c" />
      <arg value="palm-package" />
      <arg value="src" />
      <arg value="-o" />
      <arg value="bin" />
    </exec>
  </target>

The file appinfo.json.in contains the following JSON string. See the webOS SDK for the description of the fields.

{
  "id": "@id@",
  "version": "@version@",
  "vendor": "@vendor@",
  "type": "web",
  "main": "index.html",
  "title": "@title@",
  "uiRevision": "2",
  "icon": "images/icon.png"
}

The ANT script uses a filter chain to modify the source file, while it is being processed. A filter chain consists of one or more filter readers. One such filter reader is replacetokens. It replaces a token in the form of "@key@" with the specified value.

Keine Kommentare:

Kommentar veröffentlichen