Coverage for packages/workshop/src/livery/workshop/_packages.py: 97%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_words.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_versions.py, packages/workshop/tests/test_workshop_verify.py, packages/workshop/tests/test_workshop_variables.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_traces.py, packages/workshop/tests/test_workshop_test_reads.py, packages/workshop/tests/test_workshop_test_guard.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync_locked.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_sweep.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_store_tasks.py, packages/workshop/tests/test_workshop_steps.py, packages/workshop/tests/test_workshop_speed.py, packages/workshop/tests/test_workshop_skip_marks.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_shard.py, packages/workshop/tests/test_workshop_seeds.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_schema.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runtime_language.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_run.py, packages/workshop/tests/test_workshop_root_attribution.py, packages/workshop/tests/test_workshop_repair.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.py, packages/workshop/tests/test_workshop_release_point.py, packages/workshop/tests/test_workshop_release_fresh.py, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_release.py, packages/workshop/tests/test_workshop_registries.py, packages/workshop/tests/test_workshop_regions.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_provenance.py, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_parts.py, packages/workshop/tests/test_workshop_proved_flaky.py, packages/workshop/tests/test_workshop_proved_escapes.py, packages/workshop/tests/test_workshop_proved_decide.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_proof_pins.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_plugin_tools.py, packages/workshop/tests/test_workshop_phases.py, packages/workshop/tests/test_workshop_phase_verbs.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_package_level_fragments.py, packages/workshop/tests/test_workshop_package.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_metrics.py, packages/workshop/tests/test_workshop_lifecycle.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_invoke.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_influence.py, packages/workshop/tests/test_workshop_identity.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_graph.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_fragments.py, packages/workshop/tests/test_workshop_footprint.py, packages/workshop/tests/test_workshop_fold.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extensions.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_e2e_rows.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_due.py, packages/workshop/tests/test_workshop_doctor_unlisted.py, packages/workshop/tests/test_workshop_doctor.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/workshop/tests/test_workshop_declaration.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_cpp_kind.py, packages/workshop/tests/test_workshop_contributed_jobs.py, packages/workshop/tests/test_workshop_contract_file.py, packages/workshop/tests/test_workshop_contract.py, packages/workshop/tests/test_workshop_conformance.py, packages/workshop/tests/test_workshop_composition.py, packages/workshop/tests/test_workshop_commit.py, packages/workshop/tests/test_workshop_claims.py, packages/workshop/tests/test_workshop_ci_context.py, packages/workshop/tests/test_workshop_categories.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/workshop/tests/test_workshop_balance.py, packages/workshop/tests/test_workshop_affected_legs.py, packages/workshop/tests/test_tools_restub.py, packages/workshop/tests/test_tools_materialise.py, packages/workshop/tests/test_kind_tools.py, packages/extensions/ty/tests/test_ty.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/python/tests/test_speed.py, packages/extensions/python/tests/test_runner_terminal.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_quality.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/python/tests/test_python_layering.py, packages/extensions/python/tests/test_private_reaches.py, packages/extensions/python/tests/test_plugin_reaches.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/python/tests/test_examples.py, packages/extensions/python/tests/test_declared_imports.py, packages/extensions/python/tests/test_credential_traces.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/pytest/tests/test_pytest_observer_runner.py, packages/extensions/pytest/tests/test_pytest_observer.py, packages/extensions/pytest/tests/test_pytest_coverage.py, packages/extensions/pytest/tests/test_pytest_c6_selection.py, packages/extensions/pytest/tests/test_pytest_c5_repeats.py, packages/extensions/pytest/tests/test_pytest_c4_reads.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/pyrefly/tests/test_pyrefly.py, packages/extensions/nanobind/tests/test_nanobind_kind.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mypy/tests/test_mypy.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_refs.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_docstrings.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_digests.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_taskref.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_llms.py, packages/extensions/docs/tests/test_influence.py, packages/extensions/docs/tests/test_groups.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/docs/tests/test_docs_site.py, packages/extensions/docs/tests/test_docs_phase.py, packages/extensions/docs/tests/test_docs_contract.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/docs/tests/test_doc_steps.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_parts.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/coverage/tests/test_coverage_union_pins.py, packages/extensions/coverage/tests/test_coverage_store.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/coverage/tests/test_coverage_pages.py, packages/extensions/coverage/tests/test_coverage_accept.py, packages/extensions/coverage/tests/test_coverage.py, packages/extensions/coverage/tests/test_affected_legs.py, packages/extensions/conan/tests/test_layering.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/conan/tests/test_cross_kind.py, packages/extensions/conan/tests/test_conan_releases.py, packages/extensions/conan/tests/test_conan_publish.py, packages/extensions/conan/tests/test_conan_kind.py, packages/extensions/cmake/tests/test_measured_run.py, packages/extensions/cmake/tests/test_cpp_kind.py, packages/extensions/cmake/tests/test_coverage_parts.py, packages/extensions/cmake/tests/test_cmake.py, packages/extensions/clang-tidy/tests/test_clang_tidy.py, packages/extensions/clang-format/tests/test_clang_format.py, packages/extensions/changelog/tests/test_changelog.py, packages/extensions/basedpyright/tests/test_basedpyright.py, packages/extensions/agents/tests/test_agents.py ran.

1"""The package contracts: discovery, the graph, and the layering lint.
2
3A directory under ``packages/`` is a package exactly when it carries a
4``workshop.toml``; everything the workshop knows about a package it
5learns there. livery.workshop.verify_workspace is the layering lint:
6contracts present, declared edges agreeing with the native manifests
7in both directions, the graph acyclic, the base importing no
8extension, and each reference to a sibling declared as an edge.
9
10`holds_runtime_language` says whether a package holds the language the
11workshop runs on, `RUNTIME_LANGUAGE`; a member that does is a
12distribution of that language, and discovery requires its
13``pyproject.toml``.
14"""
15
16from __future__ import annotations
17
18import re
19from collections.abc import Callable, Iterable, Mapping
20from dataclasses import dataclass, field
21from itertools import takewhile
22from pathlib import Path, PurePosixPath
23
24from livery.workshop._contract import load_contract
25from livery.workshop._pytest_common import (
26 PACKAGES_DIR as PACKAGES_DIR,
27)
28from livery.workshop._pytest_common import (
29 is_group as is_group,
30)
31from livery.workshop._pytest_common import (
32 package_directories as package_directories,
33)
34
35
36@dataclass(frozen=True)
37class Edge:
38 """One declared dependency edge of a package.
39
40 Attributes:
41 path: The dependency's identity: its directory path from the
42 workspace root, as the tags spell it.
43 kind: ``runtime``, ``build``, ``test``, or ``tool``. It
44 decides one thing: a ``runtime`` or ``build`` edge must
45 appear in the native manifest with a constraint carrying
46 its floor, and the other two have no native home. Every
47 edge counts everywhere else, whatever its kind: the
48 acyclicity check, the dependents' closure the gate
49 narrows by, the order the release wave publishes in, and
50 the floor bump.
51 floor: The released version the native manifest must require.
52 """
53
54 path: str
55 kind: str
56 floor: str
57
58
59@dataclass(frozen=True)
60class Package:
61 """One package, as its contract declares it.
62
63 Attributes:
64 directory: The package directory.
65 path: The identity path from the workspace root
66 (``packages/forge``, or ``packages/extensions/widgets`` for a
67 package in a group directory).
68 name: The distribution name (``livery-forge``).
69 depends: The declared edges, in contract order.
70 step_options: The options the package sets on its steps, by
71 the table that sets them: ``phases.<phase>`` (every step of
72 the phase) and ``phases.<phase>.<step>`` (one step), each to
73 its ``(option, value)`` pairs; the step registry validates
74 them against what the steps they reach declare.
75 categories: The package's own reassignments of its paths
76 among the categories, ``[categories] vendored =
77 ["docs/assets/vendor/**"]``: a fact about the package in
78 the narrow shape a coverage floor has, on the category
79 axis alone, winning over every extension's rule.
80 publish: Whether the release train uploads the package's
81 artifact to its registry. ``[release] publish = false``
82 keeps an internal tool versioned, tagged and built by the
83 train and never uploaded; the default is true.
84 extensions: The extensions the package lists, in its contract's
85 order: its canonical list, which the extensions it requires
86 complete into its set.
87 test_reads: Extra paths or globs declared under ``[tests] reads``
88 that tests read outside the Python observer hook (package-relative,
89 or workspace-root-relative when prefixed with ``//``).
90 test_selection: Per-item test selection mode declared under
91 ``[tests] selection`` (``off``, ``shadow``, or ``on``; default
92 ``shadow``).
93 """
94
95 directory: Path
96 path: str
97 name: str
98 depends: tuple[Edge, ...]
99 publish: bool = True
100 categories: tuple[tuple[str, tuple[str, ...]], ...] = ()
101 # Left out of the hash, so a package stays a set member and a key:
102 # an option's value may be a list, a strs option's, or anything a
103 # contract holds before the registry judges it.
104 step_options: tuple[tuple[str, tuple[tuple[str, object], ...]], ...] = field(
105 default=(), hash=False
106 )
107 extensions: tuple[str, ...] = ()
108 test_reads: tuple[str, ...] = ()
109 test_selection: str = "shadow"
110
111 @property
112 def member(self) -> str:
113 """The package's path under ``packages/``: ``forge``, ``extensions/widgets``.
114
115 It names the package in a release tag
116 (``packages/<member>/v<version>``) and everywhere else a
117 package is addressed by its place rather than its
118 distribution name.
119 """
120 return self.path.removeprefix(f"{PACKAGES_DIR}/")
121
122 @property
123 def root(self) -> Path:
124 """The root of the workspace the package is a member of.
125
126 The package's directory with its path's parts taken off, read
127 from the two fields alone, without touching the disk: the root
128 is two directories above ``packages/forge``, three above
129 ``packages/extensions/widgets``, and one above the workspace's
130 own tests ([livery.workshop.workspace_suite][]). A package whose
131 path is ``.`` is at the root, so its directory is the root.
132
133 Raises:
134 ValueError: when the directory does not end with the path,
135 naming both.
136 """
137 parts = PurePosixPath(self.path).parts
138 if not parts:
139 return self.directory
140 if self.directory.parts[-len(parts) :] != parts:
141 raise ValueError(
142 f"{self.directory} does not end with the package's path"
143 f" {self.path}, so it names no workspace root: a package's"
144 " directory is its path under the root"
145 )
146 return self.directory.parents[len(parts) - 1]
147
148
149#: How git sees a directory under ``packages/`` that has no contract.
150RESIDUE = "residue"
151TRACKED = "tracked"
152UNTRACKED = "untracked"
153SECRET = "secret"
154UNKNOWN = "unknown"
155
156
157@dataclass(frozen=True)
158class Leftover:
159 """A directory under ``packages/`` with no ``workshop.toml``, as git sees it.
160
161 Git removes a package's tracked files when a checkout moves past
162 the package's removal and keeps the files it ignores (bytecode,
163 built wheels, coverage pages), so the directory stays behind
164 without its contract.
165
166 Attributes:
167 directory: The directory.
168 state: ``residue`` when git tracks nothing under it and every
169 file it holds is one git ignores, none of them a machine
170 secret: what a removed package leaves behind, which can go.
171 ``tracked`` when git tracks a file there: a package
172 missing its contract. ``untracked`` when it holds a file
173 git neither tracks nor ignores: work nobody committed yet.
174 ``secret`` when an ignored file is a machine secret, which
175 no checkout can restore. ``unknown`` when git could not
176 answer.
177 paths: The files that decide the state, relative to the root:
178 the ignored files of residue, else the tracked, untracked
179 or secret ones.
180 reason: git's own words, when it could not answer.
181 """
182
183 directory: Path
184 state: str
185 paths: tuple[str, ...] = ()
186 reason: str = ""
187
188
189def _ls_files(root: Path, relative: str, *args: str) -> tuple[tuple[str, ...], str]:
190 """The files ``git ls-files`` lists under *relative*; git's words if it fails."""
191 from livery import git
192
193 result = git.call(root, "ls-files", "-z", *args, "--", relative)
194 if result.code != 0:
195 said = (result.stderr or result.stdout).strip()
196 return (), said or f"git ls-files exited {result.code}"
197 return tuple(sorted(entry for entry in result.stdout.split("\0") if entry)), ""
198
199
200def leftover(root: Path, directory: Path) -> Leftover:
201 """How git sees *directory*, a directory under ``packages/`` with no contract."""
202 from livery.workshop._clean import protected_within
203
204 # A pathspec in posix form: git reads a backslash as an escape.
205 relative = directory.relative_to(root).as_posix()
206 tracked, failed = _ls_files(root, relative)
207 if failed:
208 return Leftover(directory, UNKNOWN, reason=failed)
209 if tracked:
210 return Leftover(directory, TRACKED, tracked)
211 untracked, failed = _ls_files(root, relative, "--others", "--exclude-standard")
212 if failed:212 ↛ 213line 212 didn't jump to line 213 because the condition on line 212 was never true
213 return Leftover(directory, UNKNOWN, reason=failed)
214 if untracked:
215 return Leftover(directory, UNTRACKED, untracked)
216 secrets = protected_within(root, relative)
217 if secrets:
218 return Leftover(directory, SECRET, secrets)
219 ignored, failed = _ls_files(
220 root, relative, "--others", "--ignored", "--exclude-standard"
221 )
222 if failed:222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true
223 return Leftover(directory, UNKNOWN, reason=failed)
224 return Leftover(directory, RESIDUE, ignored)
225
226
227def _no_contract(root: Path, directory: Path) -> str:
228 """Discovery's problem for *directory*, which has no contract.
229
230 The classification asks git, which costs a process or three, and
231 runs only here, on the way to a refusal.
232 """
233 member = directory.relative_to(root / PACKAGES_DIR).as_posix()
234 if leftover(root, directory).state != RESIDUE:
235 return f"{member}: no workshop.toml"
236 import livery.footman as footman
237
238 return (
239 f"{member}: no workshop.toml, and git tracks nothing under"
240 f" {PACKAGES_DIR}/{member}: it holds only ignored files, what a removed"
241 f" package leaves behind. `{footman.prog()} sync` removes the directory"
242 )
243
244
245_RELEASE_TAG = re.compile(rf"({PACKAGES_DIR}(?:/[^/]+)+)/v(\d+\.\d+\.\d+)")
246
247
248def release_tag(tag: str) -> tuple[str, str] | None:
249 """The package path and version a release *tag* names; None for another tag.
250
251 A release tag is ``packages/<member>/v<major>.<minor>.<patch>``, and
252 the member may sit in a group directory:
253 ``packages/extensions/widgets/v1.2.0`` names
254 ``("packages/extensions/widgets", "1.2.0")``. Every reader of
255 release tags parses them here, so a package at any depth under
256 ``packages/`` releases like any other.
257 """
258 match = _RELEASE_TAG.fullmatch(tag)
259 return (match.group(1), match.group(2)) if match else None
260
261
262def receipt_member(tag: str) -> str:
263 """The member a release receipt *tag* names, or ``""`` for another tag.
264
265 ``packages/extensions/widgets/v1.2.0`` names ``extensions/widgets``.
266 """
267 found = release_tag(tag)
268 return found[0].removeprefix(f"{PACKAGES_DIR}/") if found else ""
269
270
271def member_depth(root: Path, relative: Path) -> int:
272 """How many leading parts of *relative* name a package's directory.
273
274 2 for ``packages/forge/...``, 3 for ``packages/<group>/<name>/...``
275 in a group directory, 0 for a path outside ``packages/`` or one
276 that is the package directory itself or above it.
277 """
278 parts = relative.parts
279 if len(parts) <= 2 or parts[0] != PACKAGES_DIR:
280 return 0
281 group = root / PACKAGES_DIR / parts[1]
282 if group.is_dir() and is_group(group):
283 return 3 if len(parts) > 3 else 0
284 return 2
285
286
287def member_of(relative: str, members: Iterable[str]) -> str:
288 """The member of *members* whose directory holds *relative*, or ``""``.
289
290 *relative* is a posix path from the workspace root
291 (``packages/extensions/widgets/src/x.py``); *members* are package
292 members as [livery.workshop.Package][] names them
293 (``extensions/widgets``). The longest match wins.
294 """
295 found = ""
296 for member in members:
297 if relative.startswith(f"{PACKAGES_DIR}/{member}/") and len(member) > len(
298 found
299 ):
300 found = member
301 return found
302
303
304#: The workspace's own test directory, a unit of the gate like a
305#: package's suite. It holds the root's set. Its tests reach any
306#: package, so every run of a test step that judges them runs them, and
307#: a change under it affects that unit alone.
308WORKSPACE_TESTS = "tests"
309
310
311def workspace_suite(root: Path) -> Package | None:
312 """The workspace's own tests, the ``tests`` directory at its root, as a unit.
313
314 ``None`` when the workspace has none. The unit lists no extension
315 and holds the root's set. A test step whose extensions that set
316 holds runs it beside the members it judges
317 ([livery.workshop.scoped_suite][]). It is no member, so no package
318 step judges it, and the workspace's category table answers for its
319 files (`is_workspace_unit`).
320 """
321 directory = root / WORKSPACE_TESTS
322 if not directory.is_dir():
323 return None
324 return Package(
325 directory=directory,
326 path=WORKSPACE_TESTS,
327 name="workspace-tests",
328 depends=(),
329 )
330
331
332def is_workspace_unit(package: Package) -> bool:
333 """Whether *package* is the workspace's own unit rather than a member.
334
335 The workspace's tests (`workspace_suite`) are its unit, and a root
336 without them is its own unit, for the files under no package. A
337 member's path is under ``packages/``, and a unit's is not.
338 """
339 return not package.path.startswith(f"{PACKAGES_DIR}/")
340
341
342#: The extension of the language the workshop runs on. A member
343#: holding it is a distribution of that language: discovery requires its
344#: project file, and it joins the uv workspace the venv is made from.
345RUNTIME_LANGUAGE = "python"
346
347
348def holds_runtime_language(package: Package) -> bool:
349 """Say whether *package* holds the extension of the workshop's own language.
350
351 That extension is ``python``. A member holds it when it lists it,
352 or when an extension it lists requires it. The workspace's own
353 tests hold it when the root's set does. Discovery asks this of
354 every member, so a member that lists it is answered without
355 reading any extension's declaration.
356 """
357 if RUNTIME_LANGUAGE in package.extensions:
358 return True
359 from livery.workshop._composition import extension_set
360
361 return RUNTIME_LANGUAGE in extension_set(package)
362
363
364def package_paths(packages: tuple[Package, ...]) -> tuple[str, ...]:
365 """The src and tests directories the *packages* own, as they exist.
366
367 The workspace's own tests, a unit whose directory is the tests
368 themselves, contribute that directory.
369 """
370 paths = []
371 for package in packages:
372 if package.path == WORKSPACE_TESTS:
373 if package.directory.is_dir():373 ↛ 375line 373 didn't jump to line 375 because the condition on line 373 was always true
374 paths.append(package.path)
375 continue
376 for name in ("src", "tests"):
377 directory = package.directory / name
378 if directory.is_dir():
379 paths.append(f"{package.path}/{name}")
380 return tuple(paths)
381
382
383#: Valid values for ``[tests] selection`` in a package contract.
384TEST_SELECTION_MODES: tuple[str, ...] = ("off", "shadow", "on")
385
386
387def _validate_test_selection(member: str, value: object) -> str:
388 """Validate ``[tests] selection`` for *member*; defaults to ``shadow``."""
389 if value is None:
390 return "shadow"
391 if not isinstance(value, str) or value not in TEST_SELECTION_MODES:
392 allowed = ", ".join(TEST_SELECTION_MODES)
393 raise ValueError(
394 f"{member}: [tests] selection {value!r} must be one of {allowed}"
395 )
396 return value
397
398
399def _validate_test_reads(member: str, entries: object) -> tuple[str, ...]:
400 """Validate and normalize ``[tests] reads`` patterns for *member*."""
401 if entries is None:
402 return ()
403 if not isinstance(entries, list):
404 raise ValueError(
405 f"{member}: [tests] reads must be a list of relative path patterns"
406 )
407 cleaned: list[str] = []
408 for raw in entries:
409 if not isinstance(raw, str) or not raw.strip():
410 raise ValueError(
411 f"{member}: [tests] reads contains an empty or non-string pattern"
412 )
413 norm = raw.strip().replace("\\", "/")
414 body = norm[2:] if norm.startswith("//") else norm
415 if (
416 not body
417 or body.startswith("/")
418 or (len(body) >= 2 and body[1] == ":" and body[0].isalpha())
419 ):
420 raise ValueError(
421 f"{member}: [tests] reads pattern {raw!r} must be relative to the"
422 " package (or prefixed with // for workspace-root-relative)"
423 )
424 parts = PurePosixPath(body).parts
425 if ".." in parts:
426 raise ValueError(
427 f"{member}: [tests] reads pattern {raw!r} must not traverse with '..'"
428 )
429 cleaned.append(norm)
430 return tuple(cleaned)
431
432
433def discover_packages(root: Path) -> tuple[Package, ...]:
434 """Every package the workspace carries, by its contract, sorted by path.
435
436 Raises ValueError, with every finding listed, when a directory
437 under ``packages/`` lacks its contract, or holds the runtime's
438 language (`holds_runtime_language`) and lacks the
439 ``pyproject.toml`` a distribution of that language carries: a
440 half-present package is a wrong state, not a lesser one. A
441 directory holding only what a removed package left behind is
442 named as such, with the ``fm sync`` that removes it. A package
443 that lists no extension holds none, and needs no project file.
444 """
445 problems = []
446 packages = []
447 # A workspace born a moment ago has no members yet; zero packages
448 # is a legal answer, not a missing directory.
449 for directory in package_directories(root):
450 member = directory.relative_to(root / PACKAGES_DIR).as_posix()
451 contract_file = directory / "workshop.toml"
452 if not contract_file.is_file():
453 problems.append(_no_contract(root, directory))
454 continue
455 contract = load_contract(contract_file)
456 depends = tuple(
457 Edge(
458 path=str(edge.get("path", "")),
459 kind=str(edge.get("kind", "build")),
460 floor=str(edge.get("floor", "")),
461 )
462 for edge in contract.get("depends", [])
463 )
464 release = contract.get("release") or {}
465 # The contract's judge has held every table below to its shape.
466 reassigned = [
467 (str(category), tuple(patterns))
468 for category, patterns in contract.get("categories", {}).items()
469 ]
470 options: list[tuple[str, tuple[tuple[str, object], ...]]] = []
471 for phase, table in contract.get("phases", {}).items():
472 # Scalars are the phase's own options, for every step of
473 # the phase; a table is one step's.
474 own = tuple(
475 (str(key), value)
476 for key, value in table.items()
477 if not isinstance(value, dict)
478 )
479 if own or not table:
480 options.append((f"phases.{phase}", own))
481 options.extend(
482 (
483 f"phases.{phase}.{step}",
484 tuple((str(key), value) for key, value in nested.items()),
485 )
486 for step, nested in table.items()
487 if isinstance(nested, dict)
488 )
489 publish = bool(release.get("publish", True))
490 tests_table = contract.get("tests") or {}
491 test_reads = _validate_test_reads(member, tests_table.get("reads"))
492 test_selection = _validate_test_selection(member, tests_table.get("selection"))
493 package = Package(
494 directory=directory,
495 path=f"{PACKAGES_DIR}/{member}",
496 name=str(contract.get("name", "")),
497 depends=depends,
498 publish=publish,
499 categories=tuple(reassigned),
500 step_options=tuple(options),
501 extensions=tuple(str(name) for name in contract.get("extensions", ())),
502 test_reads=test_reads,
503 test_selection=test_selection,
504 )
505 if (
506 holds_runtime_language(package)
507 and not (directory / "pyproject.toml").is_file()
508 ):
509 problems.append(
510 f"{member}: holds {RUNTIME_LANGUAGE} and has no pyproject.toml"
511 )
512 continue
513 packages.append(package)
514 if problems:
515 raise ValueError(
516 "packages missing a file they need:\n " + "\n ".join(problems)
517 )
518 return tuple(packages)
519
520
521def verify_workspace(root: Path) -> tuple[Package, ...]:
522 """The layering lint: check every workspace invariant, or raise.
523
524 The graph's invariants ([livery.workshop._packages.verify_graph][]) and
525 the base's rules over every python source
526 ([livery.workshop._packages.import_problems][]) together, in one refusal.
527 Returns the discovered packages when everything holds. Raises
528 ValueError listing every violation verbatim otherwise:
529
530 - every ``build`` edge appears in the native manifest with a
531 constraint carrying its floor, and every workspace-internal
532 native dependency is a declared edge (agreement both ways);
533 - the dependency graph is acyclic, so dependencies only point
534 downward;
535 - the base imports no extension, and each reference a package's
536 sources make to a sibling is a declared edge.
537 """
538 packages = discover_packages(root)
539 problems = graph_problems(root, packages) + import_problems(root, packages)
540 if problems:
541 raise ValueError(
542 "the workspace breaks its layering:\n " + "\n ".join(problems)
543 )
544 return packages
545
546
547def verify_graph(root: Path) -> tuple[Package, ...]:
548 """The graph half of the layering lint: the contracts and the native manifests.
549
550 Each edge agrees with its native manifest, the graph is acyclic,
551 the extensions a contract lists close over what they require, each
552 contract's step options name what exists, and the root is no
553 package. What it reads is the contracts and the manifests, so a run
554 whose change touched none of them skips it. Returns the discovered
555 packages; raises ValueError listing every violation otherwise.
556 """
557 packages = discover_packages(root)
558 problems = graph_problems(root, packages)
559 if problems:559 ↛ 560line 559 didn't jump to line 560 because the condition on line 559 was never true
560 raise ValueError(
561 "the workspace breaks its layering:\n " + "\n ".join(problems)
562 )
563 return packages
564
565
566@dataclass(frozen=True)
567class RuleContext:
568 """What a rule of the layering phase judges: the workspace and its sources.
569
570 Attributes:
571 root: The workspace root.
572 packages: Every package the workspace carries.
573 files: The root-relative sources the run judges; None for every
574 one. A rule over the sources keeps to these, and a rule over
575 a package's references judges each package holding one
576 (`packages_in_scope`).
577 """
578
579 root: Path
580 packages: tuple[Package, ...]
581 files: frozenset[str] | None = None
582
583 def packages_in_scope(self) -> tuple[Package, ...]:
584 """The packages holding a source this run judges, every one without a scope."""
585 if self.files is None:
586 return self.packages
587 files = self.files
588 return tuple(
589 package
590 for package in self.packages
591 if any(path.startswith(f"{package.path}/") for path in files)
592 )
593
594 def sources(self) -> tuple[SourceReferences, ...]:
595 """What each source this run judges references, one record per source.
596
597 Read from the ``references`` answer of each package in scope,
598 in package order.
599 """
600 from livery.workshop import _lifecycle
601
602 return tuple(
603 source
604 for package in self.packages_in_scope()
605 for source in _lifecycle.references(package)
606 if self.files is None or source.path in self.files
607 )
608
609
610#: A rule's judge: the context, to the problems, empty when the rule
611#: holds.
612Judge = Callable[[RuleContext], list[str]]
613
614
615def import_problems(
616 root: Path, packages: tuple[Package, ...], files: frozenset[str] | None = None
617) -> list[str]:
618 """Every base rule's findings over the sources in scope, each by its step's name."""
619 return [
620 f"{step}: {line}"
621 for step in RULES
622 for line in rule_problems(step, root, packages, files)
623 ]
624
625
626def rule_problems(
627 step: str,
628 root: Path,
629 packages: tuple[Package, ...],
630 files: frozenset[str] | None = None,
631) -> list[str]:
632 """What the base's layering step *step* finds over the sources in scope.
633
634 *files* names the root-relative sources a narrowed run judges;
635 None judges every one. A rule over the sources judges the named
636 ones, and a rule over a package's references judges each package
637 holding one.
638 """
639 return RULES[step](RuleContext(root=root, packages=packages, files=files))
640
641
642def graph_problems(root: Path, packages: tuple[Package, ...]) -> list[str]:
643 """Every violation of the graph's invariants, verbatim; empty when they hold."""
644 from livery.workshop import _lifecycle
645 from livery.workshop._composition import extension_set
646
647 by_path = {package.path: package for package in packages}
648 names_by_path = {package.path: package.name for package in packages}
649 problems: list[str] = []
650
651 for package in packages:
652 # The set's answers say what the package declares natively:
653 # python's the pyproject's dependencies, conan's the recipe's
654 # references, combined.
655 native = _lifecycle.declared_requirements(package)
656 tested = _lifecycle.declared_test_requirements(package)
657 declared = {edge.path: edge for edge in package.depends}
658 for edge in package.depends:
659 if edge.path not in by_path:659 ↛ 660line 659 didn't jump to line 660 because the condition on line 659 was never true
660 problems.append(
661 f"{package.path}: declares an edge on {edge.path},"
662 " which is not a package here"
663 )
664 continue
665 if edge.kind == "test":
666 if tested is not None:
667 problems.extend(_test_problems(package, edge, by_path, tested))
668 continue
669 if edge.kind not in ("build", "runtime"):
670 continue # a tool edge has no native home
671 dep = by_path[edge.path]
672 constraint = native.get(dep.name)
673 if constraint is None:
674 # The sibling's set says which ecosystem's manifest the
675 # requirement belongs in: a writer takes its own alone.
676 held = ", ".join(extension_set(dep)) or "no extension"
677 problems.append(
678 f"{package.path}: the {edge.kind} edge on {edge.path} is not"
679 f" declared in the package's manifests ({dep.name} missing;"
680 f" {edge.path} holds {held})"
681 )
682 elif edge.floor and f">={edge.floor}" not in constraint:
683 problems.append(
684 f"{package.path}: the edge on {edge.path} floors at"
685 f" {edge.floor}, and the declared requirement says"
686 f" {dep.name}{constraint or ''}"
687 )
688 internal_names = set(names_by_path.values())
689 for name in native:
690 if name in internal_names and name != package.name:690 ↛ 689line 690 didn't jump to line 689 because the condition on line 690 was always true
691 dep_path = next(path for path, n in names_by_path.items() if n == name)
692 if dep_path not in declared:
693 problems.append(
694 f"{package.path}: depends on {name} natively, with no"
695 f" [[depends]] edge on {dep_path}"
696 )
697
698 problems.extend(_cycles(packages))
699 from livery.workshop._extensions import closure_problems
700
701 problems.extend(closure_problems(root))
702 from livery.workshop._steps import option_problems
703
704 problems.extend(option_problems(packages))
705 if (root / "src").is_dir():
706 problems.append(
707 "src/ at the workspace root is not a member: the root is never a"
708 " package, so nothing claims, formats, lints or tests it; a"
709 " package lives under packages/<name>/, one directory per"
710 " package, and a project shipping one package has one"
711 )
712 return problems
713
714
715@dataclass(frozen=True)
716class ReferencedName:
717 """One name a source references, and how the source makes the reference.
718
719 A record of [livery.workshop.SourceReferences][]: an extension that
720 answers the ``references`` query makes one for each name a source
721 references, once for each way the source makes the reference.
722
723 Attributes:
724 name: The dotted name, as the source spells it.
725 lazy: Whether only a function or a method body makes the
726 reference, so importing the source does not.
727 type_checking: Whether only a type checker makes it, so no run
728 of the source does.
729 optional: Whether the source handles the name being absent, so
730 it runs without it.
731 """
732
733 name: str
734 lazy: bool = False
735 type_checking: bool = False
736 optional: bool = False
737
738
739@dataclass(frozen=True)
740class SourceReferences:
741 """What one source references: one record of a package's ``references`` answer.
742
743 An extension that reads a language's sources answers the
744 ``references`` query with one record for each source file of the
745 package, and the layering steps resolve each name to the member
746 that owns it with [livery.workshop.neighbours][].
747
748 Attributes:
749 path: The source, relative to the workspace root, posix: a file
750 inside the package the answer is about.
751 module: The name other code references the source by; empty for
752 a source nothing references by name, such as a test.
753 references: Every name the source references, in source order,
754 once for each way the source makes the reference.
755 accounted: The names among them that the conventions of the
756 source's language account for, so they need no dependency
757 edge.
758 """
759
760 path: str
761 module: str = ""
762 references: tuple[ReferencedName, ...] = ()
763 accounted: tuple[str, ...] = ()
764
765
766@dataclass(frozen=True)
767class Neighbours:
768 """Who owns each name the workspace's members reference each other by.
769
770 [livery.workshop.neighbours][] makes it from the members; a rule
771 over the sources asks it which member a referenced name belongs to.
772
773 Attributes:
774 owners: Each module root a member ships, to the member's path.
775 Each member's extensions answer its roots
776 ([livery.workshop.MODULE_ROOTS][]), so a reference resolves
777 the same way whichever extension made it.
778 by_path: Every member by its path.
779 """
780
781 owners: Mapping[str, str]
782 by_path: Mapping[str, Package]
783
784 def owner_of(self, reference: str) -> str:
785 """The package path owning *reference*, longest prefix winning.
786
787 Empty when no package owns it: a third-party name, or the
788 standard library. Longest prefix, because three distributions
789 share the ``livery.toolroom`` namespace and the shortest match
790 would attribute two of them to the third.
791 """
792 best = ""
793 for prefix in self.owners:
794 matches = reference == prefix or reference.startswith(prefix + ".")
795 if matches and len(prefix) > len(best):
796 best = prefix
797 return self.owners[best] if best else ""
798
799
800def neighbours(packages: tuple[Package, ...]) -> Neighbours:
801 """Map each module root *packages* ship to the member that ships it.
802
803 Each member's set answers the roots it ships
804 ([livery.workshop.MODULE_ROOTS][]), so the map names no language.
805 A member whose set answers no root owns no name.
806
807 Args:
808 packages: The workspace's members, as
809 [livery.workshop.discover_packages][] reads them.
810
811 Returns:
812 The roots by owner and the members by path.
813 """
814 from livery.workshop import _lifecycle
815
816 owners: dict[str, str] = {}
817 for package in packages:
818 for prefix in _lifecycle.module_roots(package):
819 owners[prefix] = package.path
820 return Neighbours(owners=owners, by_path={p.path: p for p in packages})
821
822
823def _reachable(by_path: Mapping[str, Package], start: str) -> set[str]:
824 """Every package path *start* reaches through declared edges."""
825 seen: set[str] = set()
826 queue = [edge.path for edge in by_path[start].depends]
827 while queue:
828 path = queue.pop()
829 if path in seen or path not in by_path:
830 continue
831 seen.add(path)
832 queue += [edge.path for edge in by_path[path].depends]
833 return seen
834
835
836def inherited_floor(by_path: Mapping[str, Package], reach: set[str], dep: str) -> str:
837 """The floor *dep* already carries within *reach*; the highest declared.
838
839 Every declaration inside the reachable set is installed, so the
840 highest of them is what resolution already guarantees. That floor
841 claims nothing new: raising one is a decision, and the release's
842 lowest-direct leg is what proves a floor is high enough.
843 """
844 floors = [
845 edge.floor
846 for path in reach
847 for edge in by_path[path].depends
848 if edge.path == dep and edge.floor
849 ]
850 if not floors:850 ↛ 851line 850 didn't jump to line 851 because the condition on line 850 was never true
851 return "0.0.0"
852 return max(floors, key=_version_key)
853
854
855def _version_key(version: str) -> tuple[int, ...]:
856 """*version* as comparable integers; a non-numeric part sorts as zero."""
857 parts = []
858 for piece in version.split("."):
859 digits = "".join(takewhile(str.isdigit, piece))
860 parts.append(int(digits) if digits else 0)
861 return tuple(parts)
862
863
864def undeclared_references(
865 packages: tuple[Package, ...], *, only: set[str] | None = None
866) -> tuple[list[tuple[Package, Package, str, str]], list[tuple[Package, Package]]]:
867 """Sibling references no edge declares, split by what the graph reaches.
868
869 Each package's ``references`` answer says what its sources
870 reference and which names its language's conventions account for;
871 this resolves each other name to the sibling that owns it and walks
872 the graph over them. A reference the declared graph already
873 reaches can be declared without changing what the graph reaches,
874 so it can introduce neither a cycle nor an upward edge, and it is
875 returned as (package, dependency, edge kind, floor). Anything else
876 is a new dependency for a person to decide, returned as
877 (package, dependency). *only* judges the packages at those paths
878 and walks the graph over every one.
879 """
880 around = neighbours(packages)
881 writable: list[tuple[Package, Package, str, str]] = []
882 refused: list[tuple[Package, Package]] = []
883 for package in packages:
884 if only is not None and package.path not in only:
885 continue
886 referenced = _referenced_siblings(package, around)
887 declared = {edge.path for edge in package.depends}
888 reach = _reachable(around.by_path, package.path)
889 for dep_path, kind in sorted(referenced.items()):
890 if dep_path in declared or dep_path not in around.by_path:
891 continue
892 dependency = around.by_path[dep_path]
893 if dep_path in reach:
894 floor = inherited_floor(around.by_path, reach, dep_path)
895 writable.append((package, dependency, kind, floor))
896 else:
897 refused.append((package, dependency))
898 return writable, refused
899
900
901def _referenced_siblings(package: Package, around: Neighbours) -> dict[str, str]:
902 """The siblings *package*'s sources reference that nothing accounts for.
903
904 Each to the edge it asks for. A name the source runs without, or
905 one the conventions of its language account for, needs no edge. A
906 sibling that only test and test-support files reference, by their
907 category, asks for a ``test`` edge; one that any other file
908 references asks for a ``runtime`` edge.
909 """
910 from livery.workshop import _lifecycle
911 from livery.workshop._categories import TEST, TEST_SUPPORT, category_of
912
913 found: dict[str, str] = {}
914 for source in _lifecycle.references(package):
915 accounted = set(source.accounted)
916 owners = {
917 owner
918 for reference in source.references
919 if not reference.optional and reference.name not in accounted
920 if (owner := around.owner_of(reference.name)) not in ("", package.path)
921 }
922 if not owners:
923 continue
924 relative = source.path.removeprefix(f"{package.path}/")
925 tested = category_of(package, relative).name in (TEST, TEST_SUPPORT)
926 for owner in owners:
927 if found.get(owner) != "runtime":927 ↛ 926line 927 didn't jump to line 926 because the condition on line 927 was always true
928 found[owner] = "test" if tested else "runtime"
929 return found
930
931
932def declare_edge(
933 package: Package, dependency: Package, *, kind: str, floor: str
934) -> list[str]:
935 """Declare *package*'s *kind* edge on *dependency* at *floor*; the files written.
936
937 For a build, runtime or test edge, the writers of the package's set
938 first write the native requirement at the same floor
939 (``_lifecycle.declare_requirement``), so ``layering.graph`` finds
940 the two in agreement; then the ``[[depends]]`` edge joins the
941 package's contract. A sibling no writer takes refuses before the
942 contract changes. A test edge in a set with no writer of a test
943 requirement, and a tool edge, write no requirement. The files are
944 relative to the package, the contract first.
945 """
946 from livery.workshop import _lifecycle
947
948 required = (
949 _lifecycle.declare_requirement(package, dependency, floor, kind=kind)
950 if kind != "tool"
951 else []
952 )
953 contract = package.directory / "workshop.toml"
954 text = contract.read_text("utf-8")
955 edge = (
956 f'\n[[depends]]\npath = "{dependency.path}"\nkind = "{kind}"\n'
957 f'floor = "{floor}"\n'
958 )
959 contract.write_text(text.rstrip("\n") + "\n" + edge, encoding="utf-8")
960 return ["workshop.toml", *required]
961
962
963def write_edges(root: Path) -> list[str]:
964 """Declare every sibling reference the graph already reaches; the lines written.
965
966 The fix of the layering phase's sibling-references step. For each reference
967 [livery.workshop._packages.undeclared_references][] can write, the
968 writers of the package's set write the native requirement and the
969 ``[[depends]]`` edge joins the package's contract, both at the
970 floor the graph carries. A reference the graph does not reach is
971 left for the judge that follows: it is a new dependency, and a
972 decision. Idempotent: a second call writes nothing.
973 """
974 packages = discover_packages(root)
975 written: list[str] = []
976 for package, dependency, kind, floor in undeclared_references(packages)[0]:
977 files = declare_edge(package, dependency, kind=kind, floor=floor)
978 written.append(
979 f" layering: {package.path} declares the {kind} edge on"
980 f" {dependency.path} at floor {floor} ({', '.join(files)})"
981 )
982 return written
983
984
985def _test_problems(
986 package: Package,
987 edge: Edge,
988 by_path: Mapping[str, Package],
989 tested: Mapping[str, str],
990) -> list[str]:
991 """How *package*'s test *edge* disagrees with its test requirements *tested*."""
992 from livery.workshop._composition import extension_set
993
994 dependency = by_path[edge.path]
995 constraint = tested.get(dependency.name)
996 if constraint is None:
997 held = ", ".join(extension_set(dependency)) or "no extension"
998 return [
999 f"{package.path}: the test edge on {edge.path} is not declared in the"
1000 f" package's test requirements ({dependency.name} missing;"
1001 f" {edge.path} holds {held}); the gate's --fix writes it"
1002 ]
1003 if edge.floor and f">={edge.floor}" not in constraint:
1004 return [
1005 f"{package.path}: the test edge on {edge.path} floors at {edge.floor},"
1006 " and the declared test requirement says"
1007 f" {dependency.name}{constraint}; the gate's --fix writes the floor"
1008 ]
1009 return []
1010
1011
1012def write_test_requirements(root: Path) -> list[str]:
1013 """Write each test requirement a package's manifests lack; the lines written.
1014
1015 The fix of ``layering.graph`` for the test edges it judges: in each
1016 package whose set answers ``test-requirements``, a test edge whose
1017 requirement is missing, or carries another floor, is written at the
1018 edge's floor by the writers of the set
1019 (``_lifecycle.declare_requirement``). Idempotent: a second call
1020 writes nothing.
1021
1022 Raises:
1023 Failed: when no writer of a package's set takes a test edge's
1024 sibling, naming both sets.
1025 """
1026 from livery.workshop import _lifecycle
1027
1028 packages = discover_packages(root)
1029 by_path = {package.path: package for package in packages}
1030 written: list[str] = []
1031 for package in packages:
1032 tested = _lifecycle.declared_test_requirements(package)
1033 if tested is None:
1034 continue
1035 for edge in package.depends:
1036 if edge.kind != "test" or edge.path not in by_path:
1037 continue
1038 if not _test_problems(package, edge, by_path, tested):
1039 continue
1040 dependency = by_path[edge.path]
1041 files = _lifecycle.declare_requirement(
1042 package, dependency, edge.floor, kind="test"
1043 )
1044 if files:1044 ↛ 1035line 1044 didn't jump to line 1035 because the condition on line 1044 was always true
1045 written.append(
1046 f" layering: {package.path} requires {dependency.name}"
1047 f" at floor {edge.floor or 'none'} for its tests"
1048 f" ({', '.join(files)})"
1049 )
1050 return written
1051
1052
1053def _cycles(packages: tuple[Package, ...]) -> list[str]:
1054 """A cycle report, empty when dependencies only point downward."""
1055 edges = {
1056 package.path: [edge.path for edge in package.depends] for package in packages
1057 }
1058 seen: set[str] = set()
1059 stack: list[str] = []
1060
1061 def walk(node: str) -> list[str]:
1062 if node in stack:
1063 loop = [*stack[stack.index(node) :], node]
1064 return [" -> ".join(loop)]
1065 if node in seen:
1066 return []
1067 seen.add(node)
1068 stack.append(node)
1069 found = [cycle for child in edges.get(node, []) for cycle in walk(child)]
1070 stack.pop()
1071 return found
1072
1073 return [
1074 f"dependency cycle: {cycle}"
1075 for package in packages
1076 for cycle in walk(package.path)
1077 ]
1078
1079
1080def _sibling_references(context: RuleContext) -> list[str]:
1081 """The undeclared sibling references, by what the graph reaches.
1082
1083 A package's references come from all of its sources, so a package
1084 holding a source in scope is judged whole, and one holding none
1085 keeps its verdict.
1086 """
1087 problems: list[str] = []
1088 judged = {package.path for package in context.packages_in_scope()}
1089 writable, refused = undeclared_references(context.packages, only=judged)
1090 for package, dependency, kind, floor in writable:
1091 problems.append(
1092 f"{package.path}: uses {dependency.name} through a sibling that"
1093 f" brings it in, with no [[depends]] edge on {dependency.path}."
1094 f" Declare the {kind} edge at floor {floor}, the one the graph"
1095 " already carries, and the matching requirement; the gate's"
1096 " --fix writes both"
1097 )
1098 for package, dependency in refused:
1099 problems.append(
1100 f"{package.path}: uses {dependency.name}, and nothing it"
1101 f" depends on brings that in. Declare the edge on"
1102 f" {dependency.path} and its requirement deliberately: this"
1103 " one is a new dependency, not a fact the graph already has"
1104 )
1105 return problems
1106
1107
1108#: The base's own import path, and the namespace extensions live under.
1109BASE_MODULE = "livery.workshop"
1110EXTENSIONS_NAMESPACE = "livery.extensions"
1111
1112
1113def extension_imports_in_the_base(sources: Iterable[SourceReferences]) -> list[str]:
1114 """Each base module that imports an extension, with the extension named.
1115
1116 The base (``livery.workshop``) imports no extension under
1117 ``livery.extensions``: what an extension needs of the base it takes through
1118 the base's seams, and the base reaches an extension only through the
1119 registries the extension fills at mount. *sources* are records of the
1120 ``references`` answers; a module that runs without the name it imports
1121 is left alone, and one importing it lazily or for a type checker is
1122 judged.
1123 """
1124 problems: list[str] = []
1125 for source in sources:
1126 if not source.module.startswith(BASE_MODULE + "."):
1127 continue
1128 for reference in source.references:
1129 imported = reference.name
1130 if reference.optional:
1131 continue
1132 if imported == EXTENSIONS_NAMESPACE or imported.startswith(
1133 EXTENSIONS_NAMESPACE + "."
1134 ):
1135 problems.append(
1136 f"{source.path}: the base imports the extension {imported}; the"
1137 " base reaches an extension through a registry it fills at mount,"
1138 " never by import"
1139 )
1140 return problems
1141
1142
1143def _base_imports_no_extension(context: RuleContext) -> list[str]:
1144 """The base-imports-no-extension rule, over the ``references`` answers in scope."""
1145 return extension_imports_in_the_base(context.sources())
1146
1147
1148#: The base's rules over the sources, each the layering step of its
1149#: name, which the base registers beside its other steps: the base
1150#: importing no extension and the sibling references, both over the
1151#: ``references`` answers. The sibling step's fix writes the edges
1152#: (``write_edges``).
1153RULES: dict[str, Judge] = {
1154 "base-imports-no-extension": _base_imports_no_extension,
1155 "sibling-references": _sibling_references,
1156}