How do I recursively delete files with a certain extension?

Hi,

I’m having trouble with what should be a simple operation. I’m trying to delete *.css files under a directory. The directory has subdirectories with *.css files in them. I would like to recursively delete all *.css files under the directory. My code looks like this:

clean {
  doLast {
    delete fileTree(dir: 'app/styles' , include: '**/*.css')
  }
}

The code runs, but it only deletes *.css files immediately under ‘app/styles’. I tried many different combinations of constructing FileTree objects and specifying file matching patterns. None worked so far.

What am I doing wrong?

Here’s my gradle environment:

$ gradle --version
  ------------------------------------------------------------
Gradle 1.11
------------------------------------------------------------
  Build time:
 2014-02-11 11:34:39 UTC
Build number: none
Revision:
   a831fa866d46cbee94e61a09af15f9dd95987421
  Groovy:
     1.8.6
Ant:
        Apache Ant(TM) version 1.9.2 compiled on July 8 2013
Ivy:
        2.2.0
JVM:
        1.7.0_51 (Oracle Corporation 24.51-b03)
OS:
         Mac OS X 10.10 x86_64

Thank you.

‘Delete’ tasks have a ‘delete’ method to configure what should get deleted (‘delete’ doesn’t refer to ‘project.delete’ here). Configuring that in ‘doLast’ is too late. Getting rid of ‘doLast’ should solve the problem. For API details, check ‘Delete’ in the Gradle Build Language Reference.

I googled a bit more, and found a similar question, for which an issue is filed:

  1. Question 2. Issue

To work around the issue, one is to use ANT. I did it like this:

clean {
  doLast {
    ant.delete() {
      fileset(dir: 'app/styles') {
 include(name: '**/*.css')
      }
    }
  }
}

Ah thank you, Peter. Getting rid of ‘doLast’ did the trick.

clean {
  delete fileTree(dir: 'app/styles' , include: '**/*.css')
}

It took me a while to understand what you wrote (I’m slow), but I now understand what you are saying.

Thanks again.