#!/usr/bin/env python3 """Проверка файлов по manifest в формате sha256sum.""" from __future__ import annotations import argparse import hashlib import json import sys from pathlib import Path def file_digest(path: Path, chunk_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while block := handle.read(chunk_size): digest.update(block) return digest.hexdigest() def parse_manifest(path: Path) -> list[tuple[str, str]]: entries: list[tuple[str, str]] = [] for number, raw_line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1): line = raw_line.strip() if not line or line.startswith("#"): continue parts = line.split(None, 1) if len(parts) != 2: raise ValueError(f"Строка {number}: неверный формат") digest, name = parts digest = digest.lower() if len(digest) != 64 or any(char not in "0123456789abcdef" for char in digest): raise ValueError(f"Строка {number}: неверный SHA-256") name = name.lstrip("*").strip() if name: entries.append((digest, name)) return entries def main() -> int: parser = argparse.ArgumentParser(description="Проверить файлы по manifest") parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--root", 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}") root = args.root.expanduser().resolve() if args.root else None if root is not None and not root.is_dir(): parser.error(f"Корень не найден: {root}") try: entries = parse_manifest(manifest) except ValueError as error: print(f"Ошибка manifest: {error}", file=sys.stderr) return 2 report = [] ok = 0 failed = 0 for expected, name in entries: candidate = Path(name) if not candidate.is_absolute() and root is not None: candidate = root / candidate candidate = candidate.expanduser() status = "ok" actual = "" if not candidate.is_file(): status = "missing" else: try: actual = file_digest(candidate) if actual != expected: status = "mismatch" except OSError as error: status = "error" actual = str(error) if status == "ok": ok += 1 else: failed += 1 report.append({"path": str(candidate), "expected": expected, "actual": actual, "status": status}) for item in report: if item["status"] != "ok": print(f"{item['status']}: {item['path']}") print(f"Проверено: {len(report)}, в порядке: {ok}, проблем: {failed}") if args.json: target = args.json.expanduser().resolve() if target.exists(): print(f"Отчёт уже существует: {target}", file=sys.stderr) return 2 target.write_text(json.dumps({"items": report}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт: {target}") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())