Files
claude-config/bin/do_epic/config.py
T

168 lines
13 KiB
Python

"""do-epic's machine-wide settings: `~/.claude-projects/do-epic/config.toml`, and `repo-rule.md` beside it.
One pair per machine, the same for every epic (docs/decisions.md → `do-epic: drives one Jira epic …`). The config is TOML:
jira-url = "https://acme.atlassian.net"
env-file = "~/.secrets/acme-jira.env"
repoless-model = "claude-opus-5-5"
clone-folder = "~/code"
language = "Swedish"
[label-repos]
twu-4 = "tenant-web-ui-4"
- `jira-url` is the Jira site's address: https, a host, and no path.
- `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of `~/.claude-projects` and outside the clone folder, which hold git checkouts. `~/.claude-projects/<key>.env` is fine.
- `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`.
- `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out.
- `language` is the default language of Jira text, by its English name. English where left out.
- `jira-finish-transition` and `jira-finish-status` name the workflow transition that moves a finished chunk's issue and closes a finished epic, such as "Mark as done", and the status it leads to, such as "Done". A project's config names a plan item's the same way. Set both or neither; without them do-epic moves no issue to done and closes no epic.
- `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks. A status Jira counts as done always does both, listed or not.
- `jira-automation-moves-issues = true` says the team's own automation moves an issue when its pull request merges. do-epic then moves only the issue of a chunk without a repo, which has no pull request, and waits for the automation to move each other. It needs `jira-unblocking-statuses`, which then names the status the automation gives an issue whose pull request merged. false where left out.
- `jira-finding-type` names the Jira issue type do-epic files a finding as, and `jira-review-type` the one it files a repo's release review as, such as `"Feature"` and `"Chore"`, for a Jira project that has no Task type. Task where left out. do-epic doesn't file anything where the project lacks the type, and says which types it has.
- `sub-task-summary` shapes the summary of each sub-task do-epic files for an issue that changes several repos, such as `"{label}: {Summary}"`. `{label}` is the team's label for the repo, else the repo's name, and `{Summary}` is the issue's summary with a capital first letter. It must hold `{Summary}`. Where left out, a summary is `[<repo>] <the issue's summary>`.
- `[label-repos]` has one line for each label of the team's own that names a repo: the label, then that repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. A team whose label is the repo's name maps the name to itself. Where several lines name one repo, do-epic writes the label of the first.
- `repo-rule.md` is prose that says how to tell an item's repo, and mustn't be blank."""
import dataclasses
import pathlib
import re
import string
import types
from project_config.settings import anywhere, CONFIG, DEFAULT_ISSUE_TYPE, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINDING_TYPE, JIRA_FINISH, JIRA_REVIEW_TYPE, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE, type_fault
from failure import Failure
from do_epic.backend.protocol import LABEL
from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME, REVIEW_LABEL
from text_files.markdown_text import listed
from model_routing.ladder_file import read_ladder, SHIPPED
from do_epic.split import SPLIT_LABEL
REPO_RULE = "repo-rule.md"
# Three readers, seated as the human who writes this config, picked these spellings from four candidates each, 3-0: `jira-url` over `site`, `clone-folder` over `repos-folder` (which reads as the folder of repos that already exist) and `repoless-model` over `no-repo-model`. `env-file` and `language` keep the names a project's config gives them.
JIRA_URL = "jira-url"
REPOLESS_MODEL = "repoless-model"
CLONE_FOLDER = "clone-folder"
SETTINGS = (JIRA_URL, ENV_FILE, REPOLESS_MODEL)
# Three readers, seated as those who write and read this config, picked `label-repos` from four candidates, over `repo-aliases`, `repo-labels` and `team-labels`, 2-1. All three readers would misread `repo-labels` as mapping a repo to its label.
LABEL_REPOS = "label-repos"
# Three readers, seated as those who write and read this config, picked `jira-unblocking-statuses` from four candidates, 3-0, and `jira-automation-moves-issues` 2-1. `jira-unblock-statuses` reads as statuses do-epic moves an issue to, and `jira-finish-issues = false` as closing no epic either.
UNBLOCKING_STATUSES = "jira-unblocking-statuses"
AUTOMATION_MOVES = "jira-automation-moves-issues"
SUB_TASK_SUMMARY = "sub-task-summary"
ISSUE_TYPES = (JIRA_FINDING_TYPE, JIRA_REVIEW_TYPE)
OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH, UNBLOCKING_STATUSES, AUTOMATION_MOVES, LABEL_REPOS, SUB_TASK_SUMMARY, *ISSUE_TYPES)
LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTIONAL, 'and')}."
@dataclasses.dataclass(frozen=True)
class DoEpicConfig:
"""folder is `~/.claude-projects/do-epic`; repo_rule is `repo-rule.md`'s text."""
folder: pathlib.Path
jira_url: str
env_file: pathlib.Path
clone_folder: pathlib.Path
language: str
repoless_model: str
repo_rule: str
# How a finished epic closes; None where the config doesn't say.
finish: Finish | None = None
# The LABEL_REPOS table; empty where the config has none.
label_repos: LabelRepos = types.MappingProxyType({})
# The UNBLOCKING_STATUSES list; empty where the config has none.
unblocking: tuple[str, ...] = ()
automation_moves: bool = False
# The SUB_TASK_SUMMARY template; None where the config has none.
sub_task_summary: str | None = None
finding_type: str = DEFAULT_ISSUE_TYPE
review_type: str = DEFAULT_ISSUE_TYPE
def label_repo_faults(table: object) -> list[str]:
"""What is wrong with the LABEL_REPOS table: each entry whose key isn't a team's label, or whose value isn't a repo's name."""
if not isinstance(table, dict):
return [f"`{LABEL_REPOS}` is {table!r}, not a table of labels, such as `twu-4 = \"tenant-web-ui-4\"` under `[{LABEL_REPOS}]`"]
return [
*(f"`{LABEL_REPOS}` maps {label!r}, a label do-epic gives a meaning of its own" for label in table if of_label(label, {}) is not None or label in (REVIEW_LABEL, SPLIT_LABEL)),
*(f"`{label}` stands below `[{LABEL_REPOS}]`, so it is read as a label; move it above the table" for label in table if label in (*SETTINGS, *OPTIONAL)),
*(f"`{LABEL_REPOS}` maps {label!r}, which is no Jira label: a label holds no white space" for label in table if not LABEL.fullmatch(label)),
*(f"`{LABEL_REPOS}` maps {label!r} to {repo!r}, not a repo's name in letters, digits, dots, hyphens and underscores" for label, repo in table.items() if not (isinstance(repo, str) and REPO_NAME.fullmatch(repo))),
]
def summary_template_faults(template: object) -> list[str]:
"""What is wrong with the SUB_TASK_SUMMARY template: a value that isn't one line, that Python can't read as a template, a field other than `{label}` and `{Summary}`, a format after a field's name, or no `{Summary}`."""
example = "`\"{label}: {Summary}\"`"
if not isinstance(template, str) or "\n" in template:
return [f"`{SUB_TASK_SUMMARY}` is {template!r}, not one line of text such as {example}"]
try:
fields = [(name, spec, conversion) for _, name, spec, conversion in string.Formatter().parse(template) if name is not None]
except ValueError as failure:
return [f"`{SUB_TASK_SUMMARY}` is {template!r}, which Python can't read as a template ({failure}); write a brace that is plain text as {{{{ or }}}}"]
names = [name for name, _, _ in fields]
return [
*(f"`{SUB_TASK_SUMMARY}` names {{{name}}}, and only {{label}} and {{Summary}} are known" for name in dict.fromkeys(names) if name not in ("label", "Summary")),
*(f"`{SUB_TASK_SUMMARY}` writes {{{name}{'!' + conversion if conversion else ''}{':' + spec if spec else ''}}} with something after the name; write {{{name}}} alone" for name, spec, conversion in fields if (spec or conversion) and name in ("label", "Summary")),
*([f"`{SUB_TASK_SUMMARY}` lacks {{Summary}}, so no sub-task's summary would say what changes in it, such as {example}"] if "Summary" not in names else []),
]
def workflow_faults(values: dict[str, object]) -> list[str]:
"""What is wrong with the UNBLOCKING_STATUSES list and the AUTOMATION_MOVES switch in values."""
statuses, moves = values.get(UNBLOCKING_STATUSES, ["Done"]), values.get(AUTOMATION_MOVES, False)
return [
*([f"`{UNBLOCKING_STATUSES}` is {statuses!r}, not a list of the status names Jira shows, such as [\"Release Ready\"]"] if not (isinstance(statuses, list) and statuses and all(name_of(status) for status in statuses)) else []),
*([f"`{AUTOMATION_MOVES}` is {moves!r}, not true or false"] if not isinstance(moves, bool) else []),
# With no status listed, an issue whose pull request merged would read as open, and its chunk would start again.
*([f"`{AUTOMATION_MOVES}` is set, so `{UNBLOCKING_STATUSES}` must name the status the automation gives an issue whose pull request merged"] if moves is True and UNBLOCKING_STATUSES not in values else []),
]
def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure:
"""The settings and the repo rule under home; a Failure naming the file it can't read, else each missing or misspelt setting it finds, so that do-epic refuses to start."""
folder = home / PROJECTS / DO_EPIC
values = parsed(folder / CONFIG)
if isinstance(values, Failure):
return Failure(f"{values.reason}. {LISTED}")
ladder = read_ladder(ladder_file)
if isinstance(ladder, Failure):
return ladder
models = sorted({rung.model for rung in ladder.rungs})
rule: str | Failure
try:
rule = (folder / REPO_RULE).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure:
rule = Failure(f"cannot read {folder / REPO_RULE}: {failure}")
config_folders = [path for path in (home / PROJECTS).iterdir() if path.is_dir()]
clone_folder = anywhere(values.get(CLONE_FOLDER, "~/code"), home)
env_file = anywhere(values.get(ENV_FILE), home)
language = values.get(LANGUAGE, "English")
url, model = values.get(JIRA_URL), values.get(REPOLESS_MODEL)
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"`{JIRA_URL}` is {url!r}, not a site's https address without a path, such as \"https://acme.atlassian.net\""] if JIRA_URL in values and not (isinstance(url, str) and re.fullmatch(SITE, url)) else []),
*([f"`{CLONE_FOLDER}` is {values[CLONE_FOLDER]!r}, not a path that starts with / or ~/"] if clone_folder is None else []),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not a path that starts with / or ~/"] if ENV_FILE in values and env_file is None else []),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, inside a folder of ~/{PROJECTS} or the clone folder, which hold git checkouts"] if env_file and lies_in(env_file, *config_folders, *([clone_folder] if clone_folder else [])) else []),
*([f"`{LANGUAGE}` is {language!r}, {fault}"] if LANGUAGE in values and (fault := language_fault(language)) else []),
*([f"`{REPOLESS_MODEL}` is {model!r}, not a model on the routing ladder: {', '.join(models)}"] if REPOLESS_MODEL in values and model not in models else []),
*finish_faults(values),
*workflow_faults(values),
*(summary_template_faults(values[SUB_TASK_SUMMARY]) if SUB_TASK_SUMMARY in values else []),
*label_repo_faults(values.get(LABEL_REPOS, {})),
*(f"`{name}` is {values[name]!r}, {fault}" for name, example in zip(ISSUE_TYPES, ("Feature", "Chore")) if name in values and (fault := type_fault(values[name], example))),
*([rule.reason] if isinstance(rule, Failure) else [f"`{REPO_RULE}` is blank"] if not rule.strip() else []),
]
if faults:
return Failure(f"{folder}: {'; '.join(faults)}. {LISTED}")
# Without a fault, each value above is present and of the type asserted here.
assert clone_folder and env_file and isinstance(url, str) and isinstance(model, str) and isinstance(language, str) and isinstance(rule, str)
labels = values.get(LABEL_REPOS, {})
assert isinstance(labels, dict)
statuses = values.get(UNBLOCKING_STATUSES, [])
assert isinstance(statuses, list)
template = values.get(SUB_TASK_SUMMARY)
assert template is None or isinstance(template, str)
finding_type, review_type = (str(values.get(name, DEFAULT_ISSUE_TYPE)) for name in ISSUE_TYPES)
return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values), types.MappingProxyType(labels), tuple(statuses), values.get(AUTOMATION_MOVES) is True, template, finding_type, review_type)