#!/usr/bin/env python3 """Генерация JSON manifest для каталога.""" from __future__ import annotations import argparse import hashlib import json import os from datetime import datetime, timezone from pathlib import Path DEFAULT_EXCLUDES = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv"} 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 iter_files(root: Path, excludes: set[str]): for current, dirs, files in os.walk(root): current_path = Path(current) dirs[:] = [ name for name in dirs if name not in excludes and not (current_path / name).is_symlink() ] for name in files: path = current_path / name if path.is_symlink() or not path.is_file(): continue yield path def main() -> int: parser = argparse.ArgumentParser(description="Создать manifest каталога") parser.add_argument("--dir", type=Path, required=True, help="Папка для инвентаризации") parser.add_argument("--output", type=Path, default=Path("manifest.json"), help="Файл JSON") parser.add_argument("--hash", choices=("sha256", "none"), default="sha256", help="Считать ли SHA-256") parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить") parser.add_argument("--force", action="store_true", help="Перезаписать существующий manifest") args = parser.parse_args() root = args.dir.expanduser().resolve() output = args.output.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") if output.exists() and not args.force: parser.error(f"Файл уже существует: {output}. Добавьте --force для перезаписи") excludes = DEFAULT_EXCLUDES | {item.strip() for item in args.exclude if item.strip()} files = [] total_size = 0 for path in iter_files(root, excludes): if path.resolve() == output: continue try: stat = path.stat() except OSError as error: print(f"Пропуск {path}: {error}") continue item = { "path": str(path.relative_to(root)).replace(os.sep, "/"), "size": stat.st_size, "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(timespec="seconds"), } if args.hash == "sha256": try: item["sha256"] = file_hash(path) except OSError as error: print(f"Не удалось прочитать {path}: {error}") continue files.append(item) total_size += stat.st_size data = { "version": 1, "root": str(root), "generated": datetime.now(timezone.utc).isoformat(timespec="seconds"), "hash": args.hash, "count": len(files), "total_size": total_size, "files": files, } output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Файлов: {len(files)}, размер: {total_size} байт") print(f"manifest сохранён: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())