180 lines
5.9 KiB
Python
180 lines
5.9 KiB
Python
"""State dir layout, atomic JSON files and the append-only ledger."""
|
|
import contextlib
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
SUBDIRS = ("bases", "jobs", "raw", "notes", "out", "briefs")
|
|
RETRY_TRIES = 40
|
|
RETRY_SLEEP_S = 0.05
|
|
|
|
_ledger_lock = threading.Lock()
|
|
|
|
|
|
def _run_md(run) -> str:
|
|
p = os.path.abspath(str(run))
|
|
if not p.lower().endswith(".md"):
|
|
raise ValueError("--run must name the run log .md file: %s" % p)
|
|
return p
|
|
|
|
|
|
def run_slug(run) -> str:
|
|
"""`logs/<slug>/run.md` -> `<slug>`; any other `<stem>.md` -> `<stem>`."""
|
|
p = Path(_run_md(run))
|
|
return p.parent.name if p.name.lower() == "run.md" else p.stem
|
|
|
|
|
|
def _git_rev_parse(d: Path, flag: str) -> Path | None:
|
|
"""`git rev-parse <flag>` run in `d`, made absolute against `d`; None without git, outside a
|
|
repo or on failure."""
|
|
try:
|
|
r = subprocess.run(["git", "rev-parse", flag], cwd=str(d),
|
|
stdin=subprocess.DEVNULL, capture_output=True, timeout=30)
|
|
except (OSError, subprocess.SubprocessError):
|
|
return None
|
|
out = r.stdout.decode("utf-8", "replace").strip()
|
|
return Path(os.path.abspath(os.path.join(str(d), out))) if r.returncode == 0 and out else None
|
|
|
|
|
|
def _git_toplevel(d: Path) -> Path | None:
|
|
"""Toplevel of the checkout holding `d`; None without git, outside a repo or on failure."""
|
|
return _git_rev_parse(d, "--show-toplevel")
|
|
|
|
|
|
def _same_repo(a: Path, b: Path) -> bool:
|
|
"""Both checkouts share one `--git-common-dir` (one repo, or worktrees of one repo)."""
|
|
ca, cb = _git_rev_parse(a, "--git-common-dir"), _git_rev_parse(b, "--git-common-dir")
|
|
if ca is None or cb is None:
|
|
return False
|
|
return os.path.normcase(str(ca.resolve())) == os.path.normcase(str(cb.resolve()))
|
|
|
|
|
|
def scratch_root(run) -> Path:
|
|
"""$SPIRE_SCRATCH, else `<root>/.spire/scratch`. `<root>` = the run log's toplevel; the cwd's
|
|
toplevel instead when the run log is in another repo or in none (external tickets folder);
|
|
else the run's dir. Worktrees of one repo count as the same repo. The run's toplevel comes
|
|
from the nearest existing ancestor of the run's dir, so `init` before the run dir exists
|
|
resolves to the same place as every later call from the same cwd."""
|
|
run_dir = Path(_run_md(run)).parent
|
|
env = os.environ.get("SPIRE_SCRATCH")
|
|
if env:
|
|
return Path(os.path.abspath(env))
|
|
probe = run_dir
|
|
while not probe.is_dir() and probe.parent != probe:
|
|
probe = probe.parent
|
|
top = _git_toplevel(probe)
|
|
try:
|
|
cwd_top = _git_toplevel(Path.cwd())
|
|
except OSError: # cwd deleted
|
|
cwd_top = None
|
|
if cwd_top is not None and (top is None or not _same_repo(top, cwd_top)):
|
|
top = cwd_top
|
|
return (top if top is not None else run_dir) / ".spire" / "scratch"
|
|
|
|
|
|
def state_dir(run) -> Path:
|
|
"""`<scratch_root>/<slug>/gremlins`."""
|
|
return scratch_root(run) / run_slug(run) / "gremlins"
|
|
|
|
|
|
def init_state(run) -> Path:
|
|
"""Create the state dir and its subdirs (idempotent). Write `<scratch_root>/.gitignore` = `*`
|
|
when it is missing; never overwrite one."""
|
|
state = state_dir(run)
|
|
for d in SUBDIRS:
|
|
(state / d).mkdir(parents=True, exist_ok=True)
|
|
ignore = scratch_root(run) / ".gitignore"
|
|
with contextlib.suppress(FileExistsError), open(ignore, "xb") as f:
|
|
f.write(b"*\n")
|
|
return state
|
|
|
|
|
|
def _retry(fn, tries: int = RETRY_TRIES, sleep_s: float = RETRY_SLEEP_S):
|
|
"""Call fn(); retry PermissionError (Windows sharing violations)."""
|
|
for attempt in range(1, tries + 1):
|
|
try:
|
|
return fn()
|
|
except PermissionError:
|
|
if attempt == tries:
|
|
raise
|
|
time.sleep(sleep_s)
|
|
|
|
|
|
def atomic_write_bytes(path, data: bytes) -> None:
|
|
"""Write to a temp file in the same dir, then `os.replace` with retries."""
|
|
path = Path(path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = path.parent / (".%s.%d.%s.tmp" % (path.name, os.getpid(), uuid.uuid4().hex[:8]))
|
|
with open(tmp, "wb") as f:
|
|
f.write(data)
|
|
f.flush()
|
|
os.fsync(f.fileno())
|
|
try:
|
|
_retry(lambda: os.replace(tmp, path))
|
|
except BaseException:
|
|
with contextlib.suppress(OSError):
|
|
os.remove(tmp)
|
|
raise
|
|
|
|
|
|
def read_bytes_retry(path) -> bytes:
|
|
def _read():
|
|
with open(path, "rb") as f:
|
|
return f.read()
|
|
return _retry(_read)
|
|
|
|
|
|
def read_json(p) -> dict | None:
|
|
"""The parsed file, or None if it does not exist. Corrupt content raises ValueError."""
|
|
try:
|
|
data = read_bytes_retry(p)
|
|
except FileNotFoundError:
|
|
return None
|
|
return json.loads(data.decode("utf-8"))
|
|
|
|
|
|
def write_json(p, obj) -> None:
|
|
atomic_write_bytes(p, (json.dumps(obj, indent=1, sort_keys=True) + "\n").encode("utf-8"))
|
|
|
|
|
|
def _ledger_path(run) -> Path:
|
|
return state_dir(run) / "ledger.jsonl"
|
|
|
|
|
|
def ledger_append(run, line: dict) -> None:
|
|
"""Append one JSON line with a single write; repairs a torn last line first."""
|
|
path = _ledger_path(run)
|
|
body = (json.dumps(line, sort_keys=True) + "\n").encode("utf-8")
|
|
|
|
def _append():
|
|
torn = False
|
|
with contextlib.suppress(FileNotFoundError), open(path, "rb") as r:
|
|
if r.seek(0, os.SEEK_END) > 0:
|
|
r.seek(-1, os.SEEK_END)
|
|
torn = r.read(1) != b"\n"
|
|
with open(path, "ab") as f:
|
|
f.write((b"\n" if torn else b"") + body)
|
|
with _ledger_lock:
|
|
_retry(_append)
|
|
|
|
|
|
def ledger_lines(run) -> list[dict]:
|
|
"""Every parsable line of the ledger; [] when there is none yet."""
|
|
try:
|
|
data = read_bytes_retry(_ledger_path(run))
|
|
except FileNotFoundError:
|
|
return []
|
|
out = []
|
|
for ln in data.splitlines():
|
|
try:
|
|
obj = json.loads(ln.decode("utf-8", "replace"))
|
|
except ValueError:
|
|
continue
|
|
if isinstance(obj, dict):
|
|
out.append(obj)
|
|
return out
|