XiaoYao
XiaoYao

Reputation: 3317

How to get a filename and set it as a property in Ant?

I need to scan files in a folder and set property as file name in Ant so I can use it later. For example, there's a test123.tar under Jenkins folder. I need to use test*.tar to match this file and then set a property named "filename" to test123.tar Is it possible to do it? Thank you very much!

Upvotes: 3

Views: 8333

Answers (2)

ewan.chalmers
ewan.chalmers

Reputation: 16235

You could use pathconvert to convert a fileset into a list of files, then loadresource with a filterchain to extract the single required value from the list.

<project default="test">

    <target name="test">

        <!-- read your fileset into a property formatted as a list of lines -->
        <pathconvert property="file.list" pathsep="${line.separator}">
            <map from="${basedir}${file.separator}" to=""/>
            <fileset dir="${basedir}">
                <include name="test*.tar"/>
            </fileset>
        </pathconvert>


        <!-- extract a single target file from the list -->
        <loadresource property="file.name">
            <string value="${file.list}"/>
            <filterchain>
                <!-- add your own logic to deal with multiple matches -->
                <headfilter lines="1"/>
            </filterchain>
        </loadresource>

        <!-- print the result -->
        <echo message="file.name: ${file.name}"/>

    </target>

</project>

Output:

$ ls test*.tar
test012.tar  test123.tar  testabc.tar
$
$ ant
Buildfile: C:\tmp\ant\build.xml

test:
     [echo] file.name: test012.tar

BUILD SUCCESSFUL
Total time: 0 seconds

Verbose output:

$ ant -v
test:
[pathconvert] Set property file.list = test012.tar
[pathconvert] test123.tar
[pathconvert] testabc.tar
[loadresource] loading test012.tar
[loadresource] test123.tar
[loadresource] testabc.tar into property file.name
[loadresource] loaded 13 characters
     [echo] file.name: test012.tar

BUILD SUCCESSFUL
Total time: 0 seconds

Upvotes: 9

Jayan
Jayan

Reputation: 18459

A combination of fileset (to search) and pathconvert will help.

<project name="SuperRoot" default="demo" basedir=".">
    <fileset id="afileset" dir="searchfolder" includes="**/test*.jar"/>

    <target name="demo" >
        <pathconvert property="result" refid="afileset" />
        <echo message="found : ${result}"/>
        <basename property="foo.filename" file="${result}"/>
        <echo message="found : ${foo.filename}"/>
        </target>
</project>

Upvotes: 1

Related Questions