"""A file kept plain, or gzipped beside its plain name as .gz: reading it by its plain name, and compressing it. Why gzip and when a file is compressed: docs/decisions.md → `archives: loop-claude's archive and the review folders keep every file, and gzip each one 30 days after it was last written`. """ import errno import gzip import os import pathlib import zlib from failure import Failure from text_files.file_writes import replace_file SUFFIX = ".gz" def stored(path: pathlib.Path) -> pathlib.Path | None: """Where the file named path is kept: path itself, else its gzip; None where neither is.""" # A plain file beside its gzip was written after it was compressed, so it holds the newer bytes. Whatever else stands at path, such as a folder, is read as path, so the read names it. return next((kept for kept in (path, gzipped(path)) if kept.exists()), None) def read_stored(path: pathlib.Path) -> bytes: """The bytes of the file named path, read from its gzip where it is kept that way. Raises OSError, FileNotFoundError where neither is kept.""" kept = stored(path) if kept is None: raise FileNotFoundError(2, "No such file or directory", str(path)) if kept == path: return path.read_bytes() try: return gzip.decompress(kept.read_bytes()) except (EOFError, zlib.error) as failure: raise OSError(errno.EIO, f"not a whole gzip: {failure}", str(kept)) from failure def stored_glob(folder: pathlib.Path, pattern: str) -> list[pathlib.Path]: """The plain name of each file in folder that pattern matches, whether kept plain or gzipped, sorted.""" return sorted({*folder.glob(pattern), *(path.with_name(path.name.removesuffix(SUFFIX)) for path in folder.glob(pattern + SUFFIX))}) def compress(path: pathlib.Path) -> Failure | None: """Replaces path with its gzip, which keeps path's times: writes the gzip, reads it back, and removes path only once it reads back path's bytes. A failure keeps path.""" packed = gzipped(path) try: before = path.stat() data = path.read_bytes() if unwritten := replace_file(packed, gzip.compress(data, mtime=0)): return Failure(f"could not compress {path}: {unwritten.reason}") if gzip.decompress(packed.read_bytes()) != data: return Failure(f"could not compress {path}: {packed} reads back other bytes") os.utime(packed, ns=(before.st_atime_ns, before.st_mtime_ns)) after = path.stat() # Written while it compressed: the plain file keeps the newer bytes, which readers prefer, and a later run compresses them. if (after.st_size, after.st_mtime_ns) == (before.st_size, before.st_mtime_ns): path.unlink() except (OSError, EOFError, zlib.error) as failure: return Failure(f"could not compress {path}: {failure}") return None def gzipped(path: pathlib.Path) -> pathlib.Path: return path.with_name(path.name + SUFFIX)