Reputation: 17336
I have the following folders/files.
A/B/C/D/giga.txt A/BB/ A/CC/DD/fifa.jpg A/ZZZ/1/a.txt A/ZZZ/2/b.png A/ZZZ/3/
How can I code in Gradle/Groovy to delete ONLY the empty directories/subfolders. i.e. Delete "A/BB", "A/ZZZ/3" in the above sample example. Real case has lot of such folders.
I tried
tasks.withType(Delete) { includeEmptyDirs = true }
didn't work
tasks.withType(Delete) { includeEmptyDirs = false }
didn't work
I don't want to use Gradle > calling > Ant way as that'd be my last resort. Also, don't want to delete each empty folder by writing explicit delete statement per empty folder.
Case 2: If I run the following:
delete fileTree (dir: "A", include: "**/*.txt")
this above cmd will remove any .txt file under folder A and any subfolder under it. Now, this will make "A/ZZZ/1" a valid candidate for "empty folder" which I would want to delete as well.
Upvotes: 1
Views: 6193
Reputation: 8668
If you want to delete all the folders that themselves only contain empty folders, this code might help.
def emptyDirs = []
project.fileTree(dir: destdir).visit {
def File f = it.file
if (f.isDirectory() ) {
def children = project.fileTree(f).filter { it.isFile() }.files
if (children.size() == 0) {
emptyDirs << f
}
}
}
// reverse so that we do the deepest folders first
emptyDirs.reverseEach { it.delete() }
Upvotes: 3
Reputation: 24498
Using the Javadoc for FileTree, consider the following to delete empty dirs under "A". Uses Gradle 1.11:
task deleteEmptyDirs() {
def emptyDirs = []
fileTree (dir: "A").visit { def fileVisitDetails ->
def file = fileVisitDetails.file
if (file.isDirectory() && (file.list().length == 0)) {
emptyDirs << file
}
}
emptyDirs.each { dir -> dir.delete() }
}
Upvotes: 3