#!/usr/bin/env python3 """Проверка файлов по контрольным суммам SHA-256.""" from __future__ import annotations import argparse import hashlib import json import sys from pathlib import Path def file_hash(path: Path, chunk_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(chunk_size): digest.update(chunk) return digest.hexdigest() def load_entries(path: Path) -> tuple[list[tuple[str, str]], Path | None]: text = path.read_text(encoding="utf-8", errors="replace") if path.suffix.lower() == ".json" or text.lstrip().startswith("{"): data = json.loads(text) suggested = Path(data["root"]) if data.get("root") else None entries = [] for item in data.get("files", []): relative = item.get("path") digest = item.get("sha256") or item.get("hash") if relative and digest: entries.append((str(relative), str(digest).lower())) return entries, suggested entries = [] for line in text.splitlines(): line = line.strip() if not line or line.startswith("#"): continue parts = line.split(None, 1) if len(parts) != 2 or len(parts[0]) != 64: continue digest, name = parts if name.startswith("*"): name = name[1:] entries.append((name, digest.lower())) return entries, None def main() -> int: parser = argparse.ArgumentParser(description="Проверить контрольные суммы") parser.add_argument("--manifest", type=Path, required=True, help="JSON manifest или список sha256sum") parser.add_argument("--base", type=Path, help="Базовая папка для относительных путей") parser.add_argument("--json", type=Path, help="Сохранить результат в JSON") args = parser.parse_args() manifest = args.manifest.expanduser().resolve() if not manifest.is_file(): parser.error(f"Manifest не найден: {manifest}") try: entries, suggested = load_entries(manifest) except (OSError, ValueError, json.JSONDecodeError) as error: parser.error(f"Не удалось прочитать manifest: {error}") if not entries: parser.error("В manifest не найдено ни одной записи с SHA-256") if args.base: base = args.base.expanduser().resolve() elif suggested: base = suggested.expanduser().resolve() else: base = manifest.parent if not base.is_dir(): parser.error(f"Базовая папка не найдена: {base}") checked = 0 failed = 0 missing = 0 failures = [] for relative, expected in entries: path = Path(relative) if not path.is_absolute(): path = base / path if not path.is_file(): missing += 1 failures.append({"path": str(path), "status": "missing"}) print(f"НЕТ ФАЙЛА: {path}") continue try: actual = file_hash(path) except OSError as error: failed += 1 failures.append({"path": str(path), "status": "unreadable", "error": str(error)}) print(f"ОШИБКА ЧТЕНИЯ: {path}: {error}") continue checked += 1 if actual == expected: print(f"OK: {path}") else: failed += 1 failures.append({"path": str(path), "status": "mismatch", "expected": expected, "actual": actual}) print(f"НЕ СОВПАЛО: {path}") print(f"\nПроверено: {checked}, ошибок: {failed}, пропущено: {missing}") if args.json: output = args.json.expanduser() output.parent.mkdir(parents=True, exist_ok=True) output.write_text( json.dumps( {"manifest": str(manifest), "base": str(base), "checked": checked, "failures": failures}, ensure_ascii=False, indent=2, ) + "\n", encoding="utf-8", ) print(f"Отчёт сохранён: {output}") return 1 if failed or missing else 0 if __name__ == "__main__": raise SystemExit(main())