#!/usr/bin/env python3 """Удаление пустых каталогов с предпросмотром по умолчанию.""" from __future__ import annotations import argparse import sys from pathlib import Path def find_empty(root: Path) -> list[Path]: removed: set[Path] = set() changed = True while changed: changed = False paths = sorted(root.rglob("*"), key=lambda item: len(item.parts), reverse=True) for path in paths: if path in removed or not path.is_dir() or path.is_symlink(): continue try: children = [child for child in path.iterdir() if child not in removed] except OSError: continue if not children: removed.add(path) changed = True return sorted(removed, key=lambda item: len(item.parts), reverse=True) def confirm(count: int) -> bool: print(f"Будет удалено пустых папок: {count}.") if not sys.stdin.isatty(): print("Нет интерактивного терминала. Добавьте --yes для подтверждения.") return False answer = input("Удалить эти папки? Введите yes: ").strip().lower() return answer in {"yes", "да"} def main() -> int: parser = argparse.ArgumentParser(description="Удалить пустые папки") parser.add_argument("--dir", type=Path, required=True, help="Корневая папка") parser.add_argument("--apply", action="store_true", help="Удалить найденные папки") parser.add_argument("--yes", action="store_true", help="Не задавать вопрос при удалении") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") if root == Path(root.anchor): parser.error("Нельзя запускать на корне файловой системы") candidates = find_empty(root) if not candidates: print("Пустые папки не найдены.") return 0 for path in candidates: print(f"Пустая папка: {path.relative_to(root)}") if not args.apply: print(f"\nПредпросмотр: {len(candidates)} папок. Для удаления добавьте --apply.") return 0 if not args.yes and not confirm(len(candidates)): print("Отменено.") return 1 deleted = 0 for path in candidates: try: path.rmdir() deleted += 1 except OSError as error: print(f"Не удалось удалить {path}: {error}", file=sys.stderr) print(f"\nУдалено папок: {deleted} из {len(candidates)}") return 0 if deleted == len(candidates) else 1 if __name__ == "__main__": raise SystemExit(main())