Files
claude-config/bin/project_config/settings.py
T
2026-11-20 19:32:59 +01:00

477 lines
28 KiB
Python

"""A project's settings, read from the one config that names its checkout: `~/.claude-projects/<key>/config.toml`.
No path 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 decimal
import math
import pathlib
import re
import tomllib
import typing
from failure import Failure
from plan.formula import parse_formula
from plan.todo_table import SHAPE
from project_config import templates
from plan.ranking import variables
PROJECTS = ".claude-projects"
CONFIG = "config.toml"
# The key of do-epic's machine-wide settings: the folder's config.toml has no `checkout`, so no project may use the key.
DO_EPIC = "do-epic"
# A Jira Cloud or Confluence Cloud site's address: only https, so the credentials are never sent in the clear.
SITE = r"https://[A-Za-z0-9.-]+(?::[0-9]+)?"
# Every path a project sets, by its role. Three readers, seated as the human who writes the config, picked the spelling from four candidates. They 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", "standards")
# They also picked a prefix over bare relative paths: each line says its own place, and a relative 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 ~/'
# A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
ENV_FILE = "env-file"
# An optional setting: the service that sends the loop's DMs to the human, one of NOTIFIERS. A project that names none gets no DMs, so a client's env file of Jira credentials is never read for a chat token.
NOTIFIER = "notifier"
Notifier = typing.Literal["mattermost", "slack"]
NOTIFIERS: tuple[Notifier, ...] = typing.get_args(Notifier)
# An optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out.
WAIT_FOR_APPROVAL = "wait-for-approval"
# An optional setting: who merges a chunk's pull request, one of MERGERS; the chunk where it is left out.
MERGE = "merge"
Merger = typing.Literal["chunk", "human"]
MERGERS: tuple[Merger, ...] = typing.get_args(Merger)
# An optional boolean setting: whether the loop may run the project's language runtime, package manager, tests and task runner on the host, for a project with no container setup. False where left out.
TOOLING_ON_HOST = "tooling-on-host"
# An optional number setting: the comprehension score under which code health is very important. A legacy project, whose code scores low, may lower it.
READABILITY_FLOOR = "readability-floor"
# The floor where the config leaves it out, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
DEFAULT_FLOOR = decimal.Decimal("7.0")
# The most chunks of the project loop-claude runs at once, each in its own tmux window; 1 where left out. Three readers seated as the README's audience picked the spelling 2-1 over concurrent-chunks.
PARALLEL_CHUNKS = "parallel-chunks"
# The optional text settings. `language` is the language the project's prose is written in, by its English name. The others are templates, as `templates` says.
LANGUAGE = "language"
COMMIT_TITLE = "commit-title"
PULL_REQUEST_TITLE = "pull-request-title"
BRANCH = "branch"
# Two optional settings. `epic-branch` names the working branch that an epic's chunks branch off and merge into, `{epic}` standing for the epic's key (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`). `review-request-comment` is the comment `chunk-pr` posts on a pull request into that branch, to ask a reviewer that reviews only pull requests into the default branch. Three readers, seated as the human who writes the config, a chunk's worker and one of a client's team, picked both spellings from four candidates each, 3-0: `merge-branch` and `working-branch` read as the chunk's own branch, and `base-branch` as replacing the default branch for the whole repo.
EPIC_BRANCH = "epic-branch"
REVIEW_REQUEST_COMMENT = "review-request-comment"
# An optional path setting: main's help says what it places.
TOUCH_PREDICTIONS = "touch-predictions"
# An optional setting: a list of paths, each spelt as SPELLING says, to the files that hold the team's own coding conventions, which each reviewer agent larv-review launches reads. Three readers, seated as the human who writes a client's config, picked the spelling 2-1 from four candidates, over a bare `conventions`, which they confused with `principles` and `working-rules`.
CODING_CONVENTIONS = "coding-conventions"
# Two optional settings, each a name, set together and only where `plan` names a Jira epic: the name of the workflow transition that finishes an item, and of the status it must lead to. Three readers, seated as the human who writes a client's config, picked the spelling from four candidates: two flat keys, as the other settings are, with a prefix that says what they apply to.
JIRA_FINISH_TRANSITION = "jira-finish-transition"
JIRA_FINISH_STATUS = "jira-finish-status"
JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS)
# Two settings, needed where `plan` names a Jira epic and allowed only there: what a todo.md states under ## Scoring.
JIRA_SCORE_FORMULA = "jira-score-formula"
JIRA_SCORE_BAR = "jira-score-bar"
JIRA_SCORE = (JIRA_SCORE_FORMULA, JIRA_SCORE_BAR)
# The issue types that `todo-item add` files an item as and do-epic files a finding as, and do-epic files a release review as; only do-epic's config reads the review type.
JIRA_FINDING_TYPE = "jira-finding-type"
JIRA_REVIEW_TYPE = "jira-review-type"
# Jira Software's project templates ship Task, but a project such as TW may lack it.
DEFAULT_ISSUE_TYPE = "Task"
# The settings allowed only where `plan` names a Jira epic.
JIRA_PLAN_ONLY = (*JIRA_FINISH, *JIRA_SCORE, JIRA_FINDING_TYPE)
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
JIRA = "jira:"
EPIC_SPELLINGS = {
"goals-and-audience": '"jira:https://<site>/browse/<epic\'s key>" for goals and audience kept in a Jira Cloud epic\'s description',
"plan": '"jira:https://<site>/browse/<epic\'s key>" for a plan kept as a Jira Cloud epic\'s child issues',
}
# The settings that each name a record, a document a project keeps beside its plan. Each may name a Confluence Cloud page in place of a path: `confluence:`, then the page's address as the browser shows it, whose last part, the title, may be left out.
RECORDS = ("decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog")
CONFLUENCE = "confluence:"
# The records that ranking a plan reads.
RANKED = ("decisions", "comprehension-history")
PAGE_SPELLING = '"confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>" for a record kept on a Confluence Cloud page'
OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials"
@dataclasses.dataclass(frozen=True)
class Epic:
"""A Jira Cloud epic: site is its site's address, such as https://acme.atlassian.net, and key its issue key, such as ABC-12."""
site: str
key: str
@property
def spelling(self) -> str:
"""The epic as a config spells it."""
return f"{JIRA}{self.site}/browse/{self.key}"
@dataclasses.dataclass(frozen=True)
class Finish:
"""How a finished item of a Jira plan moves: by the workflow transition named transition, which must lead to the status named status."""
transition: str
status: str
@dataclasses.dataclass(frozen=True)
class JiraScoring:
"""How a plan in Jira scores an item: by formula, such as `100 * V / (2**S + 8)`, with bar the lowest score at which one is filed."""
formula: str
bar: float
@dataclasses.dataclass(frozen=True)
class Page:
"""A Confluence Cloud page: site is its site's address, such as https://acme.atlassian.net, page_id its number, and spelling the setting's value as the config writes it."""
site: str
page_id: str
spelling: str
@dataclasses.dataclass(frozen=True)
class Unnamed(Failure):
"""No config names a checkout here: none names the one asked for, or git fails there, as outside a checkout. A config that is faulty or cannot be read is a plain Failure."""
@dataclasses.dataclass(frozen=True)
class ProjectConfig:
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except three kinds that pages or epics hold instead: `plan` and `goals-and-audience` where they are kept in Jira, and a record kept on a Confluence page."""
key: str
folder: pathlib.Path
top: pathlib.Path
paths: dict[str, pathlib.Path]
# The config's `env-file`, or None where it sets none.
env_file: pathlib.Path | None = None
wait_for_approval: bool = False
merge: Merger = "chunk"
tooling_on_host: bool = False
readability_floor: decimal.Decimal = DEFAULT_FLOOR
parallel_chunks: int = 1
language: str = "English"
commit_title: str = templates.TITLE
pull_request_title: str = templates.TITLE
branch: str = templates.BRANCH
# The config's `epic-branch` template, or None where it sets none.
epic_branch: str | None = None
# The config's `review-request-comment`, or None where it sets none.
review_request_comment: str | None = None
# The config's `coding-conventions`, in its order; empty where it sets none.
coding_conventions: tuple[pathlib.Path, ...] = ()
# The epic whose child issues are the plan, where the config's `plan` names one.
epic: Epic | None = None
# The epic whose description holds the goals and audience, where the config's `goals-and-audience` names one.
goals_epic: Epic | None = None
# The config's `notifier`, or None where it names none.
notifier: Notifier | None = None
# The config's `jira-finish-transition` and `jira-finish-status`, or None where it sets neither.
jira_finish: Finish | None = None
# The config's `jira-finding-type`, the issue type `todo-item add` files an item as.
jira_finding_type: str = DEFAULT_ISSUE_TYPE
# The config's `jira-score-formula` and `jira-score-bar`, which it sets where `plan` names an epic.
jira_scoring: JiraScoring | None = None
# The Confluence page of each record the config keeps on one, by the record's setting.
pages: dict[str, Page] = dataclasses.field(default_factory=dict)
@property
def plan_file(self) -> pathlib.Path | None:
"""The plan's file; None where the plan is kept in Jira."""
return self.paths.get("plan")
@property
def plan_label(self) -> str:
"""What a message calls the plan: its path, or the epic as the config spells it."""
return self.epic.spelling if self.epic else str(self.paths["plan"])
@property
def places(self) -> dict[str, str]:
"""Where each of SETTINGS is kept, in SETTINGS' order, then TOUCH_PREDICTIONS where the config sets it: a path, or the epic or page as the config spells it."""
spelt = {name: kept.spelling for name, kept in {"plan": self.epic, "goals-and-audience": self.goals_epic, **self.pages}.items() if kept}
return {name: spelt[name] if name in spelt else str(self.paths[name]) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in spelt or name in self.paths}
@property
def texts(self) -> dict[str, str]:
"""Each text setting's value, by the name the config gives it."""
return {LANGUAGE: self.language, COMMIT_TITLE: self.commit_title, PULL_REQUEST_TITLE: self.pull_request_title, BRANCH: self.branch}
@property
def titles(self) -> templates.Titles:
return templates.Titles(self.commit_title, self.pull_request_title)
def tracked(self, setting: str) -> str | None:
"""setting's path from top, as git names a file in a commit; None where the config puts it outside the checkout, whose commits hold no version of it."""
path = self.paths.get(setting)
if path is None:
return None
return path.relative_to(self.top).as_posix() if path.is_relative_to(self.top) else None
def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure:
"""The config that names main, the project's main checkout.
top is the worktree that asks, and main itself outside a worktree. A `checkout:` path lands in top.
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 configs(home):
config = read(file, home)
if isinstance(config, Failure):
return config
# Resolved on both sides, so a checkout reached through a symlink, or spelt with `..`, still finds its config.
if config[0].resolve() == main.resolve():
named.append((file, config[1]))
if not named:
return Unnamed(f"no config names the checkout {main}: write ~/{PROJECTS}/<key>/{CONFIG}, as `project-config --help` shows")
if len(named) > 1:
return Failure(f"{' and '.join(str(file) for file, _ in named)} each name the checkout {main}; only one config may")
file, values = named[0]
paths = {name: placed(values[name], top, file.parent, home) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in values}
epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS}
pages = {name: page for name in RECORDS if (page := page_of(values.get(name)))}
conventions = conventions_of(values.get(CODING_CONVENTIONS, []), top, file.parent, home)
env_file = anywhere(values.get(ENV_FILE), home)
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
scalars = {scalar: scalar.read(values[scalar.name]) for scalar in SCALARS if scalar.name in values}
formula, bar = values.get(JIRA_SCORE_FORMULA), values.get(JIRA_SCORE_BAR)
scoring = JiraScoring(formula, bar_value) if isinstance(formula, str) and (bar_value := bar_of(bar)) is not None else None
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, *OPTIONAL)),
*(f"`{scalar.name}` is {values[scalar.name]!r}, {read.reason}" for scalar, read in scalars.items() if isinstance(read, Unfit)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in (*EPIC_SPELLINGS, *RECORDS)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {PAGE_SPELLING}" for name in RECORDS if name in values and paths[name] is None and name not in pages),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{CODING_CONVENTIONS}` is {values[CODING_CONVENTIONS]!r}, not a list of paths, each {SPELLING}"] if conventions is None else []),
# Each setting that reaches a service needs the file that holds its credentials.
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
*(f"`{name}` names a Confluence page, so `{ENV_FILE}` must name the file that holds its credentials" for name in pages if ENV_FILE not in values),
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira or Confluence mustn't hold up.
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
*(f"`{name}` names a Confluence page, so `plan` must name a Jira epic" for name in RANKED if name in pages and not epics["plan"]),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_PLAN_ONLY if name in values and not epics["plan"]),
*(f"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
*finish_faults(values),
*([f"`{REVIEW_REQUEST_COMMENT}` is set, so `{EPIC_BRANCH}` must be set: the comment goes on pull requests into that branch"] if REVIEW_REQUEST_COMMENT in values and EPIC_BRANCH not in values else []),
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}: {fault}"] if JIRA_SCORE_FORMULA in values and (fault := formula_fault(formula)) else []),
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
]
if faults:
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
# faults names a formula or bar a plan in Jira lacks or misspells.
assert scoring is not None or not epics["plan"]
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=finish_of(values), jira_scoring=scoring, pages=pages, coding_conventions=conventions or ())
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
@dataclasses.dataclass(frozen=True)
class Unfit:
"""Why a setting's value doesn't fit it, as the end of the sentence "`<setting>` is <value>, <reason>"."""
reason: str
@dataclasses.dataclass(frozen=True)
class Scalar:
"""An optional setting that holds one value, not a path: the ProjectConfig field it sets, whose default is its value where the config leaves it out, how its value is read, and how `project-config <name>` prints it."""
name: str
field: str
# The value, or Unfit; typed Any, since each Scalar reads into its own field's type.
read: typing.Callable[[object], typing.Any]
shown: typing.Callable[[typing.Any], str] = str
def switch(value: object) -> bool | Unfit:
return value if isinstance(value, bool) else Unfit("not true or false")
def floor_read(value: object) -> decimal.Decimal | Unfit:
floor = floor_of(value)
return Unfit(f"not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`") if floor is None else floor
def parallel_read(value: object) -> int | Unfit:
return value if type(value) is int and value >= 1 else Unfit(f"not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`")
def merger_read(value: object) -> Merger | Unfit:
return next((name for name in MERGERS if name == value), None) or Unfit(f"not {' or '.join(f'"{name}"' for name in MERGERS)}")
def notifier_read(value: object) -> Notifier | Unfit:
return next((name for name in NOTIFIERS if name == value), None) or Unfit(f"not {' or '.join(NOTIFIERS)}")
def text_read(fault: typing.Callable[[object], str | None]) -> typing.Callable[[object], str | Unfit]:
"""A text setting's reader, from the check that says why a value doesn't fit."""
def read(value: object) -> str | Unfit:
found = fault(value)
return Unfit(found) if found else str(value)
return read
def type_fault(value: object, example: str = "Feature") -> str | None:
"""Why value is no issue type's name; None where it is one. example is a name a message quotes."""
return None if name_of(value) else f'not the name Jira shows, such as "{example}"'
def formula_fault(value: object) -> str | None:
"""Why value is no formula that may score an item, as todo.md's `Score` line states one; None where it is one."""
if not isinstance(value, str):
return "not a formula, such as \"100 * V / (2**S + 8)\""
parsed = parse_formula(value, variables(SHAPE))
return parsed.reason if isinstance(parsed, Failure) else None
def bar_of(value: object) -> float | None:
"""The bar value spells, an integer or a float; None where it spells none, as for a boolean or TOML's nan or inf, as floor_of says."""
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
return None
return float(value)
def finish_faults(values: dict[str, object]) -> list[str]:
"""What is wrong with the two JIRA_FINISH settings in values, which are set together or not at all."""
return [
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
]
def finish_of(values: dict[str, object]) -> Finish | None:
"""The Finish the two JIRA_FINISH settings in values name; None where they don't name both."""
names = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
return Finish(*names) if len(names) == 2 else None
def name_of(value: object) -> str | None:
"""The name value holds, of a Jira transition or status; None where it holds none."""
return value if isinstance(value, str) and value.strip() else None
def epic_of(value: object) -> Epic | None:
"""The epic a setting's value spells; None where it spells none."""
spelt = isinstance(value, str) and re.fullmatch(rf"{JIRA}({SITE})/browse/([A-Z][A-Z0-9_]*-[0-9]+)", value)
return Epic(spelt.group(1), spelt.group(2)) if spelt else None
def page_of(value: object) -> Page | None:
"""The page a setting's value spells; None where it spells none."""
spelt = isinstance(value, str) and re.fullmatch(rf"{CONFLUENCE}({SITE})/wiki/spaces/[^/?#]+/pages/([0-9]+)(?:/[^/?#]*)?", value)
return Page(spelt.group(1), spelt.group(2), spelt.string) if spelt else None
def floor_of(value: object) -> decimal.Decimal | None:
"""The floor value spells, an integer or a float from 1 to 10; None where it spells none. Not a string, nor a boolean, which Python counts as an integer, nor TOML's nan or inf."""
# An integer too large for a float makes math.isfinite raise, so only a float is checked.
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
return None
floor = decimal.Decimal(str(value))
return floor if 1 <= floor <= 10 else None
def language_fault(value: object) -> str | None:
"""Why value names no language; None where it does. Only words, since the name is quoted to every worker and reviewer as an instruction."""
named = isinstance(value, str) and re.fullmatch(r"[^\W\d_]+(?:[ -][^\W\d_]+)*", value)
return None if named else 'not a language\'s English name in words of letters, such as "Swedish" or "Brazilian Portuguese"'
def comment_fault(value: object) -> str | None:
"""Why value is no comment to post on a pull request; None where it is one."""
return None if isinstance(value, str) and value.strip() and "\n" not in value else 'not one line of text, such as "@coderabbitai review"'
# Each one-value setting, in the order `project-config` lists them.
SCALARS = (
Scalar(WAIT_FOR_APPROVAL, "wait_for_approval", switch, lambda on: "true" if on else "false"),
Scalar(MERGE, "merge", merger_read),
Scalar(TOOLING_ON_HOST, "tooling_on_host", switch, lambda on: "true" if on else "false"),
Scalar(READABILITY_FLOOR, "readability_floor", floor_read),
Scalar(PARALLEL_CHUNKS, "parallel_chunks", parallel_read),
Scalar(NOTIFIER, "notifier", notifier_read),
Scalar(LANGUAGE, "language", text_read(language_fault)),
Scalar(COMMIT_TITLE, "commit_title", text_read(templates.title_fault)),
Scalar(PULL_REQUEST_TITLE, "pull_request_title", text_read(templates.title_fault)),
Scalar(BRANCH, "branch", text_read(templates.branch_fault)),
Scalar(EPIC_BRANCH, "epic_branch", text_read(templates.epic_branch_fault)),
Scalar(REVIEW_REQUEST_COMMENT, "review_request_comment", text_read(comment_fault)),
Scalar(JIRA_FINDING_TYPE, "jira_finding_type", text_read(type_fault)),
)
OPTIONAL = tuple(sorted({CODING_CONVENTIONS, ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS)}))
def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
"""Whether path lies in one of places. Both sides are resolved, so a symlink can't lead a path out of the place it names."""
return any(path.resolve().is_relative_to(place.resolve()) for place in places)
def held(folder: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure | None:
"""The config in folder, read as its project's main checkout reads it; None where folder is not a config's folder under home."""
# Matched on resolved paths, as git names a folder, so a config's folder reached through a symlink is still found.
file = next((file for file in configs(home) if file.parent.resolve() == folder.resolve()), None)
if file is None:
return None
config = read(file, home)
return config if isinstance(config, Failure) else load(config[0], config[0], home)
def by_name(name: str, home: pathlib.Path) -> ProjectConfig | Failure | None:
"""The config of the project whose main checkout is a folder called name, though that folder may not exist yet, loaded as `held` does; None where no config names one. A config that cannot be read fails every name, since it may be the one asked for."""
files = []
for file in configs(home):
config = read(file, home)
if isinstance(config, Failure):
return config
if config[0].name == name:
files.append(file)
if len(files) > 1:
return Failure(f"{' and '.join(str(file) for file in files)} each name a checkout called {name}; only one config may")
return held(files[0].parent, home) if files else None
def configs(home: pathlib.Path) -> list[pathlib.Path]:
"""Every project's config file under home, in key order. do-epic's machine-wide config is not a project's."""
return sorted(file for file in (home / PROJECTS).glob(f"*/{CONFIG}") if file.parent.name != DO_EPIC)
def env_files(home: pathlib.Path) -> list[pathlib.Path]:
"""Every config's env-file, do-epic's included. Each is read without the checks load makes, so a config that fails them still keeps its credentials guarded. A config that can't be read doesn't name one."""
values = [parsed(file) for file in (*configs(home), home / PROJECTS / DO_EPIC / CONFIG)]
return [path for found in values if not isinstance(found, Failure) and (path := anywhere(found.get(ENV_FILE), home))]
def parsed(file: pathlib.Path) -> dict[str, object] | Failure:
"""The TOML values in file; a Failure where file can't be read or parsed."""
try:
return tomllib.loads(file.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as failure:
return Failure(f"cannot read {file}: {failure}")
def read(file: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, dict[str, object]] | Failure:
"""The checkout a config names, as an absolute path, and its other values."""
values = parsed(file)
if isinstance(values, Failure):
return values
checkout = anywhere(values.get("checkout"), home)
if checkout is None:
found = f"not {values['checkout']!r}" if "checkout" in values else "and is missing"
return Failure(f'{file}: `checkout` names the project\'s main checkout as a path that starts with / or ~/, such as "~/code/acme-billing", {found}')
return checkout, {name: value for name, value in values.items() if name != "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 conventions_of(value: object, top: pathlib.Path, folder: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, ...] | None:
"""The paths a `coding-conventions` value lists, or None where it is not a list of paths that `placed` can place."""
if not isinstance(value, list):
return None
paths = tuple(path for listed in value if (path := placed(listed, top, folder, home)))
return paths if len(paths) == len(value) else None
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