1

I have a gradle task that deletes files matching a certain pattern in their names:

task deleteTempFiles(type: Delete) {
    tasks['clean'].dependsOn(it)
    delete fileTree(dir: '..', include: '**/tempfile*.tmp')
}

I would like to delete files older than, lets say, 2 hours or 24 hours. It could be 2 days for that matter. What is the easiest way to do it in gradle?

user3111525
  • 5,013
  • 9
  • 39
  • 64
  • I imagine you should be able to use some variation of `filetree.matching() `and a closure that uses `file.getlastmodified` – RaGe Jun 22 '16 at 21:12

3 Answers3

1
task deleteTempFiles(type: Delete) {

    def cutoff = new Date().minus(1); //24 hrs ago

    delete fileTree (dir: '..')
        .matching{ include '**/tempfile*.tmp' }
        .findAll { 
            def filedate = new Date (it.lastModified())
            filedate.before(cutoff) 
        }
}
RaGe
  • 22,696
  • 11
  • 72
  • 104
  • What about files older than 8 hours? – user3111525 Jun 23 '16 at 06:37
  • 1
    @user3111525, it's probably easy to do, isn't it? – Opal Jun 23 '16 at 06:54
  • Search is your friend. http://stackoverflow.com/questions/21166927/incrementing-date-object-by-hours-minutes-in-groovy http://stackoverflow.com/questions/25046910/how-do-i-subtract-minutes-from-current-time – RaGe Jun 23 '16 at 15:39
  • @RaGe if you change your answer that includes a solution for 2 hours, 1 day and so on, i.e. a general way of doing it -- I will accept it as an answer. – user3111525 Jun 23 '16 at 20:36
0

If you're looking for a solution that will delete all files/folders, not just "empty out" the folders, here's something I came up with that can be remixed for other use-cases.

/**
 * cleanCypressBuildCache will clean up build files that Cypress generates
 * before running tests. These are normally self-cleaned but if the build is interrupted
 * or dies during Cypress tests, then they'll remain forever. So we clean them up here.
 */
task cleanCypressBuildCache(type: Delete) {
    def cypressBuildFolder = System.getenv('APPDATA') + '/Cypress/cy/production/projects'
    def daysToKeepOldItems = 2

    description = 'Tidy up Cypress ' + cypressBuildFolder

    // Delete old folders / files
    def cutoff = new Date().minus(daysToKeepOldItems);
    def deleteList = []
    fileTree (dir: cypressBuildFolder).visit {
        def File file = it.file
        def shouldBeDeleted = new Date(file.lastModified()).before(cutoff)
        if (shouldBeDeleted) {
            deleteList << file
        }
    }
    // Not sure why, by `it.delete()` didn't work but `project.delete(it)` did.
    deleteList.each { project.delete(it) }
}
SilbinaryWolf
  • 461
  • 4
  • 9
0

in response to: // Not sure why, by it.delete() didn't work but project.delete(it) did. it's because it comes through as an AttributeBasedFileVisitDetails object.

what you'd need to do is use it.getFile().delete()