systemap 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
systemap/delta.py ADDED
@@ -0,0 +1,670 @@
1
+ """What a change does to the map: `systemap delta --base REF [--head REF]`.
2
+
3
+ The loop in the skill is built for the first draft. After a pull request
4
+ moves a module, `extract --check` fails, says the map is stale, and the
5
+ only answer used to be the whole loop again, at first-draft cost. This
6
+ module reads the facts at two commits and says, in the map's terms, what
7
+ the change did:
8
+
9
+ moved ................ a module at a new path, with the same content or
10
+ the same public names; the card that names the
11
+ old path is told to rename it
12
+ added ................ a new module, and the card that claims it; a new
13
+ module no card claims is coverage lost, and the
14
+ line says so
15
+ removed .............. a module that is gone, and the card that still
16
+ names it
17
+ entry vanished ....... a card's entry that its modules defined at the
18
+ base commit and no longer do
19
+ interface vanished ... the same for the name an interface line starts
20
+ with, by the check's own interface rule
21
+ new crossing import .. an import that crosses a card boundary at the
22
+ head commit, did not at the base, and has no
23
+ flow and no answer under [judgement]
24
+ evidence lost ........ a flow an import backed at the base commit and
25
+ nothing backs now
26
+
27
+ Each line names its fix. A line needs a person, or it does not (a new
28
+ module claimed through a `pkg.*` pattern needs nobody), and the exit
29
+ code says which: 0 when nothing needs a person, 1 when something does.
30
+ `--format markdown` prints the same report as a pull-request comment.
31
+
32
+ The facts at each commit are read from the git tree (`git archive` into
33
+ a temporary directory, then the extractor as usual), so the working copy
34
+ is not touched and an extraction here cannot differ from what `systemap
35
+ extract` would read at that commit. The model is the one on disk, the map
36
+ as it is now, the file the person edits: a card that names a module's new
37
+ path is taken to have claimed the old one at the base commit, and a card
38
+ that still names the old path is judged as if renamed, so a pending rename
39
+ is one line, not four.
40
+
41
+ The comparison runs on every map of the tree (`compute_tree`): the top
42
+ map over every module, and the map inside a card over the modules that
43
+ card claims, so a moved module names its card on each map it is drawn
44
+ on, and the map's file. A sub-map's lines carry its id in front.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import dataclasses
50
+ import io
51
+ import re
52
+ import subprocess
53
+ import tarfile
54
+ import tempfile
55
+ from dataclasses import dataclass
56
+ from pathlib import Path
57
+ from typing import Any
58
+
59
+ from systemap import evidence, extract, nest
60
+ from systemap.check import interface_head, interface_problem
61
+ from systemap.config import Config
62
+ from systemap.judgement import answers, crossing_line, crossing_pairs
63
+ from systemap.model import (
64
+ Component,
65
+ Meaning,
66
+ Model,
67
+ claimed,
68
+ defines_entry,
69
+ is_symbol,
70
+ module_matches,
71
+ public_names,
72
+ symbol_claims,
73
+ )
74
+
75
+ MARKER = "<!-- systemap delta -->"
76
+ NEXT = "systemap refresh && systemap check && systemap judgement --strict"
77
+ # Past this share of the cards, the skill says to run the full loop instead
78
+ # of acting line by line.
79
+ FULL_LOOP_SHARE = 1 / 3
80
+
81
+
82
+ class DeltaError(Exception):
83
+ """The two commits cannot be compared; the message says why."""
84
+
85
+
86
+ # ---- git: the facts at a commit, without touching the working copy -----------
87
+
88
+
89
+ def _git(repo: Path, *args: str) -> subprocess.CompletedProcess[bytes]:
90
+ return subprocess.run(["git", *args], cwd=repo, capture_output=True, timeout=300)
91
+
92
+
93
+ def resolve(repo: Path, ref: str) -> str:
94
+ """The full commit sha a ref names, or a DeltaError naming the ref."""
95
+ proc = _git(repo, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}")
96
+ if proc.returncode != 0 or not proc.stdout.strip():
97
+ raise DeltaError(f"unknown ref {ref}; give a commit, a branch or a tag git can find")
98
+ return proc.stdout.decode("utf-8").strip()
99
+
100
+
101
+ def merge_base(repo: Path, base: str, head: str) -> str:
102
+ """The commit the two share, so a base branch that moved on is not a change;
103
+ the base itself when git cannot say (no shared history)."""
104
+ proc = _git(repo, "merge-base", base, head)
105
+ out = proc.stdout.decode("utf-8").strip()
106
+ return out if proc.returncode == 0 and out else base
107
+
108
+
109
+ def _extract_all(tar: tarfile.TarFile, into: Path) -> None:
110
+ # The data filter refuses paths outside the target; it exists from
111
+ # 3.11.4, and an older 3.11 extracts the archive git wrote as is.
112
+ if hasattr(tarfile, "data_filter"):
113
+ tar.extractall(into, filter="data")
114
+ else: # pragma: no cover - older interpreters only
115
+ tar.extractall(into)
116
+
117
+
118
+ def facts_at(cfg: Config, sha: str) -> dict[str, Any]:
119
+ """The facts for the tree at `sha`, extracted from git, never from the working copy."""
120
+ proc = _git(cfg.root, "archive", "--format=tar", sha)
121
+ if proc.returncode != 0:
122
+ raise DeltaError(
123
+ f"git archive {sha[:7]} failed: {proc.stderr.decode('utf-8', 'replace').strip()}"
124
+ )
125
+ with tempfile.TemporaryDirectory(prefix="systemap-delta-") as tmp:
126
+ into = Path(tmp).resolve()
127
+ with tarfile.open(fileobj=io.BytesIO(proc.stdout)) as tar:
128
+ _extract_all(tar, into)
129
+ facts = extract.build(dataclasses.replace(cfg, root=into))
130
+ facts["built_at_commit"] = sha
131
+ return facts
132
+
133
+
134
+ def remote_repository(repo: Path) -> str:
135
+ """`owner/name` of the origin remote when it is on GitHub, else empty."""
136
+ proc = _git(repo, "remote", "get-url", "origin")
137
+ if proc.returncode != 0:
138
+ return ""
139
+ url = proc.stdout.decode("utf-8", "replace").strip()
140
+ found = re.search(r"github\.com[:/]([^/\s]+)/([^/\s]+?)(?:\.git)?/?$", url)
141
+ return f"{found.group(1)}/{found.group(2)}" if found else ""
142
+
143
+
144
+ def figure_url(cfg: Config, sha: str) -> str:
145
+ """The committed whole-map figure at `sha`, as the URL a comment renders, or empty.
146
+
147
+ A comment cannot show a relative path, and GitHub's own writing guide
148
+ gives the form for an image in the repository from an issue or a pull
149
+ request: the blob URL with `?raw=true`. The figure is the first
150
+ configured `.svg` that draws every reading (no `layer`), else the first
151
+ `.svg`; nothing when the file is not in the tree at that commit.
152
+ """
153
+ owner = remote_repository(cfg.root)
154
+ if not owner:
155
+ return ""
156
+ svgs = [f for f in cfg.figures if f.out.endswith(".svg")]
157
+ whole = [f for f in svgs if not f.layer]
158
+ for fig in whole + svgs:
159
+ path = f"{cfg.out_dir}/{fig.out}"
160
+ if _git(cfg.root, "cat-file", "-e", f"{sha}:{path}").returncode == 0:
161
+ return f"https://github.com/{owner}/blob/{sha}/{path}?raw=true"
162
+ return ""
163
+
164
+
165
+ # ---- the comparison --------------------------------------------------------------
166
+
167
+
168
+ @dataclass(frozen=True)
169
+ class Line:
170
+ """One thing the change did to the map, with its fix when a person is needed."""
171
+
172
+ kind: str
173
+ text: str
174
+ cards: tuple[str, ...] = ()
175
+ person: bool = False
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class Delta:
180
+ """Everything `systemap delta` reports about two commits."""
181
+
182
+ base: str
183
+ head: str
184
+ base_ref: str
185
+ head_ref: str
186
+ changed: int
187
+ added: int
188
+ removed: int
189
+ moved: int
190
+ cards: int
191
+ lines: tuple[Line, ...]
192
+
193
+ @property
194
+ def open(self) -> list[Line]:
195
+ return [line for line in self.lines if line.person]
196
+
197
+ @property
198
+ def quiet(self) -> list[Line]:
199
+ return [line for line in self.lines if not line.person]
200
+
201
+ @property
202
+ def named(self) -> list[str]:
203
+ return sorted({card for line in self.lines for card in line.cards})
204
+
205
+ @property
206
+ def has_change(self) -> bool:
207
+ return bool(self.changed or self.added or self.removed or self.moved or self.lines)
208
+
209
+ @property
210
+ def past_a_third(self) -> bool:
211
+ return self.cards > 0 and len(self.named) > self.cards * FULL_LOOP_SHARE
212
+
213
+
214
+ def _moves(
215
+ base: dict[str, Any], head: dict[str, Any], gone: list[str], new: list[str]
216
+ ) -> dict[str, tuple[str, str]]:
217
+ """old module -> (new module, how it was recognised), for every move.
218
+
219
+ Same content first (the extractor's sha of the source), then the same
220
+ public names when there are any; each new module is matched once.
221
+ """
222
+ out: dict[str, tuple[str, str]] = {}
223
+ free = list(new)
224
+ for old in gone:
225
+ for candidate in free:
226
+ if base[old]["sha"] == head[candidate]["sha"]:
227
+ out[old] = (candidate, "same content")
228
+ free.remove(candidate)
229
+ break
230
+ for old in gone:
231
+ if old in out:
232
+ continue
233
+ names = public_names(base[old])
234
+ if not names:
235
+ continue
236
+ for candidate in free:
237
+ if public_names(head[candidate]) == names:
238
+ out[old] = (candidate, "same public names")
239
+ free.remove(candidate)
240
+ break
241
+ return out
242
+
243
+
244
+ def _mapped(pattern: str, mapping: dict[str, str]) -> str:
245
+ """One `implemented_by` entry with a moved module renamed; patterns stay."""
246
+ if is_symbol(pattern):
247
+ module, _, name = pattern.partition(":")
248
+ return f"{mapping.get(module, module)}:{name}"
249
+ return mapping.get(pattern, pattern)
250
+
251
+
252
+ def with_claims(model: Model, mapping: dict[str, str]) -> Model:
253
+ """The model with every claim renamed through `mapping`, positions and all."""
254
+ return dataclasses.replace(
255
+ model,
256
+ components=tuple(
257
+ dataclasses.replace(
258
+ c, implemented_by=tuple(_mapped(p, mapping) for p in c.implemented_by)
259
+ )
260
+ for c in model.components
261
+ ),
262
+ )
263
+
264
+
265
+ def _names_it(c: Component, module: str) -> bool:
266
+ """Does a card name `module` outright, by name or as a symbol's module?"""
267
+ return module in c.implemented_by or any(m == module for m, _n in symbol_claims(c))
268
+
269
+
270
+ def compute(
271
+ cfg: Config,
272
+ model: Model,
273
+ meaning: Meaning,
274
+ base: dict[str, Any],
275
+ head: dict[str, Any],
276
+ base_ref: str = "",
277
+ head_ref: str = "",
278
+ *,
279
+ model_file: str = "",
280
+ within: str = "",
281
+ prefix: str = "",
282
+ ) -> Delta:
283
+ """What the change from `base` to `head` does to the map the model draws.
284
+
285
+ `model_file` is the file the fixes name (the configured model when
286
+ empty); `within` names the card a sub-map is inside, whose claims
287
+ bound what a new module may be ignored from; `prefix` is what the
288
+ sub-map's judgement lines carry, so an answered crossing import is
289
+ matched as printed.
290
+ """
291
+ b: dict[str, Any] = base.get("components", {})
292
+ h: dict[str, Any] = head.get("components", {})
293
+ gone = sorted(set(b) - set(h))
294
+ new = sorted(set(h) - set(b))
295
+ moves = _moves(b, h, gone, new)
296
+ renamed = {old: new_name for old, (new_name, _how) in moves.items()}
297
+ inverse = {new_name: old for old, new_name in renamed.items()}
298
+ model_file = model_file or cfg.model
299
+ base_short = base.get("built_at_commit", "")[:7]
300
+ at_base = f" at {base_short}" if base_short else " at the base commit"
301
+
302
+ # The map as written names what the person can edit; the two views are
303
+ # the same claims carried to each commit's names.
304
+ head_model = with_claims(model, renamed)
305
+ base_model = with_claims(model, inverse)
306
+ owner_written = evidence.owners(model, head)
307
+ owner_head = evidence.owners(head_model, head)
308
+ owner_base = evidence.owners(base_model, base)
309
+ ignores = [i.module for i in cfg.coverage_ignore]
310
+
311
+ def ignored(module: str) -> bool:
312
+ return any(module_matches(i, module) for i in ignores)
313
+
314
+ lines: list[Line] = []
315
+
316
+ # ---- moved, added, removed ------------------------------------------------
317
+ for old, (new_name, how) in moves.items():
318
+ explicit = [c.id for c in model.components if _names_it(c, old)]
319
+ claimed_by = owner_written.get(new_name)
320
+ if explicit:
321
+ who = ", ".join(explicit)
322
+ lines.append(
323
+ Line(
324
+ "moved",
325
+ f"moved: {old} -> {new_name} ({how}); {who} names {old} in implemented_by: "
326
+ f"rename it to {new_name} in {model_file}",
327
+ tuple(explicit),
328
+ person=True,
329
+ )
330
+ )
331
+ elif (
332
+ claimed_by is None
333
+ and not ignored(new_name)
334
+ and not extract.is_empty_marker(h[new_name])
335
+ ):
336
+ was = owner_base.get(old)
337
+ lines.append(
338
+ Line(
339
+ "moved",
340
+ f"moved: {old} -> {new_name} ({how}); no card claims {new_name}: name it in "
341
+ f"a card's implemented_by in {model_file}",
342
+ (was,) if was else (),
343
+ person=True,
344
+ )
345
+ )
346
+ else:
347
+ where = f", claimed by {claimed_by}" if claimed_by else ", ignored under [coverage]"
348
+ lines.append(
349
+ Line(
350
+ "moved",
351
+ f"moved: {old} -> {new_name} ({how}){where}",
352
+ (claimed_by,) if claimed_by else (),
353
+ )
354
+ )
355
+ for module in new:
356
+ if module in inverse:
357
+ continue
358
+ claimed_by = owner_written.get(module)
359
+ if claimed_by:
360
+ lines.append(Line("added", f"added: {module}, claimed by {claimed_by}", (claimed_by,)))
361
+ elif extract.is_empty_marker(h[module]):
362
+ lines.append(Line("added", f"added: {module}, an empty package marker"))
363
+ elif ignored(module) and not within:
364
+ lines.append(Line("added", f"added: {module}, ignored under [coverage]"))
365
+ else:
366
+ # Inside a card there is no ignoring: the sub-map claims
367
+ # exactly what the card claims.
368
+ way_out = (
369
+ f"the map inside {within} claims exactly what {within} claims"
370
+ if within
371
+ else "or ignore it with a reason under [coverage]"
372
+ )
373
+ lines.append(
374
+ Line(
375
+ "added",
376
+ f"added: {module}, claimed by no card; name it in a card's implemented_by "
377
+ f"in {model_file}, {way_out}",
378
+ person=True,
379
+ )
380
+ )
381
+ for module in gone:
382
+ if module in renamed:
383
+ continue
384
+ explicit = [c.id for c in model.components if module in c.implemented_by]
385
+ symbols = [
386
+ (c.id, name) for c in model.components for m, name in symbol_claims(c) if m == module
387
+ ]
388
+ if explicit:
389
+ who = ", ".join(explicit)
390
+ lines.append(
391
+ Line(
392
+ "removed",
393
+ f"removed: {module}; {who} names it in implemented_by: drop it in {model_file}",
394
+ tuple(explicit),
395
+ person=True,
396
+ )
397
+ )
398
+ elif symbols:
399
+ who = ", ".join(f"{cid} claims symbol {module}:{name}" for cid, name in symbols)
400
+ lines.append(
401
+ Line(
402
+ "removed",
403
+ f"removed: {module}; {who}: drop it in {model_file}",
404
+ tuple(cid for cid, _n in symbols),
405
+ person=True,
406
+ )
407
+ )
408
+ elif module in ignores and not within:
409
+ lines.append(
410
+ Line(
411
+ "removed",
412
+ f"removed: {module}; the [coverage] ignore that names it is stale: remove it",
413
+ person=True,
414
+ )
415
+ )
416
+ else:
417
+ was = owner_base.get(module)
418
+ tail = f", was claimed by {was} through a pattern" if was else ""
419
+ lines.append(Line("removed", f"removed: {module}{tail}", (was,) if was else ()))
420
+
421
+ # ---- entry and interface names that vanished ---------------------------------
422
+ # A card told to rename or drop a module is not asked about its names
423
+ # too: the rename or the drop comes first, and delta is run again.
424
+ touched = {card for line in lines if line.person for card in line.cards}
425
+ for c_base, c_head in zip(base_model.components, head_model.components, strict=True):
426
+ if c_head.kind == "actor" or c_head.id in touched:
427
+ continue
428
+ if c_head.entry and defines_entry(c_base, base) and not defines_entry(c_head, head):
429
+ lines.append(
430
+ Line(
431
+ "entry vanished",
432
+ f"entry vanished: {c_head.id} names entry {c_head.entry}, which its modules "
433
+ f"defined{at_base} and no longer do; set entry to a public name they define "
434
+ f"in {model_file}",
435
+ (c_head.id,),
436
+ person=True,
437
+ )
438
+ )
439
+ if not c_head.interface.strip() or interface_problem(c_base, b):
440
+ continue
441
+ if interface_problem(c_head, h):
442
+ found = interface_head(c_head.interface)
443
+ name = ".".join(part for part in (found or ("", "")) if part)
444
+ lines.append(
445
+ Line(
446
+ "interface vanished",
447
+ f"interface vanished: {c_head.id}'s interface starts with {name}, which its "
448
+ f"modules defined{at_base} and no longer do; start it with a public name "
449
+ f"they define in {model_file}, or leave it empty",
450
+ (c_head.id,),
451
+ person=True,
452
+ )
453
+ )
454
+
455
+ # ---- new crossing imports ------------------------------------------------------
456
+ joined = {frozenset(f.edge) for f in model.flows}
457
+ before = {(renamed.get(m, m), renamed.get(t, t)) for m in b for t in b[m].get("uses", {})}
458
+ # The judgement's line for the pair at the head commit, so an answer
459
+ # that covers the pair there (by pair, into, from, kind or the exact
460
+ # line) covers the new import here.
461
+ pairs = crossing_pairs(h, owner_head)
462
+ for module in sorted(h):
463
+ p = owner_head.get(module)
464
+ if not p:
465
+ continue
466
+ for target in sorted(h[module].get("uses", {})):
467
+ q = owner_head.get(target)
468
+ if not q or q == p or frozenset((p, q)) in joined or (module, target) in before:
469
+ continue
470
+ asked = prefix + crossing_line(p, q, pairs.get((p, q), [(module, target)]))
471
+ if any(answers(a, asked) for a in cfg.judgement_answered):
472
+ continue
473
+ lines.append(
474
+ Line(
475
+ "new crossing import",
476
+ f"new crossing import: {module} (card {p}) imports {target} (card {q}) and "
477
+ f"no flow joins {p} and {q}; add the flow with its sentence in {model_file}, "
478
+ "or answer it under [judgement] answered",
479
+ (p, q),
480
+ person=True,
481
+ )
482
+ )
483
+
484
+ # ---- evidence lost ------------------------------------------------------------------
485
+ ev_base = evidence.of_model(base_model, meaning, base, cfg.observed_by)
486
+ ev_head = evidence.of_model(head_model, meaning, head, cfg.observed_by)
487
+ for f in model.flows:
488
+ was_observed = ev_base[f.edge].state == evidence.OBSERVED
489
+ if was_observed and ev_head[f.edge].state == evidence.DECLARED:
490
+ lines.append(
491
+ Line(
492
+ "evidence lost",
493
+ f"evidence lost: {f.src} -> {f.dst} ({f.artifact}) was observed{at_base} and "
494
+ "no import joins them now; find the evidence, name the mechanism in the "
495
+ f"sentence, or remove the flow in {model_file}",
496
+ (f.src, f.dst),
497
+ person=True,
498
+ )
499
+ )
500
+
501
+ changed = sum(1 for m in set(b) & set(h) if b[m].get("sha") != h[m].get("sha"))
502
+ return Delta(
503
+ base=base.get("built_at_commit", ""),
504
+ head=head.get("built_at_commit", ""),
505
+ base_ref=base_ref,
506
+ head_ref=head_ref,
507
+ changed=changed,
508
+ added=len(new) - len(moves),
509
+ removed=len(gone) - len(moves),
510
+ moved=len(moves),
511
+ cards=sum(1 for c in model.components if c.kind != "actor"),
512
+ lines=tuple(lines),
513
+ )
514
+
515
+
516
+ def _view(facts: dict[str, Any], modules: set[str]) -> dict[str, Any]:
517
+ """The facts restricted to `modules`: what a map inside a card compares."""
518
+ components: dict[str, Any] = facts.get("components", {})
519
+ return {**facts, "components": {m: r for m, r in components.items() if m in modules}}
520
+
521
+
522
+ def compute_tree(
523
+ cfg: Config,
524
+ tree: nest.Tree,
525
+ base: dict[str, Any],
526
+ head: dict[str, Any],
527
+ base_ref: str = "",
528
+ head_ref: str = "",
529
+ ) -> Delta:
530
+ """The change on every map of the tree, as one report.
531
+
532
+ The top map is compared over every module. The map inside a card is
533
+ compared over the modules the card claims, at each commit (a moved
534
+ module counts on both sides, through the card's renamed claims), so
535
+ a module the card lost or gained names the sub-map's card and file
536
+ too, and nothing outside the card is the sub-map's business. The
537
+ counts are the top map's; the cards named are every map's, a
538
+ sub-map's under `<map>/<card>`.
539
+ """
540
+ top = compute(cfg, tree.top.model, tree.top.meaning, base, head, base_ref, head_ref)
541
+ b: dict[str, Any] = base.get("components", {})
542
+ h: dict[str, Any] = head.get("components", {})
543
+ gone = sorted(set(b) - set(h))
544
+ new = sorted(set(h) - set(b))
545
+ renamed = {old: new_name for old, (new_name, _how) in _moves(b, h, gone, new).items()}
546
+ inverse = {new_name: old for old, new_name in renamed.items()}
547
+ lines = list(top.lines)
548
+ cards = top.cards
549
+ for m in tree.maps[1:]:
550
+ card = tree.opening_card(m)
551
+ if card is None:
552
+ continue
553
+ at_head = set(claimed(card, h))
554
+ at_base = set(claimed(with_claims_of(card, inverse), b))
555
+ sub = compute(
556
+ cfg,
557
+ m.model,
558
+ m.meaning,
559
+ _view(base, at_base),
560
+ _view(head, at_head),
561
+ base_ref,
562
+ head_ref,
563
+ model_file=m.rel,
564
+ within=card.id,
565
+ prefix=m.prefix,
566
+ )
567
+ cards += sub.cards
568
+ lines += [
569
+ dataclasses.replace(
570
+ line,
571
+ text=m.prefix + line.text,
572
+ cards=tuple(f"{m.id}/{c}" for c in line.cards),
573
+ )
574
+ for line in sub.lines
575
+ ]
576
+ return dataclasses.replace(top, cards=cards, lines=tuple(lines))
577
+
578
+
579
+ def with_claims_of(card: Component, mapping: dict[str, str]) -> Component:
580
+ """One card with its claims renamed through `mapping`."""
581
+ return dataclasses.replace(
582
+ card, implemented_by=tuple(_mapped(p, mapping) for p in card.implemented_by)
583
+ )
584
+
585
+
586
+ # ---- the two reports -------------------------------------------------------------------
587
+
588
+
589
+ def _label(ref: str, sha: str) -> str:
590
+ short = sha[:7]
591
+ if ref and short and not ref.startswith(short) and ref != sha:
592
+ return f"{ref} ({short})"
593
+ return ref or short
594
+
595
+
596
+ def _counts(d: Delta) -> str:
597
+ return (
598
+ f"{d.changed} modules changed, {d.added} added, {d.removed} removed, {d.moved} moved; "
599
+ f"{len(d.named)} of {d.cards} cards named"
600
+ )
601
+
602
+
603
+ FULL_LOOP = (
604
+ "more than a third of the cards are named: the skill says to run the full loop "
605
+ "instead of acting line by line"
606
+ )
607
+
608
+
609
+ def report(d: Delta) -> list[str]:
610
+ """The lines the CLI prints: the header, each group, and what to run."""
611
+ span = f"{_label(d.base_ref, d.base)} -> {_label(d.head_ref, d.head)}"
612
+ if not d.has_change:
613
+ pair = f"{_label(d.base_ref, d.base)} and {_label(d.head_ref, d.head)}"
614
+ return [f"delta: no module changed between {pair}; the map is unaffected"]
615
+ out = [f"delta: {span}: {_counts(d)}"]
616
+ if d.open:
617
+ out.append(f"needs a person ({len(d.open)}):")
618
+ out += [f" {line.text}" for line in d.open]
619
+ if d.quiet:
620
+ out.append(f"changed, nothing to do ({len(d.quiet)}):")
621
+ out += [f" {line.text}" for line in d.quiet]
622
+ if d.past_a_third:
623
+ out.append(FULL_LOOP)
624
+ if d.open:
625
+ out.append(f"act on each line above, then run: {NEXT}")
626
+ else:
627
+ out.append("nothing needs a person; run: systemap refresh")
628
+ return out
629
+
630
+
631
+ def markdown(d: Delta, figure: str = "") -> str:
632
+ """The same report as a pull-request comment; `figure` is the committed map's URL."""
633
+ span = f"`{_label(d.base_ref, d.base)}` to `{_label(d.head_ref, d.head)}`"
634
+ out = [MARKER, "## What this change does to the map", ""]
635
+ if not d.has_change:
636
+ out += [
637
+ f"No module changed between {span.replace(' to ', ' and ')}; the map is unaffected.",
638
+ "",
639
+ ]
640
+ return "\n".join(out)
641
+ out += [f"{span}: {_counts(d)}.", ""]
642
+ if d.open:
643
+ out += [f"**Needs a person ({len(d.open)})**", ""]
644
+ out += [f"- `{line.text}`" for line in d.open]
645
+ out.append("")
646
+ if d.quiet:
647
+ out += [f"**Changed, nothing to do ({len(d.quiet)})**", ""]
648
+ out += [f"- `{line.text}`" for line in d.quiet]
649
+ out.append("")
650
+ if d.past_a_third:
651
+ out += [f"> {FULL_LOOP[0].upper()}{FULL_LOOP[1:]}.", ""]
652
+ head_short = d.head[:7] or d.head_ref
653
+ base_short = d.base[:7] or d.base_ref
654
+ if figure:
655
+ out += [f"![the map at {head_short}]({figure})", ""]
656
+ out.append(
657
+ f"The committed map at `{head_short}`; the change map itself is "
658
+ f"`systemap figure --mode change --base {base_short} --out change.svg`."
659
+ )
660
+ else:
661
+ out.append(
662
+ f"No committed figure to show at `{head_short}`; the change map is "
663
+ f"`systemap figure --mode change --base {base_short} --out change.svg`."
664
+ )
665
+ if d.open:
666
+ out.append(f"Act on each line, then run `{NEXT}`.")
667
+ else:
668
+ out.append("Nothing needs a person; `systemap refresh` brings the facts up to date.")
669
+ out.append("")
670
+ return "\n".join(out)