#!/usr/bin/env python3 """Генерация manifest для zip или tar.""" from __future__ import annotations import argparse import hashlib import json import tarfile import zipfile from datetime import datetime, timezone from pathlib import Path def hash_stream(handle) -> str: digest = hashlib.sha256() while chunk := handle.read(1024 * 1024): digest.update(chunk) return digest.hexdigest() def hash_file(path: Path) -> str: with path.open("rb") as handle: return hash_stream(handle) def main() -> int: parser = argparse.ArgumentParser(description="Сгенерировать manifest архива") parser.add_argument("archive", type=Path, help="Zip или tar архив") parser.add_argument("--output", type=Path, help="Имя JSON-файла") parser.add_argument("--force", action="store_true", help="Перезаписать manifest") args = parser.parse_args() path = args.archive.expanduser().resolve() if not path.is_file(): parser.error(f"Архив не найден: {path}") output = (args.output or path.with_name(path.name + ".manifest.json")).expanduser().resolve() if output.exists() and not args.force: parser.error(f"Файл уже существует: {output}. Используйте --force") members = [] errors = [] if zipfile.is_zipfile(path): kind = "zip" with zipfile.ZipFile(path) as archive: for info in archive.infolist(): if info.is_dir(): continue record = { "name": info.filename, "size": info.file_size, "mtime": datetime(*info.date_time).isoformat(timespec="seconds"), "sha256": None, } if info.flag_bits & 0x1: record["error"] = "encrypted" errors.append(info.filename) else: try: with archive.open(info) as handle: record["sha256"] = hash_stream(handle) except (RuntimeError, zipfile.BadZipFile) as error: record["error"] = str(error) errors.append(info.filename) members.append(record) elif tarfile.is_tarfile(path): kind = "tar" with tarfile.open(path, mode="r:*") as archive: for member in archive: if not member.isfile(): continue record = { "name": member.name, "size": member.size, "mtime": datetime.fromtimestamp(member.mtime, tz=timezone.utc).isoformat(timespec="seconds"), "sha256": None, } source = archive.extractfile(member) if source is None: record["error"] = "not readable" errors.append(member.name) else: with source: record["sha256"] = hash_stream(source) members.append(record) else: print("Формат не распознан. Поддерживаются zip и tar.") return 2 members.sort(key=lambda item: item["name"]) manifest = { "tool": "archives-generate-manifest", "created": datetime.now(timezone.utc).isoformat(timespec="seconds"), "archive": path.name, "format": kind, "archive_size": path.stat().st_size, "archive_sha256": hash_file(path), "files": len(members), "total_bytes": sum(item["size"] for item in members), "members": members, } output.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8") print(f"Файлов: {manifest['files']}, размер: {manifest['total_bytes'] / 1024 / 1024:.1f} МБ") print(f"Manifest: {output}") if errors: print(f"Не удалось проверить элементов: {len(errors)}") return 1 return 0 if __name__ == "__main__": raise SystemExit(main())