1"""The conformance clauses, the subject they judge, and the violations they name."""
3from __future__ import annotations
5import contextlib
6import io
7import re
8import tempfile
9import threading
10import tomllib
11from collections.abc import Callable
12from dataclasses import dataclass, replace
13from pathlib import Path
14from typing import TYPE_CHECKING, Any, cast
16from livery.workshop import _steps
17from livery.workshop._categories import (
18 BASE_TABLE,
19 CategoryError,
20 CategoryRule,
21 category_of,
22 category_rules,
23 matches,
24)
25from livery.workshop._composition import extension_set
26from livery.workshop._fragments import Fragment, package_fragment
27from livery.workshop._packages import Package
28from livery.workshop._phases import PhaseContext
29from livery.workshop._steps import (
30 BASE_EXTENSION,
31 WORKSPACE,
32 StepRecord,
33 answering,
34 installed_step,
35 steps_by_name,
36)
38if TYPE_CHECKING:
39 from livery.workshop._declaration import (
40 Additions,
41 Declaration,
42 DeclaredTemplate,
43 Reference,
44 )
47@dataclass(frozen=True)
48class Subject:
49 """What an extension registers, as the kit judges it.
51 The records are the ones the extension registered, and the kit reads
52 the registries as they stand, so the extension's registrations run
53 before the kit does.
55 Attributes:
56 extension: The extension's package, ``acme.extension``: where its
57 ``extension.toml`` sits, which the kit reads as the mount
58 does.
59 sets: The sets of extensions the kit probes, each as the list a
60 package writes for it, ``("acme",)``. The
61 category-table clause judges a package listing each, and the
62 gate's walk runs over a workspace holding one such package
63 for each.
64 steps: The steps the extension registers.
65 """
67 extension: str
68 sets: tuple[tuple[str, ...], ...] = ()
69 steps: tuple[StepRecord, ...] = ()
72@dataclass(frozen=True)
73class Violation:
74 """One way a subject breaks a clause.
76 Attributes:
77 clause: The clause's name.
78 where: What the violation concerns: a set, a step, a file or
79 a path.
80 reason: What is wrong, and what the gate does because of it.
81 """
83 clause: str
84 where: str
85 reason: str
87 def __str__(self) -> str:
88 """The violation as one line: clause, what it concerns, reason."""
89 return f"{self.clause}: {self.where}: {self.reason}"
92@dataclass(frozen=True)
93class Clause:
94 """One thing the gate relies on of what an extension registers.
96 Attributes:
97 name: The clause's name, ``fragment-owner``.
98 rule: The rule in one sentence.
99 judge: The violations a subject commits; empty when it conforms.
100 """
102 name: str
103 rule: str
104 judge: Callable[[Subject], list[Violation]]
107FRAGMENT_OWNER = "fragment-owner"
108CATEGORY_TABLE = "category-table"
109STEP_ORDER = "step-order"
110DECLARATION_VALIDATES = "declaration-validates"
111REFERENCES_REGISTER_NOTHING = "references-register-nothing"
112ENTRIES_NAME_DEFINED_TASKS = "entries-name-defined-tasks"
113CLAIMS_NAME_CATEGORIES = "claims-name-categories"
114WORDS_ARE_ANSWERABLE = "words-are-answerable"
115PLUGIN_IS_AN_ENTRY_POINT = "plugin-is-an-entry-point"
116REQUIREMENTS_IN_METADATA = "requirements-in-metadata"
117DECLARATION_DOCUMENTED = "declaration-documented"
118TEMPLATE_COMPOSES = "template-composes"
119FRAGMENT_DRIFT = "fragment-drift"
120WITHDRAWN_FILE = "withdrawn-file"
121WALK_ORDER = "walk-order"
122GATE_LINES = "gate-lines"
125# One owner for a per-package file.
128def _fragment_owners(extension: str, file: str) -> list[str]:
129 """The steps carrying a fragment for *file* that names *extension*, by name."""
130 return sorted(
131 name
132 for name, record in steps_by_name().items()
133 for fragment in record.fragments
134 if fragment.file == file and extension in fragment.extensions
135 )
138def _fragment_owner(subject: Subject) -> list[Violation]:
139 violations: list[Violation] = []
140 files = sorted(
141 {
142 fragment.file
143 for record in steps_by_name().values()
144 for fragment in record.fragments
145 if fragment.extensions
146 }
147 )
148 named = dict.fromkeys(
149 extension
150 for record in subject.steps
151 for fragment in record.fragments
152 for extension in fragment.extensions
153 )
154 for extension in named:
155 for file in files:
156 owners = _fragment_owners(extension, file)
157 if len(owners) > 1:
158 violations.append(
159 Violation(
160 FRAGMENT_OWNER,
161 f"extension {extension} {file}",
162 f"{' and '.join(owners)} both carry it for the extension's"
163 " packages; the render picks one by name, so one of them"
164 " yields",
165 )
166 )
167 return violations
170# The category tables.
173def _representative(pattern: str) -> str:
174 """A path *pattern* claims: each ``**`` one directory, each wildcard one letter."""
175 parts = [
176 "a" if segment == "**" else segment.replace("*", "x").replace("?", "y")
177 for segment in pattern.split("/")
178 ]
179 return "/".join(parts)
182def _documented_answer(held: tuple[str, ...], path: str) -> list[CategoryRule]:
183 """The rule the documented order picks for *path*, or the rules that tie.
185 *held* is the package's set of extensions. The most specific pattern
186 wins; between tables of equal specificity the nearer table wins, the
187 extension later in composition order first and the base's table
188 last; two rules of one table and one specificity claiming *path* for
189 different categories or extensions tie.
190 """
191 from livery.workshop._composition import order_or_sorted
192 from livery.workshop._extensions import installed_declaration
194 nearest_first = [
195 *reversed(order_or_sorted(held, installed_declaration)),
196 BASE_TABLE,
197 ]
198 matching = [rule for rule in category_rules(held) if matches(rule.pattern, path)]
199 if not matching:199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true
200 return []
201 top = max(rule.specificity for rule in matching)
202 best = [rule for rule in matching if rule.specificity == top]
203 depth = min(nearest_first.index(rule.table) for rule in best)
204 at_nearest = [rule for rule in best if nearest_first.index(rule.table) == depth]
205 first = at_nearest[0]
206 if any(
207 rule.category != first.category or rule.extension != first.extension
208 for rule in at_nearest
209 ):
210 return at_nearest
211 return [first]
214def _set_name(listed: tuple[str, ...]) -> str:
215 """*listed* as a violation names it: its names joined with ``+``, or none."""
216 return "+".join(listed) or "none"
219def _category_table(subject: Subject) -> list[Violation]:
220 violations: list[Violation] = []
221 for listed in subject.sets:
222 probe = Package(
223 Path("."),
224 "packages/probe",
225 "probe",
226 (),
227 extensions=listed,
228 )
229 held = extension_set(probe)
230 for rule in category_rules(held):
231 path = _representative(rule.pattern)
232 if not matches(rule.pattern, path):
233 continue
234 where = f"set {_set_name(listed)} {path}"
235 wanted = _documented_answer(held, path)
236 if len(wanted) > 1:
237 first, second = wanted[0], wanted[1]
238 violations.append(
239 Violation(
240 CATEGORY_TABLE,
241 where,
242 f"{first.pattern!r} ({first.category}, {first.extension}) and"
243 f" {second.pattern!r} ({second.category}, {second.extension})"
244 " claim it at one specificity in one table; one of them"
245 " names the file more closely",
246 )
247 )
248 continue
249 try:
250 found = category_of(probe, path)
251 except CategoryError as error:
252 violations.append(
253 Violation(
254 CATEGORY_TABLE,
255 where,
256 f"refuses ({error}) where the nearer table's rule decides",
257 )
258 )
259 continue
260 rule_wanted = wanted[0]
261 if (found.name, found.pattern, found.supplier) != (261 ↛ 266line 261 didn't jump to line 266 because the condition on line 261 was never true
262 rule_wanted.category,
263 rule_wanted.pattern,
264 rule_wanted.extension,
265 ):
266 violations.append(
267 Violation(
268 CATEGORY_TABLE,
269 where,
270 f"answers {found.name} from {found.pattern!r}"
271 f" ({found.supplier}); the most specific rule of the"
272 f" nearest table, {rule_wanted.table}, says"
273 f" {rule_wanted.category} from {rule_wanted.pattern!r}"
274 f" ({rule_wanted.extension})",
275 )
276 )
277 return list(dict.fromkeys(violations))
280# The order of an extension's steps.
283def _loop(start: str) -> list[str]:
284 """The steps from *start* back to itself through ``after``; empty without one."""
285 records = steps_by_name()
287 def visit(name: str, path: list[str], seen: set[str]) -> list[str]:
288 record = records.get(name)
289 if record is None:
290 return []
291 for earlier in record.after:
292 target = answering(earlier)
293 if target is None:
294 continue
295 if target == start:
296 return [*path, target]
297 if target in seen:297 ↛ 298line 297 didn't jump to line 298 because the condition on line 297 was never true
298 continue
299 seen.add(target)
300 found = visit(target, [*path, target], seen)
301 if found:
302 return found
303 return []
305 return visit(start, [], {start})
308def _step_order(subject: Subject) -> list[Violation]:
309 violations: list[Violation] = []
310 for record in subject.steps:
311 where = f"step {record.name}"
312 for earlier in record.after:
313 # A step an installed extension declares orders nothing
314 # while the workspace does not mount it, and the gate goes on.
315 if answering(earlier) is None and not installed_step(earlier):
316 violations.append(
317 Violation(
318 STEP_ORDER,
319 where,
320 f"runs after {earlier}, which no registered step"
321 " answers to and no installed extension declares;"
322 " the gate stops there",
323 )
324 )
325 loop = _loop(record.name)
326 if loop:
327 violations.append(
328 Violation(
329 STEP_ORDER,
330 where,
331 f"runs after itself through {', '.join(loop)}; the gate"
332 " would wait on it for ever",
333 )
334 )
335 return violations
338# An extension's declaration file.
341def _listed_name(subject: Subject) -> str:
342 """The name an installed distribution declares the subject's extension under.
344 The package's own without one. The kit reads the declaration under
345 it, as the mount does, so a phase the file declares is the
346 extension's own and never another extension's.
347 """
348 from livery.workshop._extensions import extension_package, installed_extensions
350 named = [
351 name
352 for name in installed_extensions()
353 if extension_package(name) == subject.extension
354 ]
355 return named[0] if named else subject.extension
358def _declaration_validates(subject: Subject) -> list[Violation]:
359 from livery.workshop._declaration import DeclarationError, declaration_file, read
361 if declaration_file(subject.extension) is None:
362 return []
363 try:
364 read(_listed_name(subject), subject.extension)
365 except DeclarationError as error:
366 return [
367 Violation(
368 DECLARATION_VALIDATES,
369 f"extension {subject.extension}",
370 f"{error}; the mount refuses the extension",
371 )
372 ]
373 return []
376def _declared_of(subject: Subject) -> tuple[Path, Declaration] | None:
377 """The subject's declaration file and what it declares; None without one.
379 None as well for a file that refuses, which ``declaration-validates``
380 names: the clauses that read a declaration judge only one that reads.
381 """
382 from livery.workshop._declaration import DeclarationError, declaration_file, read
384 path = declaration_file(subject.extension)
385 if path is None:
386 return None
387 try:
388 declared = read(_listed_name(subject), subject.extension)
389 except DeclarationError:
390 return None
391 return None if declared is None else (path, declared)
394def _additions_of(declared: Declaration) -> list[tuple[tuple[str, ...], Additions]]:
395 """The top level's additions, then each ``[for.<target>]``'s, with their keys."""
396 tables: list[tuple[tuple[str, ...], Additions]] = [((), declared.additions)]
397 tables += [(("for", target), table) for target, table in declared.targets.items()]
398 return tables
401def _references(declared: Declaration) -> list[tuple[str, Reference]]:
402 """Each reference *declared* names, with the key that names it."""
403 from livery.workshop._contract_keys import shown
404 from livery.workshop._declaration import Reference
406 found: list[tuple[str, object]] = []
407 for prefix, additions in _additions_of(declared):
408 for record in additions.steps:
409 where = shown((*prefix, "phases", record.phase, record.step))
410 found += [(f"{where}.main", record.run), (f"{where}.fix", record.fix)]
411 if record.inputs is not None:
412 found.append((f"{where}.inputs.widen", record.inputs.widen))
413 for item in additions.jobs:
414 where = shown((*prefix, "ci", "jobs", item.point, item.job.name))
415 found += [
416 (f"{where}.installs", item.job.installs),
417 (f"{where}.labels", item.job.labels),
418 (f"{where}.deploy", item.job.deploy),
419 ]
420 found += [
421 (f"{shown(('queries', name))}.combine", spec.combine)
422 for name, spec in declared.query_specs.items()
423 ]
424 found += [
425 (f"{shown(('fragments', output.target))}.render", output.render)
426 for output in declared.fragments
427 ]
428 registered = {id(record) for record in declared.additions.steps}
429 for phase, records in declared.phases.items():
430 for record in records:
431 if id(record) in registered:
432 continue # named above, with the additions
433 where = shown(("phases", phase, record.step))
434 found += [(f"{where}.main", record.run), (f"{where}.fix", record.fix)]
435 found += [
436 (shown(("queries", name)), reference)
437 for name, reference in declared.queries.items()
438 ]
439 found += [
440 (shown(("for", target, "queries", name)), reference)
441 for target, answered in declared.target_queries.items()
442 for name, reference in answered.items()
443 ]
444 return [(key, value) for key, value in found if isinstance(value, Reference)]
447def _registered_by_import(module: str) -> list[str]:
448 """What importing *module* registers, in a process of its own."""
449 import json
450 import os
451 import sys
453 import livery.footman as footman
455 path = os.pathsep.join(entry for entry in sys.path if entry)
456 result = footman.run(
457 [sys.executable, "-m", "livery.workshop.testing._import_probe", module],
458 env={**os.environ, "PYTHONPATH": path},
459 nofail=True,
460 )
461 if result.code != 0:461 ↛ 462line 461 didn't jump to line 462 because the condition on line 461 was never true
462 lines = result.stderr.strip().splitlines()
463 return [f"its import fails: {lines[-1] if lines else result.code}"]
464 return [str(line) for line in json.loads(result.stdout)]
467def _references_register_nothing(subject: Subject) -> list[Violation]:
468 found = _declared_of(subject)
469 if found is None:
470 return []
471 named: dict[str, list[str]] = {}
472 for key, reference in _references(found[1]):
473 named.setdefault(reference.module, []).append(key)
474 violations: list[Violation] = []
475 for module, keys in named.items():
476 added = _registered_by_import(module)
477 if added:
478 violations.append(
479 Violation(
480 REFERENCES_REGISTER_NOTHING,
481 f"{module}, named by {', '.join(keys)}",
482 f"importing it registers {'; '.join(added)}; the mount"
483 " registers what the declaration says, so a reference's"
484 " module only defines",
485 )
486 )
487 return violations
490def _entries_name_defined_tasks(subject: Subject) -> list[Violation]:
491 import difflib
493 from livery.workshop._contract_keys import shown
494 from livery.workshop._declaration import defined_tasks
496 found = _declared_of(subject)
497 if found is None:
498 return []
499 path, declared = found
500 jobs = [
501 (prefix, item)
502 for prefix, additions in _additions_of(declared)
503 for item in additions.jobs
504 ]
505 if not jobs:
506 return []
507 defined = sorted(defined_tasks(path.parent))
508 violations: list[Violation] = []
509 for prefix, item in jobs:
510 where = shown((*prefix, "ci", "jobs", item.point, item.job.name, "entries"))
511 for entry in item.entries:
512 if entry.task in defined:
513 continue
514 if not defined:
515 reason = f"names {entry.task}, and the extension defines no task"
516 else:
517 near = difflib.get_close_matches(entry.task, defined, n=1)
518 hint = f"; did you mean {near[0]!r}?" if near else ""
519 reason = (
520 f"names {entry.task}, which the extension does not define{hint}"
521 )
522 violations.append(Violation(ENTRIES_NAME_DEFINED_TASKS, where, reason))
523 return violations
526def _words_are_answerable(subject: Subject) -> list[Violation]:
527 from livery.workshop._contract_keys import shown
528 from livery.workshop._steps import PACKAGE, PACKAGES
529 from livery.workshop._words import PACKAGE_PLACEHOLDERS, PLACEHOLDERS
531 found = _declared_of(subject)
532 if found is None:
533 return []
534 violations: list[Violation] = []
535 for prefix, additions in _additions_of(found[1]):
536 for record in additions.steps:
537 words = record.words
538 if words is None:
539 continue
540 where = shown((*prefix, "phases", record.phase, record.step))
541 reasons: list[str] = []
542 if words.tool not in record.tools:
543 reasons.append(
544 f"runs {words.tool}, which its tools do not name"
545 f" ({', '.join(record.tools) or 'none'}); a step runs a tool"
546 " it requires"
547 )
548 reasons += [
549 f"names {{{name}}}, which neither the engine nor its matrix"
550 f" answers; the engine answers {', '.join(PLACEHOLDERS)}"
551 for name in words.unanswered()
552 ]
553 reasons += [
554 f"varies {key} in its matrix, which no word names; every call"
555 " would run the same words"
556 for key in words.unvaried()
557 ]
558 if record.scope != PACKAGE and record.narrowing != PACKAGES:
559 reasons += [
560 f"names {{{name}}}, which only a call that judges one package"
561 " answers, and the step judges the workspace whole"
562 for name in PACKAGE_PLACEHOLDERS
563 if name in words.placeholders()
564 ]
565 violations += [
566 Violation(WORDS_ARE_ANSWERABLE, where, reason) for reason in reasons
567 ]
568 return violations
571def _claims_name_categories(subject: Subject) -> list[Violation]:
572 import difflib
574 from livery.workshop._categories import known_categories
575 from livery.workshop._contract_keys import shown
577 known = sorted(known_categories())
578 violations: list[Violation] = []
579 targets: list[tuple[str, StepRecord]] = []
580 found = _declared_of(subject)
581 if found is not None:
582 for prefix, additions in _additions_of(found[1]):
583 for record in additions.steps:
584 where = shown(
585 (*prefix, "phases", record.phase, record.step, "inputs", "reads")
586 )
587 targets.append((where, record))
588 for record in subject.steps:
589 where = shown(("phases", record.phase, record.step, "inputs", "reads"))
590 if all(existing_record is not record for _, existing_record in targets):590 ↛ 588line 590 didn't jump to line 588 because the condition on line 590 was always true
591 targets.append((where, record))
592 for where, record in targets:
593 for claim in record.category_reads:
594 if claim.category not in known:
595 near = difflib.get_close_matches(claim.category, known, n=1)
596 hint = f"; did you mean {near[0]!r}?" if near else ""
597 violations.append(
598 Violation(
599 CLAIMS_NAME_CATEGORIES,
600 where,
601 f"names the category {claim.category!r}, which the"
602 f" workshop does not know{hint}; the step claims no"
603 " file of it",
604 )
605 )
606 violations += [
607 Violation(
608 CLAIMS_NAME_CATEGORIES,
609 where,
610 f"names the suffix {suffix!r}; a suffix starts with a dot,"
611 f" {'.' + suffix!r}",
612 )
613 for suffix in claim.suffixes
614 if not suffix.startswith(".")
615 ]
616 return violations
619def _plugin_is_an_entry_point(subject: Subject) -> list[Violation]:
620 from livery.footman import installed_entry_points
622 found = _declared_of(subject)
623 if found is None or not found[1].plugin:
624 return []
625 plugin = found[1].plugin
626 if plugin in {entry.name for entry in installed_entry_points("footman.tasks")}:
627 return []
628 return [
629 Violation(
630 PLUGIN_IS_AN_ENTRY_POINT,
631 f"extension {subject.extension}",
632 f"names the plugin {plugin!r}, which no installed distribution"
633 " declares in footman.tasks; the mount cannot mount its verbs",
634 )
635 ]
638#: A requirement's distribution, at the start of a ``Requires-Dist`` line.
639_REQUIRED = re.compile(r"\s*([A-Za-z0-9][A-Za-z0-9._-]*)")
640#: An extra a ``Requires-Dist`` line's marker names.
641_EXTRA = re.compile(r"""\bextra\s*==\s*["']([^"']+)["']""")
644def _required(lines: list[str]) -> list[tuple[str, frozenset[str]]]:
645 """Each ``Requires-Dist`` line as its distribution and the extras its marker names.
647 Both in the packaging standards' normal form. The core metadata
648 format is a published standard, so reading it pins no tool's text.
649 """
650 from livery.workshop._extensions import normal_name
652 found: list[tuple[str, frozenset[str]]] = []
653 for line in lines:
654 named = _REQUIRED.match(line)
655 if named is None:
656 continue
657 marker = line.partition(";")[2]
658 extras = frozenset(normal_name(extra) for extra in _EXTRA.findall(marker))
659 found.append((normal_name(named.group(1)), extras))
660 return found
663def _requirements_in_metadata(subject: Subject) -> list[Violation]:
664 from livery.workshop._extensions import (
665 distribution_of,
666 normal_name,
667 shipping_distribution,
668 ships_elsewhere,
669 )
671 found = _declared_of(subject)
672 if found is None:
673 return []
674 declared = found[1]
675 if not declared.requires:
676 return []
677 where = f"extension {subject.extension}"
678 dist = shipping_distribution(subject.extension)
679 if dist is None:
680 return [
681 Violation(
682 REQUIREMENTS_IN_METADATA,
683 where,
684 "declares requires, and no installed distribution declares it in"
685 " workshop.extensions, so its wheel's metadata cannot be read",
686 )
687 ]
688 required = _required(list(dist.requires or ()))
689 violations: list[Violation] = []
690 # A target the same wheel ships is held to it by being in it.
691 requires = [name for name in declared.requires if ships_elsewhere(name, dist.name)]
692 for target in requires:
693 wanted = normal_name(distribution_of(target))
694 if (wanted, frozenset()) not in required:
695 violations.append(
696 Violation(
697 REQUIREMENTS_IN_METADATA,
698 where,
699 f"requires {target}, and its wheel does not depend on"
700 f" {distribution_of(target)}; a requires range is a dependency"
701 " of the wheel, so the resolver holds the two to it",
702 )
703 )
704 return violations
707def _declaration_documented(subject: Subject) -> list[Violation]:
708 """Each item the subject's declaration names without its doc line, one each.
710 Read from the file as it is written, so a doc missing beside another
711 refusal is named too; a file that does not parse names nothing here,
712 since ``declaration-validates`` names it. The verbs are the tasks
713 the sources beside the file define, read when ``[extension]`` names
714 a plugin.
715 """
716 from livery.workshop._contract_keys import shown
717 from livery.workshop._declaration import (
718 DeclarationError,
719 _step_tables, # pyright: ignore[reportPrivateUsage]
720 contract_keys,
721 declaration_file,
722 task_docs,
723 )
725 path = declaration_file(subject.extension)
726 if path is None:
727 return []
728 try:
729 data = tomllib.loads(path.read_text("utf-8"))
730 except tomllib.TOMLDecodeError:
731 return []
732 where = f"extension {subject.extension}"
733 reasons: list[str] = []
734 identity = _table(data.get("extension"))
735 if not _documented(identity.get("description")):
736 reasons.append(
737 "declares no [extension] description; the agent's guidance and the"
738 " site say what the extension does from it"
739 )
740 if identity.get("plugin"):
741 reasons += [
742 f"defines the verb {task} with no docstring; its help, the agent's"
743 " guidance and the site show the verb by the docstring's first line"
744 for task, doc in sorted(task_docs(path.parent).items())
745 if not doc
746 ]
747 try:
748 keys = contract_keys(subject.extension)
749 except DeclarationError:
750 keys = ()
751 reasons += [
752 f"declares the {item.contract} contract key {item.path} with no doc; the"
753 " editor, the agent's guidance and the site show a key by its doc"
754 for item in keys
755 if not item.doc
756 ]
757 reasons += [
758 f"declares the template {name} with no doc; fm new.package.{name}, the"
759 " agent's guidance and the site show a template by its doc"
760 for name, table in _table(data.get("templates")).items()
761 if not _documented(_table(table).get("doc"))
762 ]
763 reasons += [
764 f"declares the option {option} of the template {name} with no doc;"
765 f" fm new.package.{name}'s help and completion, the agent's guidance and"
766 " the site show an option by its doc"
767 for name, table in _table(data.get("templates")).items()
768 for option, spec in _table(_table(table).get("options")).items()
769 if not _documented(_table(spec).get("doc"))
770 ]
771 reasons += [
772 f"declares the environment variable {name} with no doc; the agent's"
773 " guidance and the site show a variable by its doc, and the entry"
774 " script says it when the value replaces the environment's"
775 for name, table in _table(data.get("env")).items()
776 if not _documented(_table(table).get("doc"))
777 ]
778 for prefix, held in _step_holders(data):
779 for phase, table in _table(held.get("phases")).items():
780 for step, body in _step_tables(_table(table)).items():
781 reasons += [
782 f"declares the option {option} of"
783 f" [{shown((*prefix, 'phases', phase, step))}] with no doc;"
784 " the agent's guidance and the site show an option by its doc"
785 for option, spec in _table(body.get("options")).items()
786 if not _documented(_table(spec).get("doc"))
787 ]
788 return [Violation(DECLARATION_DOCUMENTED, where, reason) for reason in reasons]
791def _table(value: object) -> dict[str, Any]:
792 """*value* when it is a table, else an empty one."""
793 return cast("dict[str, Any]", value) if isinstance(value, dict) else {}
796def _documented(doc: object) -> bool:
797 """Whether *doc* is a doc line: text with something in it."""
798 return isinstance(doc, str) and bool(doc.strip())
801def _step_holders(
802 data: dict[str, Any],
803) -> list[tuple[tuple[str, ...], dict[str, Any]]]:
804 """The file's top level, then each ``[for.<target>]`` table, with its keys."""
805 found: list[tuple[tuple[str, ...], dict[str, Any]]] = [((), data)]
806 found += [
807 (("for", target), _table(table))
808 for target, table in _table(data.get("for")).items()
809 ]
810 return found
813# The templates an extension declares.
816def _own_templates(subject: Subject) -> dict[str, DeclaredTemplate]:
817 """The templates the subject's declaration file declares, by name.
819 The base's are those of its ``contract.toml``. A declaration file
820 that refuses declares none here: ``declaration-validates`` names
821 it. A template takes the name an installed distribution declares
822 its extension under, which a chain names, and the package's own
823 without one.
824 """
825 from livery.workshop._contract_keys import BASE_FILE
826 from livery.workshop._declaration import template_declarations, template_specs_of
828 if subject.extension == BASE_EXTENSION:
829 data = tomllib.loads(BASE_FILE.read_text("utf-8"))
830 return template_specs_of(data, BASE_FILE, extension=BASE_EXTENSION)
831 if _declared_of(subject) is None:
832 return {}
833 found = template_declarations(_listed_name(subject), subject.extension)
834 return {template.name: template for template in found}
837def _template_composes(subject: Subject) -> list[Violation]:
838 from livery.footman import Failed
839 from livery.workshop._composition import closure, implied
840 from livery.workshop._declaration import DeclarationError
841 from livery.workshop._extensions import GROUP, installed_declaration, why_inert
842 from livery.workshop._seeds import available_templates, chain_needs, template_chain
844 own = _own_templates(subject)
845 if not own:
846 return []
847 try:
848 known = {**available_templates(), **own}
849 except Failed as error:
850 return [
851 Violation(TEMPLATE_COMPOSES, f"extension {subject.extension}", str(error))
852 ]
853 violations: list[Violation] = []
854 for name, template in sorted(own.items()):
855 where = f"template {name}"
856 try:
857 members = closure(template.extensions, installed_declaration)
858 required = implied(members, installed_declaration)
859 for entry in dict.fromkeys(template.extensions):
860 if entry in required:860 ↛ 861line 860 didn't jump to line 861 because the condition on line 860 was never true
861 continue
862 if installed_declaration(entry) is None:
863 violations.append(
864 Violation(
865 TEMPLATE_COMPOSES,
866 where,
867 f"lists {entry}, which no installed distribution declares"
868 f" in {GROUP}, so nothing shows that it composes"
869 " something in a package",
870 )
871 )
872 elif why := why_inert(entry):
873 violations.append(
874 Violation(
875 TEMPLATE_COMPOSES,
876 where,
877 f"lists {entry}, which composes nothing in a package:"
878 f" {why}; fm new.package.{name} refuses to create a"
879 " package from it",
880 )
881 )
882 except DeclarationError as error:
883 violations.append(Violation(TEMPLATE_COMPOSES, where, str(error)))
884 continue
885 try:
886 chain = template_chain(name, known)
887 except Failed as error:
888 violations.append(Violation(TEMPLATE_COMPOSES, where, str(error)))
889 continue
890 violations += [
891 Violation(
892 TEMPLATE_COMPOSES,
893 where,
894 f"its chain needs {needed}, which the set of its extensions does not"
895 " hold; a package born from it holds that set alone, so no step that"
896 f" names {needed} judges it",
897 )
898 for needed in chain_needs(chain)
899 if needed not in members
900 ]
901 return violations
904# An extension's configuration files, through the workshop's own render.
907def _probe_answers() -> dict[str, Any]:
908 """The answers the kit renders an extension's fragments with.
910 A workspace of one python member and one native member, so a
911 fragment's loops over either run.
912 """
913 return {
914 "packages": [
915 {"dir": "probe", "name": "acme-probe", "dev": "acme-probe"},
916 {"dir": "native", "name": "acme-native"},
917 ],
918 "python_floor": "3.11",
919 "namespace_package": "acme",
920 "runner_prog": "fm",
921 "project_name": "acme",
922 }
925def _package_fragments(subject: Subject) -> list[tuple[StepRecord, Fragment]]:
926 """The subject's fragments for per-package files, each with its step."""
927 return [
928 (record, fragment)
929 for record in subject.steps
930 for fragment in record.fragments
931 if fragment.extensions
932 ]
935def _project_drift(subject: Subject) -> list[Violation]:
936 """The composed project files, judged where the subject carries fragments."""
937 from livery.workshop import _templates
939 owners = sorted(
940 record.name
941 for record in subject.steps
942 for fragment in record.fragments
943 if fragment.file == "pyproject.toml"
944 )
945 if not owners:
946 return []
947 try:
948 composed = _templates.compose_fragments(_probe_answers())
949 except Exception as error:
950 return [
951 Violation(FRAGMENT_DRIFT, "the project files", f"do not render: {error}")
952 ]
953 try:
954 tomllib.loads(composed.get("pyproject.toml", ""))
955 except tomllib.TOMLDecodeError as error:
956 return [
957 Violation(
958 FRAGMENT_DRIFT,
959 "pyproject.toml",
960 f"composed with the fragment of {', '.join(owners)}, it is not"
961 f" TOML: {error}",
962 )
963 ]
964 return []
967def _package_drift(fragment: Fragment) -> str:
968 """What goes wrong rendering *fragment* into a probe package; empty when nothing."""
969 from livery.workshop import _shipped_files
971 with tempfile.TemporaryDirectory() as scratch:
972 member = Path(scratch)
973 try:
974 _shipped_files.settle_package(member, fragment.extensions)
975 except Exception as error:
976 return f"does not render: {error}"
977 drift = _shipped_files.judge_package(member, fragment.extensions)
978 if drift:
979 return f"drifts from its own render: {drift[0]}"
980 copy = member / fragment.file
981 copy.write_bytes(b"# a hand edit\n" + copy.read_bytes())
982 if not _shipped_files.judge_package(member, fragment.extensions):
983 return "a hand edit of the rendered file is not named as drift"
984 return ""
987def _fragment_drift(subject: Subject) -> list[Violation]:
988 violations = _project_drift(subject)
989 for record, fragment in _package_fragments(subject):
990 problem = _package_drift(fragment)
991 if problem:
992 held = " or ".join(fragment.extensions)
993 where = f"step {record.name} {fragment.file} for {held}"
994 violations.append(Violation(FRAGMENT_DRIFT, where, problem))
995 return violations
998def _withdraw(record: StepRecord, fragment: Fragment, *, edited: bool) -> str:
999 """What goes wrong when *record* leaves a rendered file behind; empty when nothing.
1001 The render writes the file into a probe package, a person edits it
1002 or not, the step is withdrawn, and the render settles the file
1003 again. A file another step still renders for the same extensions is
1004 not withdrawn at all, and says nothing here.
1005 """
1006 from livery.workshop import _shipped_files
1008 if record.name not in steps_by_name():1008 ↛ 1009line 1008 didn't jump to line 1009 because the condition on line 1008 was never true
1009 return ""
1010 state = _steps.snapshot()
1011 with tempfile.TemporaryDirectory() as scratch:
1012 member = Path(scratch)
1013 copy = member / fragment.file
1014 try:
1015 _shipped_files.settle_package(member, fragment.extensions)
1016 if not copy.is_file():1016 ↛ 1017line 1016 didn't jump to line 1017 because the condition on line 1016 was never true
1017 return "" # it did not render: the drift clause names that
1018 if edited:
1019 copy.write_bytes(b"# a hand edit\n" + copy.read_bytes())
1020 _steps.unregister_step(record.name)
1021 if package_fragment(fragment.extensions, fragment.file) is not None:
1022 return ""
1023 _shipped_files.settle_package(member, fragment.extensions)
1024 except Exception:
1025 return "" # a render that fails is the drift clause's to name
1026 finally:
1027 _steps.restore(state)
1028 if edited and not copy.is_file():
1029 return (
1030 "an edited copy is removed once the step is withdrawn;"
1031 " contract 11 keeps it as a local override"
1032 )
1033 if not edited and copy.is_file():
1034 return (
1035 "an unedited copy stays once the step is withdrawn; contract 11"
1036 " removes it"
1037 )
1038 return ""
1041def _withdrawn_file(subject: Subject) -> list[Violation]:
1042 violations: list[Violation] = []
1043 for record, fragment in _package_fragments(subject):
1044 held = " or ".join(fragment.extensions)
1045 where = f"step {record.name} {fragment.file} for {held}"
1046 for edited in (False, True):
1047 problem = _withdraw(record, fragment, edited=edited)
1048 if problem:
1049 violations.append(Violation(WITHDRAWN_FILE, where, problem))
1050 return violations
1053# The gate's walk over an extension's steps.
1056class _Recorder:
1057 """The calls a probe walk makes into the subject's steps, in order."""
1059 def __init__(self) -> None:
1060 self.calls: list[tuple[str, str]] = []
1061 self._lock = threading.Lock()
1063 def body(self, mode: str, name: str) -> Callable[[PhaseContext], None]:
1064 def record(ctx: PhaseContext) -> None:
1065 del ctx
1066 with self._lock:
1067 self.calls.append((mode, name))
1069 return record
1072#: A file of the probe workspace no step's claims reach.
1073_UNCLAIMED = "probe/unclaimed.probe"
1076def _probe_packages(
1077 root: Path, sets: tuple[tuple[str, ...], ...]
1078) -> tuple[Package, ...]:
1079 """One probe package for each of *sets*, listing it.
1081 So a package step finds its own.
1082 """
1083 return tuple(
1084 Package(
1085 root / "packages" / f"probe-{index}",
1086 f"packages/probe-{index}",
1087 f"probe-{index}",
1088 (),
1089 extensions=listed,
1090 )
1091 for index, listed in enumerate(sets)
1092 )
1095def _probed(record: StepRecord, packages: tuple[Package, ...]) -> bool:
1096 """Whether the probe workspace gives *record* something to judge."""
1097 from livery.workshop._composition import extension_set
1099 if record.scope == WORKSPACE:1099 ↛ 1100line 1099 didn't jump to line 1100 because the condition on line 1099 was never true
1100 return True
1101 return any(
1102 set(record.extensions) & set(extension_set(package)) for package in packages
1103 )
1106def _walked(record: StepRecord) -> bool:
1107 """Whether the gate's walk judges *record*: registered, in a phase the gate runs.
1109 A phase nobody declares counts as one the gate runs, so the walk
1110 clauses still judge a step that names one.
1111 """
1112 from livery.workshop._phases import declared_phases
1114 spec = declared_phases().get(record.phase)
1115 return record.name in steps_by_name() and (spec is None or spec.gated)
1118def _probe_walk(
1119 subject: Subject, *, fix: bool, named: bool
1120) -> tuple[list[tuple[str, str]], str, tuple[Package, ...]]:
1121 """Walk the gate over a probe workspace with the subject's steps recording.
1123 The steps' bodies are replaced by recorders and their ``after``
1124 lists emptied, so no tool runs; the registry is restored after.
1125 *named* walks over one file no claim reaches; otherwise the walk
1126 is whole and the steps' claims are emptied, so every step reads
1127 whatever git lists around the probe. Returns the calls, the gate's
1128 output, and the probe's packages.
1129 """
1130 from livery.workshop import _quality
1132 recorder = _Recorder()
1133 names = [record.name for record in subject.steps if _walked(record)]
1134 state = _steps.snapshot()
1135 out = io.StringIO()
1136 try:
1137 for record in subject.steps:
1138 if record.name not in names:
1139 continue
1140 _steps.register_step(
1141 replace(
1142 record,
1143 run=recorder.body("run", record.name),
1144 fix=None
1145 if record.fix is None
1146 else recorder.body("fix", record.name),
1147 after=(),
1148 inputs=record.inputs if named else None,
1149 )
1150 )
1151 with tempfile.TemporaryDirectory() as scratch:
1152 root = Path(scratch)
1153 (root / _UNCLAIMED).parent.mkdir(parents=True)
1154 (root / _UNCLAIMED).write_text("probe\n")
1155 packages = _probe_packages(root, subject.sets)
1156 ctx = PhaseContext(
1157 root=root,
1158 packages=packages,
1159 fix=fix,
1160 files=(_UNCLAIMED,) if named else (),
1161 )
1162 with contextlib.redirect_stdout(out):
1163 _quality.walk(ctx, only=frozenset(names))
1164 finally:
1165 _steps.restore(state)
1166 return recorder.calls, out.getvalue(), packages
1169def _walk_order(subject: Subject) -> list[Violation]:
1170 calls, _out, packages = _probe_walk(subject, fix=True, named=False)
1171 first_judge = next(
1172 (index for index, (mode, _name) in enumerate(calls) if mode == "run"), None
1173 )
1174 violations: list[Violation] = []
1175 for record in subject.steps:
1176 if not _walked(record):
1177 continue
1178 where = f"step {record.name}"
1179 fixes = [
1180 index for index, call in enumerate(calls) if call == ("fix", record.name)
1181 ]
1182 judged = ("run", record.name) in calls
1183 if record.fix is not None:
1184 if not fixes:
1185 violations.append(
1186 Violation(WALK_ORDER, where, "never rewrote under --fix")
1187 )
1188 elif first_judge is not None and fixes[-1] > first_judge:
1189 violations.append(
1190 Violation(
1191 WALK_ORDER,
1192 where,
1193 "rewrote after a judge started; every fixer runs before any"
1194 " judge",
1195 )
1196 )
1197 if judged:
1198 violations.append(
1199 Violation(
1200 WALK_ORDER,
1201 where,
1202 "judged after it rewrote; a step that rewrote is not judged"
1203 " again",
1204 )
1205 )
1206 elif not judged and _probed(record, packages):
1207 violations.append(Violation(WALK_ORDER, where, "never judged under --fix"))
1208 return violations
1211def _gate_lines(subject: Subject) -> list[Violation]:
1212 from livery.workshop._extensions import extension_package
1214 calls, out, _packages = _probe_walk(subject, fix=False, named=True)
1215 lines = out.splitlines()
1216 violations: list[Violation] = []
1217 for record in subject.steps:
1218 if not _walked(record):
1219 continue
1220 where = f"step {record.name}"
1221 # A step names the extension by the name a contract lists, which
1222 # the installed entry point maps to the subject's package.
1223 if (
1224 subject.extension != BASE_EXTENSION
1225 and record.extension != subject.extension
1226 and extension_package(record.extension) != subject.extension
1227 ):
1228 violations.append(
1229 Violation(
1230 GATE_LINES,
1231 where,
1232 f"names {record.extension} as its extension; the gate says who"
1233 f" registered a step by it, and {subject.extension} registered"
1234 " this one",
1235 )
1236 )
1237 elif (
1238 record.extension != BASE_EXTENSION
1239 and f" {record.name}: registered by {record.extension}" not in lines
1240 ):
1241 violations.append(
1242 Violation(
1243 GATE_LINES,
1244 where,
1245 f"the gate does not name {record.extension} as the extension that"
1246 " registered it",
1247 )
1248 )
1249 said = f" {record.name}: no file it reads in the named files; not run"
1250 if said not in lines:
1251 violations.append(
1252 Violation(
1253 GATE_LINES,
1254 where,
1255 'not named when it had no file to read; the gate says "no file'
1256 ' it reads" and starts nothing',
1257 )
1258 )
1259 if any(name == record.name for _mode, name in calls):
1260 violations.append(
1261 Violation(GATE_LINES, where, "started with no file to read")
1262 )
1263 return violations
1266CLAUSES: tuple[Clause, ...] = (
1267 Clause(
1268 FRAGMENT_OWNER,
1269 "A per-package configuration file has one owner among the steps"
1270 " whose fragments name an extension.",
1271 _fragment_owner,
1272 ),
1273 Clause(
1274 CATEGORY_TABLE,
1275 "A path's category is the most specific rule's, the nearer table"
1276 " winning a tie between tables, the extension later in composition"
1277 " order first and the base's table last, and two rules of one table"
1278 " never tie.",
1279 _category_table,
1280 ),
1281 Clause(
1282 STEP_ORDER,
1283 "Every step a step runs after is registered or declared by an"
1284 " installed extension, and following the steps it runs after never"
1285 " leads back to it.",
1286 _step_order,
1287 ),
1288 Clause(
1289 DECLARATION_VALIDATES,
1290 "An extension's extension.toml holds only the keys the workshop declares,"
1291 " each of its type, and every reference in it names a function its"
1292 " module defines.",
1293 _declaration_validates,
1294 ),
1295 Clause(
1296 REFERENCES_REGISTER_NOTHING,
1297 "Importing a module a declaration's reference names registers nothing:"
1298 " the declaration says what the extension adds, and the mount"
1299 " registers it.",
1300 _references_register_nothing,
1301 ),
1302 Clause(
1303 ENTRIES_NAME_DEFINED_TASKS,
1304 "Every task a CI job's entries name is one the extension defines, read"
1305 " from its sources: a group and a task decorated in it.",
1306 _entries_name_defined_tasks,
1307 ),
1308 Clause(
1309 CLAIMS_NAME_CATEGORIES,
1310 "Every category a step's claims name is one the workshop knows, and"
1311 " every suffix starts with a dot.",
1312 _claims_name_categories,
1313 ),
1314 Clause(
1315 WORDS_ARE_ANSWERABLE,
1316 "A step in words runs a tool it requires, every placeholder its words"
1317 " name is one the engine or its matrix answers, every matrix key is"
1318 " named in its words, and a package's placeholder sits in a step that"
1319 " judges one package at a time.",
1320 _words_are_answerable,
1321 ),
1322 Clause(
1323 PLUGIN_IS_AN_ENTRY_POINT,
1324 "The plugin an extension.toml names is a footman.tasks entry point an"
1325 " installed distribution declares.",
1326 _plugin_is_an_entry_point,
1327 ),
1328 Clause(
1329 REQUIREMENTS_IN_METADATA,
1330 "Every extension an extension.toml requires is a dependency of its wheel.",
1331 _requirements_in_metadata,
1332 ),
1333 Clause(
1334 DECLARATION_DOCUMENTED,
1335 "An extension's extension.toml carries an [extension] description, and"
1336 " every verb its plugin defines, every contract key, template,"
1337 " template option, step option and environment variable it declares"
1338 " carries its doc line.",
1339 _declaration_documented,
1340 ),
1341 Clause(
1342 TEMPLATE_COMPOSES,
1343 "Every extension a template lists composes something in a package,"
1344 " unless another it lists requires it, and the set of the template's"
1345 " list holds every extension its chain needs.",
1346 _template_composes,
1347 ),
1348 Clause(
1349 FRAGMENT_DRIFT,
1350 "A step's fragments render, the composed pyproject.toml parses, and a"
1351 " per-package file matches its render until a person edits it, when"
1352 " the drift gate names it.",
1353 _fragment_drift,
1354 ),
1355 Clause(
1356 WITHDRAWN_FILE,
1357 "A per-package file whose step is withdrawn, and which no other step"
1358 " renders for the package's extensions, is removed when unedited and kept"
1359 " when edited.",
1360 _withdrawn_file,
1361 ),
1362 Clause(
1363 WALK_ORDER,
1364 "Under --fix every step of a phase the gate runs that has a fix mode"
1365 " rewrites before any judge starts and is not judged again, and every"
1366 " other step of such a phase is judged.",
1367 _walk_order,
1368 ),
1369 Clause(
1370 GATE_LINES,
1371 "Every step of a phase the gate runs names the extension that registered"
1372 " it, by the name a workspace lists it under, which the gate prints, and a"
1373 " step with no file to read is named and never started.",
1374 _gate_lines,
1375 ),
1376)
1377"""Every clause, in the order the kit judges them."""
1380def judge(subject: Subject) -> list[Violation]:
1381 """Every violation *subject* commits, clause by clause; empty when it conforms."""
1382 return [violation for clause in CLAUSES for violation in clause.judge(subject)]
1385def builtin_subject() -> Subject:
1386 """The workshop's own steps as a subject, for its own suite.
1388 Its sets are the empty one, whose package the base's table answers
1389 for alone, and, for each installed extension that composes
1390 something in a package
1391 ([livery.workshop._extensions.composes_per_package][]), the set of
1392 that extension alone.
1393 """
1394 from livery.workshop._extensions import composes_per_package, installed_extensions
1396 composing = [name for name in installed_extensions() if composes_per_package(name)]
1397 return Subject(
1398 BASE_EXTENSION,
1399 sets=((), *((name,) for name in composing)),
1400 steps=tuple(
1401 record
1402 for record in steps_by_name().values()
1403 if record.extension == BASE_EXTENSION
1404 ),
1405 )