#!/usr/bin/env python3 """Поиск дубликатов по размеру и SHA-256 с перемещением в карантин.""" from __future__ import annotations import argparse import hashlib import json import os import shutil from collections import defaultdict from pathlib import Path def file_hash(path: Path, chunk_size: int = 1048576) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(chunk_size): digest.update(chunk) return digest.hexdigest() def collect(root: Path, min_size: int, quarantine: Path | None) -> list[Path]: files: list[Path] = [] for current, dirnames, filenames in os.walk(root, followlinks=False): current_path = Path(current).resolve() if quarantine is not None: try: current_path.relative_to(quarantine) dirnames[:] = [] continue except ValueError: pass dirnames[:] = [ name for name in dirnames if not os.path.islink(os.path.join(current, name)) ] for name in filenames: path = Path(current) / name if path.is_symlink(): continue try: if path.stat().st_size < min_size: continue except OSError: continue files.append(path) return files def unique_destination(base: Path) -> Path: if not base.exists(): return base for index in range(1, 1000): candidate = base.with_name(f"{base.name}.{index}") if not candidate.exists(): return candidate raise RuntimeError(f"Не удалось подобрать имя для {base}") def main() -> int: parser = argparse.ArgumentParser(description="Дубликаты файлов по SHA-256") parser.add_argument("--path", type=Path, default=Path("."), help="Каталог для поиска") parser.add_argument("--min-size", type=int, default=1, help="Минимальный размер в байтах") parser.add_argument("--quarantine", type=Path, help="Каталог для лишних копий") parser.add_argument("--apply", action="store_true", help="Переместить дубликаты в карантин") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() if args.min_size < 1: parser.error("--min-size должен быть положительным") root = args.path.expanduser().resolve() if not root.is_dir(): parser.error(f"Каталог не найден: {root}") if root == Path(root.anchor) or root == Path.home().resolve(): parser.error("Укажите конкретный каталог, а не корень или домашнюю папку") if args.apply and not args.quarantine: parser.error("Для --apply укажите --quarantine: скрипт не удаляет файлы безвозвратно") quarantine = None if args.quarantine: quarantine = args.quarantine.expanduser().resolve() if quarantine == Path(quarantine.anchor) or quarantine == Path.home().resolve(): parser.error("Некорректный каталог карантина") by_size: dict[int, list[Path]] = defaultdict(list) for path in collect(root, args.min_size, quarantine): try: by_size[path.stat().st_size].append(path) except OSError: continue groups: list[list[Path]] = [] for size, paths in by_size.items(): if len(paths) < 2: continue by_hash: dict[str, list[Path]] = defaultdict(list) for path in paths: try: by_hash[file_hash(path)].append(path) except OSError as error: print(f"Пропуск {path}: {error}") for same in by_hash.values(): if len(same) > 1: groups.append(sorted(same, key=lambda item: str(item))) groups.sort(key=lambda group: group[0].stat().st_size * (len(group) - 1), reverse=True) duplicates = sum(len(group) - 1 for group in groups) wasted = sum(group[0].stat().st_size * (len(group) - 1) for group in groups) print(f"Каталог: {root}") print(f"Групп дубликатов: {len(groups)}, лишних копий: {duplicates}, объём: {wasted / 1048576:.1f} MB") for group in groups[:30]: size = group[0].stat().st_size print(f" {size / 1048576:.1f} MB, копий: {len(group)}") print(f" оставить: {group[0]}") for path in group[1:4]: print(f" дубль: {path}") if len(group) > 4: print(f" ... ещё {len(group) - 4}") if args.json: payload = { "root": str(root), "groups": [ {"size": group[0].stat().st_size, "files": [str(path) for path in group]} for group in groups ], } args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт сохранён: {args.json}") if not args.apply: print("Предпросмотр. Для перемещения в карантин добавьте --apply.") return 0 assert quarantine is not None moved = 0 errors = 0 for group in groups: keeper = group[0] for path in group[1:]: try: relative = path.relative_to(root) destination = unique_destination(quarantine / relative) destination.parent.mkdir(parents=True, exist_ok=True) shutil.move(str(path), str(destination)) moved += 1 print(f"В карантин: {path} -> {destination}") except OSError as error: errors += 1 print(f"Ошибка с {path}: {error}") print(f"Оставлен: {keeper}") print(f"Перемещено: {moved}, ошибок: {errors}") return 0 if __name__ == "__main__": raise SystemExit(main())