File size: 1,321 Bytes
c4e128a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""File system utilities for the KDC project."""

from __future__ import annotations

import hashlib
from pathlib import Path


def ensure_dir(path: Path) -> Path:
    """Create *path* (and parents) if it does not exist. Returns *path*."""
    path.mkdir(parents=True, exist_ok=True)
    return path


def file_sha256(path: Path, chunk_size: int = 65_536) -> str:
    """Return the SHA-256 hex digest of a file without loading it fully into RAM."""
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            h.update(chunk)
    return h.hexdigest()


def human_size(size_bytes: int) -> str:
    """Format a byte count as a human-readable string (e.g. '2.3 MB')."""
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if abs(size_bytes) < 1024.0:
            return f"{size_bytes:.1f} {unit}"
        size_bytes = int(size_bytes / 1024.0)
    return f"{size_bytes:.1f} PB"


def iter_pdfs(root: Path, recursive: bool = True) -> list[Path]:
    """Return all .pdf files under *root*, optionally recursive."""
    pattern = "**/*.pdf" if recursive else "*.pdf"
    return sorted(root.glob(pattern))


def safe_stem(path: Path) -> str:
    """Return the filename stem, safe for use as a directory name."""
    return path.stem.replace(" ", "_").lower()