Cleanup should delete only contents of buildDir in Multi-project build

I want to retain the buildDir, but want to delete all its contents whenever i do “gradle clean”.
I have read in the forums how to do it in a single-root-project scenario, by overwriting the default clean task.
But i have a multi-project build, where the output of all the subproject’s build are put in a single buildDir.
In this case the sub-project’s clean task still deletes both the buildDir and its contents.

So i want to do it like ,when i do “gradle subproject:clean”, i only want the subproject’s stuff in buildDir deleted. and when i do “gradle clean” from the root, all the contents of buildDir should be removed , but the empty buildDir should still be present.

How to accomplish this in gradle?
Thanks in advance for reply,

Why do you want to do that?

I think you could do something like:

clean.finalizedBy 'recreateBuildDir'

task recreateBuildDir << { buildDir.mkdirs() }

Thanks for replying.

I put the recreateBuildDir snippet in allprojects { } and it worked.
(although it calls the recreateBuildDir for rootproject and all other subprojects)

In the git repo, we store the empty buildDir along with a empty “.gitkeep” file. sort of like a place holder.
So we do a “gradle clean” and then check in to the repository.
We just didnt want the buildDir changes to be checked in accidentally. Hence the question.

Wouldn’t it be easier to put build/ in your .gitignore? Then you wouldn’t need this hack, .gitkeep files, or run clean before checking in.