How to list the two most recent folders inside a directory using their timestamp

106 Views Asked by At

I have a parent folder and inside that I have a few folders. For an automation, I want to take the latest of the two folders according to timestamp.

I have tried to take the latest folder by using timstampselector.

    <timestampselector property="latest.modified">
        <path>
            <dirset dir="MyDirectoryPath">
                <include name="*" />
            </dirset>
        </path>
    </timestampselector>

Inside my parent folder, I have the following folders:

test      (Last modified on 07/04/2019 10:30 AM)
check     (Last modified on 08/04/2019 05:00 PM)
integrate (Last modified on 08/04/2019 12:30 PM)
slave     (Last modified on 09/04/2019 05:00 PM)

Our script should take the latest two modified folders, which is in the above case it should be integrate & slave.

How can I achieve that?

2

There are 2 best solutions below

0
martin clayton On

The task you are using is part of Ant-Contrib rather than core Ant. The documentation says you can use the count attribute to say how many items you want to select. In your case, set it to two:

<timestampselector property="latest.modified" count="2">
  <path>
    <dirset dir="MyDirectoryPath">
      <include name="*" />
    </dirset>
  </path>
</timestampselector>

This appeared to work fine for me: the property was set to a comma-separated list of two directories.

1
CAustin On

Generally speaking, it's a good idea to stay away from ant-contrib whenever possible. This particular problem can be quickly solved with native Ant's resource collections:

<last count="2" id="latest.two.files">
    <sort>
        <date />

        <fileset dir="MyDirectoryPath" />
    </sort>
</last>

Full example target:

<target name="select-latest">
    <delete dir="testdir" />
    <mkdir dir="testdir" />

    <touch file="testdir/test" datetime="07/04/2019 10:30 AM" />
    <touch file="testdir/check" datetime="08/04/2019 05:00 PM" />
    <touch file="testdir/integrate" datetime="08/04/2019 12:30 PM" />
    <touch file="testdir/slave" datetime="09/04/2019 05:00 PM" />

    <last count="2" id="latest.two.files">
        <sort>
            <date />

            <fileset dir="testdir" />
        </sort>
    </last>

    <echo message="${toString:latest.two.files}" />
</target>