Files
claude-config/bin/project_config/settings.py
T

80 lines
4.1 KiB
Python

"""A project's settings, read from the one config that names its checkout: `~/.claude-projects/<key>/config.toml`.
No setting has a default, so that a client's project never runs on another project's files: a missing config or setting is a Failure that names it."""
import dataclasses
import pathlib
import tomllib
from failure import Failure
PROJECTS = ".claude-projects"
CONFIG = "config.toml"
# Every path a project sets, by its role. The syntax panel picked role names over file names, which a client's project doesn't share.
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles")
# The panel also picked a prefix on every path over bare relative paths: each line says its own place, and a path with no prefix fails instead of landing somewhere by default.
SPELLING = '"checkout:<path>" for a path in the checkout, "folder:<path>" for one in the config\'s folder, or a path that starts with / or ~/'
@dataclasses.dataclass(frozen=True)
class ProjectConfig:
"""folder is `~/.claude-projects/<key>`, and paths holds each of SETTINGS as an absolute path."""
key: str
folder: pathlib.Path
paths: dict[str, pathlib.Path]
def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure:
"""The config that names main, the project's main checkout. A `checkout:` path lands in top, the worktree that asks, which is main itself outside a worktree.
A config that cannot be read fails every project, since it may be the one that names main."""
named: list[tuple[pathlib.Path, dict[str, object]]] = []
for file in sorted((home / PROJECTS).glob(f"*/{CONFIG}")):
values = read(file, home)
if isinstance(values, Failure):
return values
if values.pop("checkout") == main:
named.append((file, values))
if not named:
return Failure(f"no config names the checkout {main}: write ~/{PROJECTS}/<key>/{CONFIG}, as README.md → Install shows")
if len(named) > 1:
return Failure(f"{' and '.join(str(file) for file, _ in named)} both name the checkout {main}; one config may")
file, values = named[0]
paths = {name: placed(values[name], top, file.parent, home) for name in SETTINGS if name in values}
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
*(f"`{name}` is not a setting" for name in values if name not in SETTINGS),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None),
]
if faults:
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}.")
return ProjectConfig(file.parent.name, file.parent, {name: path for name, path in paths.items() if path})
def read(file: pathlib.Path, home: pathlib.Path) -> dict[str, object] | Failure:
"""The config's values, its checkout as an absolute path."""
try:
values = tomllib.loads(file.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as failure:
return Failure(f"cannot read {file}: {failure}")
checkout = anywhere(values.get("checkout"), home)
if checkout is None:
return Failure(f'{file}: `checkout` names the project\'s main checkout as a path that starts with / or ~/, such as "~/code/acme-billing", not {values.get("checkout")!r}')
return {**values, "checkout": checkout}
def placed(value: object, top: pathlib.Path, folder: pathlib.Path, home: pathlib.Path) -> pathlib.Path | None:
"""The path a setting's value spells, or None where it doesn't spell one. A prefixed path stays inside its place."""
if not isinstance(value, str):
return None
for prefix, place in (("checkout:", top), ("folder:", folder)):
if value.startswith(prefix):
inside = pathlib.PurePosixPath(value.removeprefix(prefix))
return None if inside.is_absolute() or ".." in inside.parts or not inside.parts else place / inside
return anywhere(value, home)
def anywhere(value: object, home: pathlib.Path) -> pathlib.Path | None:
if isinstance(value, str) and value.startswith("~/"):
return home / value.removeprefix("~/")
return pathlib.Path(value) if isinstance(value, str) and value.startswith("/") else None