#!/usr/bin/env python3 """Удаление файлов по маске с обязательным подтверждением.""" from __future__ import annotations import argparse import stat as stat_module import sys import time from pathlib import Path def human_size(size: int) -> str: value = float(size) for unit in ("B", "KB", "MB", "GB", "TB"): if value < 1024 or unit == "TB": return f"{int(value)} B" if unit == "B" else f"{value:.1f} {unit}" value /= 1024 return f"{size} B" def main() -> int: parser = argparse.ArgumentParser(description="Безопасно удалить файлы по маске") parser.add_argument("--dir", type=Path, required=True, help="Папка для поиска") parser.add_argument("--pattern", required=True, help="Glob-маска, например *.tmp") parser.add_argument("--recursive", action="store_true", help="Искать во вложенных папках") parser.add_argument("--older-than", type=int, help="Только файлы старше N дней") 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("Нельзя запускать на корне файловой системы") pattern = Path(args.pattern) if pattern.is_absolute() or ".." in pattern.parts: parser.error("Маска не должна быть абсолютной или содержать ..") if args.older_than is not None and args.older_than < 0: parser.error("--older-than не может быть отрицательным") candidates = root.rglob(args.pattern) if args.recursive else root.glob(args.pattern) cutoff = time.time() - (args.older_than or 0) * 86400 matches: list[tuple[Path, int]] = [] for path in candidates: try: info = path.lstat() except OSError: continue if stat_module.S_ISDIR(info.st_mode): continue if args.older_than is not None and info.st_mtime >= cutoff: continue if path.resolve() == root: continue matches.append((path, info.st_size)) if not matches: print("Файлы по маске не найдены.") return 0 total_size = sum(size for _, size in matches) for path, size in matches: print(f"{human_size(size):>10} {path}") print(f"\nФайлов: {len(matches)}, объём: {human_size(total_size)}") if not args.apply: print("Предпросмотр. Для удаления добавьте --apply.") return 0 if not args.yes: if not sys.stdin.isatty(): parser.error("Нужно подтверждение. Добавьте --yes") answer = input("Удалить эти файлы? Введите DELETE: ").strip() if answer != "DELETE": print("Отменено.") return 1 deleted = 0 failed = 0 for path, _ in matches: try: path.unlink() deleted += 1 except OSError as error: failed += 1 print(f"Ошибка {path}: {error}", file=sys.stderr) print(f"\nУдалено: {deleted}, ошибок: {failed}") return 0 if failed == 0 else 1 if __name__ == "__main__": raise SystemExit(main())