1"""What each extension of the installed set provides, read from its declaration.
3The verbs fragment, ``verbs.extensions.md``, gives each extension of
4the installed set a block of its own, in composition order: what the
5extension does, its verbs with the first line of each one's help, the
6templates it declares, each with its verb ``fm new.package.<template>``
7and its creation options, the contract keys
8it reads and the step options a package may set, each with its doc and
9where it is written, the steps it declares off with the switch that
10turns each on, and the installed extensions it contributes to and
11those its root entry leaves out with ``without``. Every line is data
12the extension's ``extension.toml`` and its plugin's docstrings hold
13already, so a workspace that lists an extension needs no other step
14for a reader to learn it.
16`verbs_by_provider` reads the verbs from a composed task tree, `blocks`
17reads every block of a workspace, and `render_block` writes one for a
18reader.
19"""
21from __future__ import annotations
23import json
24from collections.abc import Mapping, Sequence
25from dataclasses import dataclass
26from pathlib import Path
27from typing import TYPE_CHECKING, Any, cast
29import livery.footman as footman
30from livery.workshop._prose import HUMAN, REPOSITORY
32if TYPE_CHECKING:
33 from livery.workshop._declaration import Declaration
34 from livery.workshop._steps import StepRecord
36#: The group of the templates' verbs, ``new.package.<template>``.
37TEMPLATE_VERBS = "new.package"
39#: The kinds of line a block holds, in the order a block lists them.
40VERB = "verb"
41TEMPLATE = "template"
42TEMPLATE_OPTION = "template option"
43KEY = "key"
44OPTION = "option"
45SWITCH = "switch"
48@dataclass(frozen=True)
49class Verb:
50 """One verb of a composed task tree.
52 Attributes:
53 address: How it is run: ``docs.build`` for ``fm docs.build``.
54 help: The first line of its help; empty for none.
55 """
57 address: str
58 help: str = ""
61@dataclass(frozen=True)
62class Item:
63 """One line of a block: a verb, a template, a key, an option or a switch.
65 Attributes:
66 kind: What it is: ``verb``, ``template``, ``template option``,
67 ``key``, ``option`` or ``switch``.
68 name: How a reader writes it: ``docs.build``, ``python-library``,
69 ``python-library --command``, ``[coverage] floor``,
70 ``[phases.test.pytest] parallel``.
71 where: The contract it is written in, ``root`` or ``package``;
72 empty for a verb, a template and a template's option.
73 detail: An option's type or choices and its default, ``bool,
74 default true``; empty for every other kind.
75 doc: Its doc line: a verb's first line of help, the doc of a
76 template, a key or an option, what a switch does.
77 """
79 kind: str
80 name: str
81 where: str = ""
82 detail: str = ""
83 doc: str = ""
86@dataclass(frozen=True)
87class Block:
88 """What one extension of the installed set provides.
90 Attributes:
91 extension: The name it is listed by.
92 description: What it does, from ``[extension] description``.
93 installed: Whether an installed distribution declares it; a
94 listed extension the sync has not installed yet is named
95 alone.
96 items: Its verbs, templates, keys, options and switches, in
97 that order.
98 contributes: The installed extensions its ``[for.<target>]``
99 tables apply to, in composition order.
100 leaves_out: The targets its root entry names in ``without``.
101 """
103 extension: str
104 description: str = ""
105 installed: bool = True
106 items: tuple[Item, ...] = ()
107 contributes: tuple[str, ...] = ()
108 leaves_out: tuple[str, ...] = ()
111def verbs_by_provider(tree: Mapping[str, Any]) -> dict[str, list[Verb]]:
112 """Every visible verb of *tree* by the plugin that mounted it.
114 *tree* is a composed task tree as ``--json --list`` reports it. A
115 group's ``default`` task is the group's own address, the way it is
116 run. A task the repository's own tasks file defines comes under the
117 empty provider. Hidden tasks and the tasks of hidden groups are left
118 out.
119 """
120 found: dict[str, list[Verb]] = {}
121 _collect(tree, "", REPOSITORY, found)
122 return found
125def _collect(
126 node: Mapping[str, Any],
127 prefix: str,
128 inherited: str,
129 found: dict[str, list[Verb]],
130) -> None:
131 """Every visible task under *node*, by provider, its address carrying *prefix*."""
132 tasks = node.get("tasks")
133 if isinstance(tasks, dict):
134 for name, task in cast("dict[str, Any]", tasks).items():
135 if not isinstance(task, dict):135 ↛ 136line 135 didn't jump to line 136 because the condition on line 135 was never true
136 continue
137 spec = cast("dict[str, Any]", task)
138 if spec.get("hidden") is True:
139 continue
140 provider = str(spec.get("mounted_from") or inherited)
141 address = prefix[:-1] if name == "default" and prefix else f"{prefix}{name}"
142 lines = str(spec.get("help") or "").strip().splitlines()
143 found.setdefault(provider, []).append(
144 Verb(address, lines[0] if lines else "")
145 )
146 groups = node.get("groups")
147 if isinstance(groups, dict):
148 for name, sub in cast("dict[str, Any]", groups).items():
149 if not isinstance(sub, dict):149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true
150 continue
151 group = cast("dict[str, Any]", sub)
152 if group.get("hidden") is True:
153 continue
154 provider = str(group.get("mounted_from") or inherited)
155 _collect(group, f"{prefix}{name}.", provider, found)
158def blocks(
159 root: Path, verbs: Mapping[str, Sequence[Verb]]
160) -> tuple[list[Block], dict[str, list[Verb]]]:
161 """Each extension of *root*'s installed set as a block, and the verbs left over.
163 *verbs* are the composed tree's, by provider
164 (`verbs_by_provider`). An extension's block takes every verb its
165 plugin mounts, and each verb the base generates for a step the
166 extension declares: ``lint.ruff`` is ruff's. The verb the base
167 generates for a template the extension declares,
168 ``new.package.python-library``, is its template's line. The verbs
169 no block takes come back by provider, the base's and those of the
170 plugins no extension of the set carries, a provider with none left
171 out. The blocks come in composition order.
172 """
173 from livery.workshop._extensions import (
174 SELF,
175 installed_declaration,
176 installed_set,
177 left_out,
178 resolved_targets,
179 )
181 names = installed_set(root)
182 targets = resolved_targets(root)
183 off = left_out(root)
184 declared = {name: installed_declaration(name) for name in names}
185 steps = {
186 name: _active_steps(found, targets.get(name, ()))
187 for name, found in declared.items()
188 if found is not None
189 }
190 owners = _step_owners(steps)
191 templated = {
192 f"{TEMPLATE_VERBS}.{template}"
193 for found in declared.values()
194 if found is not None
195 for template in found.templates
196 }
197 rest = {provider: list(found) for provider, found in verbs.items()}
198 taken: dict[str, list[Verb]] = {}
199 kept: list[Verb] = []
200 for verb in rest.get(SELF, []):
201 if verb.address in templated:
202 continue
203 owner = owners.get(verb.address)
204 if owner is None:
205 kept.append(verb)
206 else:
207 taken.setdefault(owner, []).append(verb)
208 if SELF in rest:
209 rest[SELF] = kept
210 found_blocks: list[Block] = []
211 for name in names:
212 found = declared[name]
213 contributes = tuple(
214 target for target in targets.get(name, ()) if target != name
215 )
216 leaves = off.get(name, ())
217 if found is None:
218 found_blocks.append(
219 Block(name, "", False, (), contributes=contributes, leaves_out=leaves)
220 )
221 continue
222 own = [*taken.get(name, ())]
223 if found.plugin:
224 own += rest.pop(found.plugin, [])
225 items = [
226 Item(VERB, verb.address, doc=verb.help)
227 for verb in sorted(own, key=lambda verb: verb.address)
228 ]
229 items += _items(found, steps[name])
230 found_blocks.append(
231 Block(
232 name,
233 found.description,
234 True,
235 tuple(items),
236 contributes=contributes,
237 leaves_out=leaves,
238 )
239 )
240 return found_blocks, {provider: found for provider, found in rest.items() if found}
243def _active_steps(found: Declaration, targets: Sequence[str]) -> tuple[StepRecord, ...]:
244 """The steps *found* declares at the top level and in its tables for *targets*."""
245 records = [record for held in found.phases.values() for record in held]
246 for target in targets:
247 additions = found.targets.get(target)
248 if additions is not None:248 ↛ 246line 248 didn't jump to line 246 because the condition on line 248 was always true
249 records += additions.steps
250 return tuple(records)
253def _step_owners(steps: Mapping[str, Sequence[StepRecord]]) -> dict[str, str]:
254 """Each step address to the extension that declares it.
256 The first in composition order, unless a later one's step replaces
257 the step at that address, ``<owner>:<phase>.<step>`` in its
258 ``replaces``.
259 """
260 owners: dict[str, str] = {}
261 for name, records in steps.items():
262 for record in records:
263 replaces = any(
264 ref.partition(":")[2] == record.name for ref, _why in record.replaces
265 )
266 if replaces or record.name not in owners:266 ↛ 262line 266 didn't jump to line 262 because the condition on line 266 was always true
267 owners[record.name] = name
268 return owners
271def _items(found: Declaration, steps: Sequence[StepRecord]) -> list[Item]:
272 """*found*'s templates with their options, keys, step options and switches."""
273 from livery.workshop._declaration import contract_keys
275 items: list[Item] = []
276 for template in found.templates.values():
277 items.append(Item(TEMPLATE, template.name, doc=template.doc))
278 items += [
279 Item(
280 TEMPLATE_OPTION,
281 f"{template.name} --{option.name}",
282 detail=_answers(option.choices, option.type, option.default),
283 doc=option.doc,
284 )
285 for option in template.options
286 ]
287 items += [
288 Item(KEY, _key_name(key.path), key.contract, doc=key.doc)
289 for key in contract_keys(found.package)
290 ]
291 for record in steps:
292 items += [
293 Item(
294 OPTION,
295 f"[phases.{record.phase}.{record.step}] {option.name}",
296 "package",
297 f"{option.kind}, default {json.dumps(option.default)}",
298 option.doc,
299 )
300 for option in record.options
301 ]
302 items += [
303 Item(
304 SWITCH,
305 f"[phases.{record.phase}.{record.step}] enabled = true",
306 "root",
307 doc="turns on the step, which the extension declares off",
308 )
309 for record in steps
310 if not record.enabled
311 ]
312 return items
315def _key_name(path: str) -> str:
316 """A contract key's dotted *path* as a reader finds it: ``[coverage] floor``."""
317 table, _, rest = path.partition(".")
318 return f"[{table}] {rest}" if rest else f"[{table}]"
321def render_block(block: Block, audience: str | None) -> list[str]:
322 """*block*'s markdown lines for *audience*, ending in an empty line.
324 A heading naming the extension and its description, then one line
325 per item: a list for the agent, a table for a reader of the site.
326 The extensions it contributes to and those its root entry leaves out
327 close it.
328 """
329 prog = footman.prog()
330 lines = [f"## {block.extension}", ""]
331 if not block.installed:
332 lines += [
333 f"No installed distribution declares it yet; `{prog} sync` installs it.",
334 "",
335 ]
336 elif block.description:
337 lines += [block.description, ""]
338 if audience == HUMAN:
339 if block.items:
340 lines += ["| item | kind | what it does |", "| --- | --- | --- |"]
341 lines += [
342 f"| `{_written(item, prog)}` | {_cell(_kind(item))}"
343 f" | {_cell(item.doc)} |"
344 for item in block.items
345 ]
346 lines.append("")
347 if block.contributes:
348 lines += [f"Contributes to {_spoken(block.contributes)}.", ""]
349 if block.leaves_out:
350 lines += [
351 f"Its root entry leaves out {_spoken(block.leaves_out)} with"
352 " `without`.",
353 "",
354 ]
355 return lines
356 listed = [f"- {_agent_line(item, prog)}" for item in block.items]
357 if block.contributes:
358 listed.append(f"- contributes to {', '.join(block.contributes)}")
359 if block.leaves_out:
360 listed.append(
361 f"- leaves out {', '.join(block.leaves_out)}, named in `without` in"
362 " its root entry"
363 )
364 return [*lines, *listed, ""] if listed else lines
367def _written(item: Item, prog: str) -> str:
368 """How a reader writes *item*: a verb, a template's or its option's, as run."""
369 if item.kind == VERB:
370 return f"{prog} {item.name}"
371 if item.kind == TEMPLATE:
372 return f"{prog} {TEMPLATE_VERBS}.{item.name} <name>"
373 if item.kind == TEMPLATE_OPTION:
374 return f"{prog} {TEMPLATE_VERBS}.{item.name}"
375 return item.name
378def _answers(choices: Sequence[str], kind: str, default: object) -> str:
379 """What a template's option answers: its choices or its type, and its default."""
380 takes = f"one of {'|'.join(choices)}" if choices else kind
381 if default is None:
382 return f"{takes}, required"
383 return f"{takes}, default {json.dumps(default)}"
386def _agent_line(item: Item, prog: str) -> str:
387 """*item* as one line of the agent's list, without its bullet."""
388 doc = f": {item.doc}" if item.doc else ""
389 if item.kind == VERB:
390 return f"`{prog} {item.name}`{doc}"
391 if item.kind == TEMPLATE:
392 return f"template `{item.name}`, `{_written(item, prog)}`{doc}"
393 if item.kind == TEMPLATE_OPTION:
394 template, _, option = item.name.partition(" ")
395 return (
396 f"option `{option}` of `{prog} {TEMPLATE_VERBS}.{template}`,"
397 f" {item.detail}{doc}"
398 )
399 where = "the root contract" if item.where == "root" else "a package contract"
400 detail = f", {item.detail}" if item.detail else ""
401 return f"`{item.name}` in {where}{detail}{doc}"
404def _kind(item: Item) -> str:
405 """*item*'s kind as a table cell for a reader of the site."""
406 if item.kind in (VERB, TEMPLATE):
407 return item.kind
408 if item.kind == TEMPLATE_OPTION:
409 return f"template option, {item.detail}"
410 if item.kind == OPTION:
411 return f"package step option, {item.detail}"
412 noun = "switch" if item.kind == SWITCH else "key"
413 return f"{item.where} contract {noun}"
416def _cell(text: str) -> str:
417 """*text* safe in a table cell: a pipe would end the cell."""
418 return text.replace("|", "\\|")
421def _spoken(names: Sequence[str]) -> str:
422 """*names* as a sentence lists them: ``a``, ``a and b``, ``a, b and c``."""
423 if len(names) < 2:423 ↛ 425line 423 didn't jump to line 425 because the condition on line 423 was always true
424 return "".join(names)
425 return f"{', '.join(names[:-1])} and {names[-1]}"