Files
claude-config/bin/record_store/stores.py
T

155 lines
6.9 KiB
Python

"""The one way a tool reads or writes a project's records: through the store its config names for each.
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, and `confluence:` a Confluence Cloud page; the goals file may also be a Jira epic's description, which `goals_store` picks."""
import dataclasses
import pathlib
import typing
from record_store.confluence_page import ConfluencePage
from record_store.jira_description import EpicDescription
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from record_store.held import Held
from project_config.settings import ProjectConfig, RECORDS, TOUCH_PREDICTIONS
from text_files.file_writes import replace_file
class RecordStore(typing.Protocol):
"""One record, as text. record_store.contract holds every backend to the same behaviour."""
@property
def label(self) -> str:
"""What a message calls the record, such as its path."""
@property
def tracked(self) -> str | None:
"""The record's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a wiki page."""
def read(self) -> str | Failure:
"""The record's text as it stands, empty where it doesn't exist yet."""
def held(self) -> Held | Failure:
"""The record as it stands, with the version a write over it names."""
def write(self, text: str, over: str | None = None) -> Held | Failure:
"""Replaces the record's whole text, creating the record where it doesn't exist yet, and gives the record as the write left it. over is the version held() gave: where someone saved the record since, the write refuses. None replaces the record as it stands."""
@dataclasses.dataclass(frozen=True)
class FileStore:
"""A record kept as a markdown file at path."""
path: pathlib.Path
tracked: str | None
@property
def label(self) -> str:
return str(self.path)
def held(self) -> Held | Failure:
text = self.read()
return text if isinstance(text, Failure) else Held(text)
def read(self) -> str | Failure:
try:
return self.path.read_text(encoding="utf-8")
except FileNotFoundError:
return ""
except UnicodeDecodeError as failure:
return Failure(f"cannot read {self.path}: not UTF-8 on line {failure.object[: failure.start].count(b'\n') + 1}")
except OSError as failure:
return Failure(f"cannot read {self.path}: {failure.strerror}")
def write(self, text: str, over: str | None = None) -> Held | Failure:
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"cannot write {self.path}: {failure.strerror}")
unwritten = replace_file(self.path, text.encode("utf-8"))
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else Held(text)
def store(config: ProjectConfig, record: str) -> RecordStore:
"""The store config names for record, one of RECORDS."""
if record not in RECORDS:
raise ValueError(f"{record} is not a record; the records are {', '.join(RECORDS)}")
if record not in config.pages:
return FileStore(config.paths[record], config.tracked(record))
# load refuses a config that names a page and no env-file.
assert config.env_file is not None
return ConfluencePage(config.pages[record], config.env_file)
def touch_predictions_store(config: ProjectConfig) -> RecordStore | None:
"""The store of the touch-predictions record, the one record a config may leave out; None where it does."""
if TOUCH_PREDICTIONS not in config.paths:
return None
return FileStore(config.paths[TOUCH_PREDICTIONS], config.tracked(TOUCH_PREDICTIONS))
def goals_store(config: ProjectConfig) -> RecordStore:
"""The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description, which the store only reads."""
if config.goals_epic is None:
return FileStore(config.paths["goals-and-audience"], config.tracked("goals-and-audience"))
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return EpicDescription(config.goals_epic, config.env_file)
def held_at(revision: str, record: RecordStore, cwd: str, run: Git = git) -> str | Failure:
"""record's text at revision, read in the checkout at cwd, where its commits hold the record; else as it stands. Empty where there is no such record."""
return record.read() if record.tracked is None else file_at(revision, record.tracked, cwd, run)
def local_file(record: RecordStore, copy: pathlib.Path) -> pathlib.Path | Failure:
"""A file holding record's text, for an agent, which reads and edits files: the record's own file where a file is its backend, else copy, written with the text as it stands, and its version beside it, for `stored`, a later process, to write over. Neither exists where the record doesn't yet. `stored` puts an edited copy back."""
if isinstance(record, FileStore):
return record.path
held = record.held()
if isinstance(held, Failure):
return held
if held.text:
written = FileStore(copy, None).write(held.text)
if isinstance(written, Failure):
return written
else:
try:
# An earlier copy would read as the record's text, and `stored` would put it back.
copy.unlink(missing_ok=True)
except OSError as failure:
return Failure(f"cannot remove {copy}: {failure.strerror}")
# Kept only once the copy holds the text: a version kept for a read that failed would let a later save overwrite the save it saw.
return kept(copy, held.version) or copy
def stored(record: RecordStore, copy: pathlib.Path) -> Failure | None:
"""Stores in record the text of copy, the file `local_file` gave for it, over the version kept beside it. Where that is the record's own file, the edit is already the record. The version the write left is kept for the next save."""
if isinstance(record, FileStore):
return None
text = FileStore(copy, None).read()
if isinstance(text, Failure):
return text
if not text:
return Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}")
over = FileStore(version_file(copy), None).read()
if isinstance(over, Failure):
return over
written = record.write(text, over.strip() or None)
return written if isinstance(written, Failure) else kept(copy, written.version)
def version_file(copy: pathlib.Path) -> pathlib.Path:
"""The file beside copy that keeps the version of the record copy holds."""
return copy.with_suffix(".version")
def kept(copy: pathlib.Path, version: str | None) -> Failure | None:
"""Keeps version beside copy, or removes the file that kept an earlier one where version is None."""
if version is not None:
written = FileStore(version_file(copy), None).write(version)
return written if isinstance(written, Failure) else None
try:
version_file(copy).unlink(missing_ok=True)
except OSError as failure:
return Failure(f"cannot remove {version_file(copy)}: {failure.strerror}")
return None