#!/usr/bin/env python3 """Сравнение состава двух zip или tar архивов.""" from __future__ import annotations import argparse import json import tarfile import zipfile from pathlib import Path def collect(path: Path) -> tuple[str, dict[str, dict]]: entries: dict[str, dict] = {} if zipfile.is_zipfile(path): kind = "zip" with zipfile.ZipFile(path) as archive: for info in archive.infolist(): if info.is_dir(): continue entries[info.filename] = {"size": info.file_size, "crc": info.CRC, "kind": "file"} return kind, entries if tarfile.is_tarfile(path): kind = "tar" with tarfile.open(path, mode="r:*") as archive: for member in archive: if member.isfile(): entries[member.name] = {"size": member.size, "crc": None, "kind": "file"} elif member.isdir(): entries[member.name.rstrip("/") + "/"] = {"size": 0, "crc": None, "kind": "dir"} elif member.issym() or member.islnk(): entries[member.name] = {"size": member.size, "crc": None, "kind": "link"} return kind, entries raise ValueError(f"Формат не распознан: {path}") def main() -> int: parser = argparse.ArgumentParser(description="Сравнить два архива") parser.add_argument("first", type=Path, help="Первый архив") parser.add_argument("second", type=Path, help="Второй архив") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() first_path = args.first.expanduser().resolve() second_path = args.second.expanduser().resolve() for path in (first_path, second_path): if not path.is_file(): parser.error(f"Архив не найден: {path}") try: first_kind, first = collect(first_path) second_kind, second = collect(second_path) except ValueError as error: print(error) return 2 only_first = sorted(set(first) - set(second)) only_second = sorted(set(second) - set(first)) common = sorted(set(first) & set(second)) changed = [] for name in common: left = first[name] right = second[name] if left["size"] != right["size"] or (left["crc"] is not None and right["crc"] is not None and left["crc"] != right["crc"]): changed.append(name) def show(title: str, names: list[str]) -> None: if not names: return print(f"{title}: {len(names)}") for name in names[:50]: print(f" {name}") if len(names) > 50: print(f" и ещё {len(names) - 50}") print(f"Первый: {first_path.name} ({first_kind}), второй: {second_path.name} ({second_kind})") show("Только в первом", only_first) show("Только во втором", only_second) show("Изменены", changed) identical = not only_first and not only_second and not changed print("Архивы совпадают по составу." if identical else "Архивы различаются.") if args.json: report = { "first": str(first_path), "second": str(second_path), "only_first": only_first, "only_second": only_second, "changed": changed, "identical": identical, } args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") return 0 if identical else 1 if __name__ == "__main__": raise SystemExit(main())