Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s
CI / tests (pull_request) Successful in 3m43s
This commit is contained in:
@@ -6,10 +6,10 @@ import errno
|
||||
import gzip
|
||||
import os
|
||||
import pathlib
|
||||
import typing
|
||||
import zlib
|
||||
|
||||
from failure import Failure
|
||||
from text_files.file_writes import replace_file
|
||||
|
||||
SUFFIX = ".gz"
|
||||
|
||||
@@ -43,20 +43,20 @@ def stored_glob(folder: pathlib.Path, pattern: str) -> list[pathlib.Path]:
|
||||
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."""
|
||||
def compress(path: pathlib.Path, *, pack: typing.Callable[..., bytes], replace: typing.Callable[[pathlib.Path, bytes], Failure | None], sync: typing.Callable[[int], None]) -> 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. pack compresses as gzip.compress does, replace writes as replace_file does, and sync flushes as os.fsync does."""
|
||||
packed = gzipped(path)
|
||||
try:
|
||||
before = path.stat()
|
||||
data = path.read_bytes()
|
||||
if unwritten := replace_file(packed, gzip.compress(data, mtime=0)):
|
||||
if unwritten := replace(packed, pack(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))
|
||||
# On disk before the plain file goes, so a crash cannot leave an empty gzip in its place.
|
||||
synced(packed)
|
||||
synced(packed.parent)
|
||||
synced(packed, sync)
|
||||
synced(packed.parent, sync)
|
||||
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):
|
||||
@@ -66,10 +66,10 @@ def compress(path: pathlib.Path) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def synced(path: pathlib.Path) -> None:
|
||||
def synced(path: pathlib.Path, sync: typing.Callable[[int], None]) -> None:
|
||||
handle = os.open(path, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(handle)
|
||||
sync(handle)
|
||||
finally:
|
||||
os.close(handle)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user