Сравнить два архива
Показывает добавленные, удалённые и изменённые файлы по именам, размерам и CRC.
Что делает скрипт
Скрипт строит карту элементов для zip или tar и сравнивает её без полной распаковки. Для zip дополнительно используется CRC, для tar сравниваются имена, размеры и типы элементов. Отчёт можно сохранить в JSON, код возврата 1 сигнализирует о различиях.
Быстрый старт
python compare_archives.py old.zip new.zip
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python compare_archives.py old.zip new.zippython compare_archives.py old.tar.gz new.tar.gz --json diff.jsonpython compare_archives.py release-1.zip release-2.zip
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
compare_archives.py
#!/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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.