Remove parents in remove_empty_directories (#21726)

The original implementation did a full directory tree walk to find and remove
empty directories, so this implementation should remove the parents as well,
like the original did.
This commit is contained in:
John Shaw
2026-02-26 21:27:56 -07:00
committed by Nicolas Mowen
parent 9b7cee18db
commit af2339b35c
2 changed files with 26 additions and 12 deletions
+24 -10
View File
@@ -50,22 +50,36 @@ class SyncResult:
}
def remove_empty_directories(paths: Iterable[Path]) -> None:
def remove_empty_directories(root: Path, paths: Iterable[Path]) -> None:
"""
Remove directories if they exist and are empty.
Silently ignores non-existent and non-empty directories.
Attempts to remove parent directories as well, stopping at the given root.
"""
count = 0
for path in paths:
try:
path.rmdir()
except FileNotFoundError:
continue
except OSError as e:
if e.errno == errno.ENOTEMPTY:
while True:
parents = set()
for path in paths:
if path == root:
continue
raise
count += 1
try:
path.rmdir()
count += 1
except FileNotFoundError:
pass
except OSError as e:
if e.errno == errno.ENOTEMPTY:
continue
raise
parents.add(path.parent)
if not parents:
break
paths = parents
logger.debug("Removed {count} empty directories")