mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 14:26:29 +01:00
main was red on file length, the noqa ban, codespell, test naming and dart coverage; this change touches every one of those jobs. - sickdays: set_enabled is keyword-only; the panel test splits in two with shared probes; the sync wire format moves to DOCS-sync.md. - earned_time: _focus types the project as a Protocol, no noqa; the gate-maturity section moves to DOCS-maturity.md; codespell knows the `checkin` event name. - focus_project: real fixes for every noqa (local-day clocks, typed fakes, logged broad catches, split helpers). The public API that focus-guard calls keeps its signatures; their PLR0913 exemption lives in pyproject with the reason, not in noqa. - crdt-sync: pylint gets nacl/argon2, docstrings, and allows the public E2eLayout.of; _blobs moves to _e2e_blobs.py. - crdt_sync_dart: Argon2Params and the header errors move to e2e_params.dart (re-exported); tests split and reach 100% lines. - sql_drills: test helpers get a leading underscore, as in earned_time. Todo: fda71ed1 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki
|
|
"""projects.json: whole-file atomic writes under one flock (single writer)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import contextmanager
|
|
import fcntl
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import tempfile
|
|
from typing import TYPE_CHECKING
|
|
|
|
from focus_project._errors import RegistryError
|
|
from focus_project._model import Project
|
|
from focus_project._paths import data_dir, lock_path, projects_path
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Iterator
|
|
|
|
|
|
@contextmanager
|
|
def locked() -> Iterator[None]:
|
|
"""Hold the exclusive writer lock for a read-modify-write."""
|
|
data_dir().mkdir(parents=True, exist_ok=True)
|
|
with lock_path().open("a") as handle:
|
|
fcntl.flock(handle, fcntl.LOCK_EX)
|
|
yield
|
|
|
|
|
|
def _project_rows(text: str) -> list[object]:
|
|
"""The ``projects`` list of a registry file; ValueError/KeyError/TypeError."""
|
|
rows = json.loads(text)["projects"]
|
|
if not isinstance(rows, list):
|
|
msg = "'projects' is not a list"
|
|
raise TypeError(msg)
|
|
return rows
|
|
|
|
|
|
def read_all() -> list[Project]:
|
|
"""Every project; a missing file is empty, a bad one raises."""
|
|
try:
|
|
text = projects_path().read_text(encoding="utf-8")
|
|
except FileNotFoundError:
|
|
return []
|
|
try:
|
|
rows = _project_rows(text)
|
|
except (ValueError, KeyError, TypeError) as exc:
|
|
msg = f"unreadable {projects_path()}: {exc}"
|
|
raise RegistryError(msg) from exc
|
|
return [Project.from_dict(row) for row in rows]
|
|
|
|
|
|
def index_of(projects: list[Project], project_id: str) -> int:
|
|
"""Position of the first project with ``project_id``; KeyError if none."""
|
|
for i, project in enumerate(projects):
|
|
if project.id == project_id:
|
|
return i
|
|
raise KeyError(project_id)
|
|
|
|
|
|
def write_all(projects: list[Project]) -> None:
|
|
"""Replace the file atomically: temp file in the same dir, fsync, rename."""
|
|
target = projects_path()
|
|
payload = json.dumps({"projects": [p.to_dict() for p in projects]}, indent=2)
|
|
fd, tmp = tempfile.mkstemp(dir=target.parent, prefix="projects.", suffix=".tmp")
|
|
try:
|
|
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
handle.write(payload + "\n")
|
|
handle.flush()
|
|
os.fsync(handle.fileno())
|
|
Path(tmp).replace(target)
|
|
except BaseException:
|
|
Path(tmp).unlink(missing_ok=True)
|
|
raise
|