#!/usr/bin/env python3 """Перенос файлов из списка в системную корзину.""" from __future__ import annotations import argparse import os import sys from pathlib import Path def is_relative_to(path: Path, parent: Path) -> bool: try: path.relative_to(parent) return True except ValueError: return False def forbidden_reason(path: Path) -> str | None: resolved = path.resolve() if resolved == Path(resolved.anchor): return "корень диска" if resolved == Path.home().resolve(): return "домашний каталог" if os.name == "nt": variables = ("SystemRoot", "ProgramFiles", "ProgramFiles(x86)", "ProgramData") for name in variables: value = os.environ.get(name) if value: system_path = Path(value).resolve() if resolved == system_path or is_relative_to(resolved, system_path): return f"системный каталог {system_path}" else: system_paths = ( "/etc", "/usr", "/bin", "/sbin", "/lib", "/lib64", "/boot", "/dev", "/proc", "/sys", "/System", "/Library", ) for value in system_paths: system_path = Path(value) if resolved == system_path or is_relative_to(resolved, system_path): return f"системный каталог {system_path}" return None def main() -> int: parser = argparse.ArgumentParser(description="Отправить файлы из списка в корзину") parser.add_argument("--list", 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() list_path = args.list.expanduser().resolve() if not list_path.is_file(): parser.error(f"Список не найден: {list_path}") candidates: list[Path] = [] errors: list[str] = [] for number, line in enumerate(list_path.read_text(encoding="utf-8").splitlines(), start=1): text = line.strip() if not text or text.startswith("#"): continue path = Path(text).expanduser() if path.is_symlink(): errors.append(f"строка {number}: символическая ссылка не обрабатывается: {path}") continue if not path.exists(): errors.append(f"строка {number}: путь не найден: {path}") continue reason = forbidden_reason(path) if reason: errors.append(f"строка {number}: запрещено, {reason}: {path}") continue candidates.append(path.resolve()) if errors: print("Проблемные строки:") for error in errors: print(f" {error}") if not candidates: print("Нет корректных путей для обработки.") return 1 print(f"Путей к отправке в корзину: {len(candidates)}") for path in candidates: kind = "каталог" if path.is_dir() else "файл" print(f" {kind}: {path}") if not args.apply: print("Предпросмотр. Для отправки в корзину добавьте --apply.") return 0 if not args.yes: try: answer = input("Введите YES, чтобы отправить пути в корзину: ").strip() except EOFError: print("Нет ввода для подтверждения. Используйте --yes в неинтерактивном режиме.") return 1 if answer != "YES": print("Отменено.") return 1 try: from send2trash import send2trash except ImportError: print("Не установлен send2trash. Выполните: python3 -m pip install send2trash", file=sys.stderr) return 1 moved = 0 failed = 0 for path in candidates: try: send2trash(str(path)) moved += 1 print(f"В корзине: {path}") except Exception as error: failed += 1 print(f"Не удалось отправить {path}: {error}", file=sys.stderr) print(f"Отправлено в корзину: {moved}, ошибок: {failed}") return 0 if failed == 0 else 1 if __name__ == "__main__": raise SystemExit(main())