#!/usr/bin/env python3 """CSV-отчёт о файлах в каталоге.""" from __future__ import annotations import argparse import csv import hashlib import os from datetime import datetime 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="Создать CSV-отчёт о файлах") parser.add_argument("--dir", type=Path, required=True, help="Папка для инвентаризации") parser.add_argument("--output", type=Path, default=Path("report.csv"), help="Файл CSV") parser.add_argument("--hash", action="store_true", help="Добавить SHA-256") parser.add_argument("--exclude", action="append", default=[], help="Имя папки, которую нужно пропустить") parser.add_argument("--force", action="store_true", help="Перезаписать существующий CSV") 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()} rows = [] 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 relative = path.relative_to(root) row = { "relative_path": str(relative).replace(os.sep, "/"), "name": path.name, "extension": path.suffix.lower(), "size_bytes": stat.st_size, "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(timespec="seconds"), "depth": len(relative.parts) - 1, } if args.hash: try: row["sha256"] = file_hash(path) except OSError as error: print(f"Не удалось прочитать {path}: {error}") continue rows.append(row) total_size += stat.st_size rows.sort(key=lambda item: item["relative_path"].lower()) output.parent.mkdir(parents=True, exist_ok=True) fieldnames = ["relative_path", "name", "extension", "size_bytes", "modified", "depth"] if args.hash: fieldnames.append("sha256") with output.open("w", encoding="utf-8-sig", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) print(f"Файлов: {len(rows)}, суммарный размер: {total_size} байт") print(f"CSV сохранён: {output}") return 0 if __name__ == "__main__": raise SystemExit(main())