matdev
matdev

Reputation: 4283

How to clear specific gradle cache files when running the "Clean project" command?

I have added the following task in my project's build.gradle file:

task('clearLibCache', type: Delete, group: 'MyGroup',
        description: "Deletes any cached artifacts with the domain of com.test in the Gradle or Maven2 cache directories.") << {
    def props = project.properties
    def userHome = System.getProperty('user.home')
    def domain = props['domain'] ?: 'com.test'
    def slashyDomain = domain.replaceAll(/\./, '/')
    file("${userHome}/.gradle/caches").eachFile { cacheFile ->
        if (cacheFile.name =~ "^$domain|^resolved-$domain") delete cacheFile.path
    }
    delete "${userHome}/.m2/repository/$slashyDomain"
}

I'd like this task to be executed when I hit the "Clean project" menu, and only in this case.

How to do that ?

Upvotes: 1

Views: 17837

Answers (1)

emerssso
emerssso

Reputation: 2386

That "Clean project" menu item under the hood appears to do a couple of things (based on the output of the Gradle Console window when you click it):

  • A gradle clean, the equivalent of calling ./gradlew clean
  • Generate sources and dependencies for a debug build, including a mockable Android sources jar if needed.

I would make your task a dependency for the Gradle clean task, so that whenever the project is cleaned, this task is also invoked. This can be achieved by adding the line clean.dependsOn clearLibCache in your build.gradle after you declare the task.

Upvotes: 2

Related Questions