JoeG JoeG - 3 months ago 16
Groovy Question

Ant/Groovy: How to delete files over than given date, but keep a maximum of 3

Using code as shown below to age out files over time in a logs directory.

MAX_LOG_FILE_AGE
can be calculated or set to any desired value. This correctly deletes files older than desired.

The question arises from a change in requirements I received to instead keep only a certain number of the most recent files, in my case three (3). How might this be achieved?

long deleteDate = System.currentTimeMillis() - MAX_LOG_FILE_AGE
def ant = new AntBuilder()
ant.delete() {
fileset (dir: "${someParentDir}/logs/", includes: '**/*') {
date(millis: "${deleteDate}", when: 'before')
}
}

Answer

This would be difficult to do with Ant. But in straight Groovy, it is tractable:

def MAX_LOG_FILE_AGE_IN_MILLIS = 24 * 60 * 60 * 1000
def deleteDate = System.currentTimeMillis() - MAX_LOG_FILE_AGE_IN_MILLIS

def logDir = "logs"
def logs = []

// build list of files
new File(logDir).eachFileRecurse { file ->
    if (file.isFile() && (file.lastModified() < deleteDate)) {
        logs << file
    }
}

// sort by last modified (ascending)
def sortedLogs = logs.toSorted { a,b -> a.lastModified() <=> b.lastModified() }

// N most recent are skipped 
def n = 3
def victims = sortedLogs.dropRight(n)

// delete victims
victims.each { victim ->
    println "deleting $victim.name"
    victim.delete()
}
Comments