Coverage for packages/workshop/src/livery/workshop/_graph.py: 95%
Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_run.py, packages/workshop/tests/test_workshop_root_attribution.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_quality.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_parts.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.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_influence.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_e2e.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.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_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.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/conan/tests/test_cross_kind.py ran.
Keys
- r m x p show or hide the lines of a kind
- j k the next or previous highlighted chunk
- 0 the top of the page
- 1 the first highlighted chunk
- [ ] the previous or next file
- u the index
- ? show or hide this help
1"""The affected engine: which packages a change can influence.
3The workspace graph is the ``[[depends]]`` edges the contracts
4declare. A changed file maps to the package whose directory holds it,
5and the affected set is that package plus everything that depends on
6it, transitively (the dependents' closure): a change can break its
7consumers, never its dependencies. A change outside every package,
8the root configuration, the templates, the workspace tests, affects
9everything, because the root files configure every gate. A change
10can reach further than its package's dependents: a listed extension
11says how far through the ``reaches`` query, as python does for a
12module pytest loads as a plugin into every suite it runs.
14``fm graph.affected`` prints the verdict; the quality family's
15the reflex and the CI legs scope work to it.
18from __future__ import annotations
21from collections.abc import Callable, Iterable, Mapping
22from dataclasses import dataclass, field
23from pathlib import Path
25from livery import git
26from livery.footman import group
27from livery.workshop._packages import Package, discover_packages
29graph = group("graph", help="The workspace dependency graph")
32def dependents_closure(
33 packages: tuple[Package, ...], seeds: set[str]
34) -> tuple[Package, ...]:
35 """*seeds* (package paths) plus everything depending on them.
37 Follows the reversed ``[[depends]]`` edges to a fixed point, and
38 answers in discovery order so output stays deterministic.
40 dependents: dict[str, set[str]] = {package.path: set() for package in packages}
41 for package in packages:
42 for edge in package.depends:
43 dependents.setdefault(edge.path, set()).add(package.path)
44 affected = set(seeds)
45 frontier = list(seeds)
47 for consumer in dependents.get(frontier.pop(), ()):
48 if consumer not in affected:
49 affected.add(consumer)
50 frontier.append(consumer)
51 return tuple(package for package in packages if package.path in affected)
54def dependencies_closure(
55 packages: tuple[Package, ...], seeds: set[str]
56) -> tuple[Package, ...]:
57 """*seeds* (package paths) plus everything they depend on, transitively.
59 Follows the ``[[depends]]`` edges to a fixed point, and answers in
60 discovery order; [livery.workshop.order_topologically][]
61 puts each dependency before its dependents.
63 by_path = {package.path: package for package in packages}
64 needed = set(seeds)
65 frontier = list(seeds)
67 package = by_path.get(frontier.pop())
68 for edge in package.depends if package is not None else ():
69 if edge.path not in needed:
70 needed.add(edge.path)
71 frontier.append(edge.path)
72 return tuple(package for package in packages if package.path in needed)
75#: The prose directory: nothing under it reaches a gate.
78#: The site's own files at the root: its configuration and its pages.
79SITE_CONFIG = "zensical.toml"
80SITE_DOCS = "docs/"
82#: Files at the root that configure no package's steps: the licence,
83#: the CI files and the code-owners file the forge reads, the editor's
84#: and the agent's settings, git's own files, the entry script, the
85#: release's member list, the site's theme and the render's receipt.
86#: A workspace step that reads one still judges it.
101 ".release-manifest.json",
103 ".workshop-rendered",
107def reaches_no_package(path: str) -> bool:
108 """Whether *path* is a root file no package's steps read.
110 A change to one gates no package; the workspace steps that read it
111 still judge it ([livery.workshop._steps.selected][]).
113 from livery.workshop._categories import matches
115 return any(matches(pattern, path) for pattern in NO_PACKAGE)
118def is_site(path: str) -> bool:
119 """Whether *path* is the site's own: the root ``zensical.toml`` or ``docs/`` tree.
121 Only the site build reads them, and it runs on every run, so
122 they reach no format, lint, type, or test gate. A package's
123 ``docs/`` directory is the package's, not the site's.
125 return path == SITE_CONFIG or path.startswith(SITE_DOCS)
128def is_prose(path: str) -> bool:
129 """Whether *path* is prose: under ``notes/``, or a markdown file anywhere.
131 Prose reaches no format, lint, type, or test gate. The site build
132 is where markdown is judged, and it runs on every run.
134 return path.startswith(NOTES) or path.endswith(".md")
137def affected_packages(root: Path, *, base: str = "main") -> tuple[Package, ...] | None:
138 """The packages this branch's changes can influence, and the workspace's own tests.
140 None means everything: a touched file outside every package (the
141 root configuration, templates) configures every gate, so no
142 narrowing is honest, and the file is named. Prose (`is_prose`)
143 and the site's own files (`is_site`) affect no package wherever
144 they live, so a diff confined to them affects nothing. A change
145 under the workspace's own ``tests/`` affects that unit alone,
146 which the answer then carries as a package of its own
147 ([livery.workshop.workspace_suite][]): its tests
148 reach every package, and every leg that runs a suite runs them
149 anyway, so no package's suite has to run for it. An empty tuple
150 means the branch changes nothing a gate reads.
152 scope = affected_by(
154 git.changed_paths(root, base),
155 # Asked only for a change outside every package, or one inside a
156 # package the listed extensions are asked about.
157 before=lambda: git.merge_base(root, base),
159 return None if scope is None else scope.packages
162def affected_by(
163 root: Path, paths: Iterable[str], *, before: str | Callable[[], str]
165 """What *paths*, changed since *before*, reach among the workspace's packages.
167 `affected_from_paths` over the packages discovered under *root*.
168 ``None`` means everything.
170 packages = discover_packages(root)
171 return affected_from_paths(root, packages, paths, before=before)
174@dataclass(frozen=True)
176 """What a change reaches: the packages, and the tests that stand for some.
179 packages: The packages to gate, in discovery order, the
180 workspace's own tests unit last when its files changed.
181 tests: Per package, the test files that stand for its suite;
182 the walk names none until a better narrowing exists, so
183 every package runs its suite whole.
184 examples: The package paths whose changed files are examples
185 and nothing else: their examples run and no suite. A
186 package reached through its source runs both.
189 packages: tuple[Package, ...]
190 tests: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
191 examples: tuple[str, ...] = ()
194def docs_page(packages: tuple[Package, ...], path: str) -> Package | None:
195 """The package whose authored docs page *path* is, or None for any other path."""
196 if not path.endswith(".md") or "/_generated/" in path:
198 for package in packages:
199 if path.startswith(package.path + "/docs/"):
204def affected_from_paths(
206 packages: tuple[Package, ...],
207 paths: Iterable[str],
209 before: str | Callable[[], str] = "",
211 """What a change to *paths* reaches: the packages, and the tests that stand alone.
213 The classification `affected_packages` applies to a branch's
214 changes, for any set of paths: the reflex hands it the paths
215 between a proved tree and the working tree. Each path is
216 classified by its package's kind: a test file reaches its own
217 package alone, since nothing imports a test, and that package
218 runs its whole suite; source, test support, and configuration
219 reach the package's dependents and run the suites. A change under
220 the workspace's own tests runs that unit whole. A docs page
221 reaches nothing: the site build reads it. An example file reaches
222 its package's examples step
223 and no suite, unless source of the package changed too. A file
224 outside every package reaches everything, unless *before* (the
225 commit or tree the paths were taken from) shows the change is
226 about the packages added or removed, or, for ``uv.lock``, about
227 the members whose resolution it moves
228 ([livery.workshop._root_attribution][]): then it reaches those.
229 A change inside a package reaches further when a listed extension
230 says so: each answer to the ``reaches`` query is called with the
231 change, and every member it names for a changed path runs with
232 its dependents (`_reached`).
233 *before* may be a function answering it, asked once, and only
234 when a path outside every package or an answer to ``reaches``
236 ``None`` means everything, an empty scope nothing a gate reads.
238 from livery.workshop._categories import EXAMPLE, TEST, category_of
239 from livery.workshop._packages import WORKSPACE_TESTS, workspace_suite
241 paths = tuple(paths)
242 if not isinstance(before, str):
243 before = functools.cache(before)
244 seeds: set[str] = set()
245 # A package whose test files changed runs its whole suite; nothing
246 # imports a test, so its dependents' suites do not run. The suite
247 # is not narrowed to the changed files until a better narrowing
248 # exists: the tests a change reaches are more than the ones it edits.
249 suites: set[str] = set()
250 examples: set[str] = set()
251 tests_changed = False
253 outside: list[str] = []
254 for path in paths:
255 if docs_page(packages, path) is not None:
257 if is_prose(path) or is_site(path) or reaches_no_package(path):
259 if path.startswith(WORKSPACE_TESTS + "/"):
260 tests_changed = True
262 for package in packages:
263 if path.startswith(package.path + "/"):
265 relative = path[len(package.path) + 1 :]
266 category = category_of(package, relative).name
267 if category == EXAMPLE:
268 examples.add(package.path)
269 elif category == TEST:
270 suites.add(package.path)
272 seeds.add(package.path)
275 outside.append(path)
277 attributed = _attribute(root, packages, outside, before=before)
278 if attributed is None:
280 seeds |= attributed
282 widened = _reached(root, packages, paths, before=before)
283 if widened is None:
285 seeds |= widened
286 reached = {package.path for package in dependents_closure(packages, seeds)}
288 sorted(path for path in examples if path not in reached and path not in suites)
290 members = tuple(
292 for package in packages
293 if package.path in reached or package.path in suites or package.path in alone
295 if not tests_changed:
296 return Scope(members, {}, alone)
297 unit = workspace_suite(root)
298 if unit is None:
299 print(f" {WORKSPACE_TESTS}/: changed and gone; everything runs")
301 return Scope((*members, unit), {}, alone)
306 packages: tuple[Package, ...],
309 before: str | Callable[[], str],
311 """The packages the changes to *paths*, all outside every package, are about.
313 None means everything, and the first path that forces it is
314 named: without *before* there is nothing to compare with, and a
315 change the package set does not explain configures every gate.
317 from livery.workshop._root_attribution import (
324 point = before if isinstance(before, str) else before()
325 if root is None or not point:
326 print(f" {paths[0]}: outside the packages; everything runs")
328 delta = package_delta(root, point, packages)
329 seeds = {package.path for package in delta.added}
330 for path in paths:
331 if delta.holds(path):
332 continue # a removed package's own files: nothing depends on it now
333 old = git.file_at(root, point, path)
334 target = root / path
335 new = target.read_text("utf-8") if target.is_file() else ""
336 if path == LOCK:336 ↛ 337line 336 didn't jump to line 337 because the condition on line 336 was never true
337 moved = lock_affected(old, new, delta)
340 f" {path}: a resolution beyond the members moved; everything runs"
345 if not explained(old, new, delta):
346 print(f" {path}: outside the packages; everything runs")
348 print(f" {path}: names only the packages added or removed")
354 packages: tuple[Package, ...],
355 paths: tuple[str, ...],
357 before: str | Callable[[], str],
359 """The members the listed extensions say the change to *paths* reaches.
361 Each function the extensions answer the ``reaches`` query with
362 ([livery.workshop._queries.REACHES][]) is called with the change,
363 *before* resolved only when one answers. Each changed path an
364 answer widens is printed with why, and with how many members it
365 reaches. None means everything, and the line names the extension:
366 an answer raised, or named a path outside the members.
368 from livery.workshop._influence import Changes
369 from livery.workshop._queries import REACHES, answers
372 answered = answers(root, REACHES)
373 except Exception as error:
374 print(f" reaches: {error}; everything runs")
376 if not answered:
378 point = before if isinstance(before, str) else before()
379 changes = Changes(root, paths, point)
380 members = {package.path for package in packages}
381 seeds: set[str] = set()
382 for name, functions in answered.items():
385 (path, why, tuple(found))
386 for function in functions
387 for path, (why, found) in function(changes).items()
389 except Exception as error:
391 f" {name} could not say what the change reaches ({error});"
395 for path, why, found in widened:
396 unknown = sorted(set(found) - members)
399 f" {path}: {name} says it reaches {', '.join(unknown)},"
400 " outside the members; everything runs"
403 print(f" {path}: {why}; it reaches {len(found)} package(s)")
404 seeds.update(found)
408@graph.task(name="affected")
409def graph_affected(base: str = "main") -> None:
410 """Print the affected packages for this branch, one per line.
413 base: the branch the change will merge into
415 from livery.workshop._extensions import workspace_root
417 root = workspace_root()
418 if root is None:418 ↛ 419line 418 didn't jump to line 419 because the condition on line 418 was never true
419 print(" no workspace: no workshop.toml above the working directory")
422 affected = affected_packages(root, base=base)
423 if affected is None:
424 print(" everything: a change outside the packages configures every gate")
426 if not affected:426 ↛ 427line 426 didn't jump to line 427 because the condition on line 426 was never true
427 print(" nothing: the branch changes no files")
429 for package in affected:
430 print(f" {package.path} ({package.name})")
433def order_topologically(packages: tuple[Package, ...]) -> tuple[Package, ...]:
434 """*packages* in release order: every dependency before its dependents.
436 Kahn's walk over the ``[[depends]]`` edges restricted to the given
437 set; ties keep the input order so the result is deterministic. A
438 cycle cannot arise, the layering lint refuses one long before a
441 chosen = {p.path for p in packages}
442 remaining = list(packages)
443 ordered: list[Package] = []
444 placed: set[str] = set()
445 while remaining:
446 for index, package in enumerate(remaining):
449 for edge in package.depends
450 if edge.path in chosen and edge.path not in placed
453 ordered.append(package)
454 placed.add(package.path)
455 del remaining[index]
457 else: # pragma: no cover - guarded by the layering lint
458 ordered.extend(remaining)
460 return tuple(ordered)