Repository navigation
Expand file tree
/
Copy pathgen_coverage.py
More file actions
901 lines (787 loc) · 36.6 KB
/
Copy pathgen_coverage.py
File metadata and controls
901 lines (787 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
#!/usr/bin/env python
"""Generate README's Coverage section from the live code (a reproducible artifact).
Introspects the domain clients **offline** (dummy credentials — constructing a client
opens no connection) plus the committed public-surface data (the CLI
tree from :func:`tests.snapshots._surface.cli_tree` and the tool names in the MCP signature
snapshot ``tests/snapshots/mcp_signatures.txt``) and emits the Markdown block README embeds
between its ``COVERAGE:START`` / ``COVERAGE:END`` markers; README.ru.md gets a short Russian
block between the same markers, with the totals and a link to the English tables.
Below the tables it prints how ycli differs from the API Yandex publishes (operations it does
not wrap, query parameters it cannot send, response fields its models drop), computed by
``scripts/api_drift.py`` from the committed snapshots under ``scripts/api_snapshot/``.
Per resource it reports the wrapped SDK operations (public methods on the resource client
class, in source order) and whether that resource is reachable via the CLI and via at least
one MCP tool. MCP mirrors the SDK with honest annotations (ARCH-3): reads carry
``readOnlyHint``, writes carry explicit destructive/idempotent hints; a resource with no MCP
tool yet shows ``—`` in the MCP column.
Usage::
python scripts/gen_coverage.py # print the block to stdout
python scripts/gen_coverage.py --write # splice it into both READMEs, write the SVG
python scripts/gen_coverage.py --check # exit 1 if a README block or the SVG is stale
``--check`` powers ``tests/docs/test_coverage_readme.py`` so the tables can never silently drift
from the code.
"""
from __future__ import annotations
import argparse
import inspect
import sys
import tomllib
from dataclasses import dataclass
from functools import cache
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Mapping
ROOT = Path(__file__).resolve().parent.parent
# Run as a file, a script sees only its own directory: tests/ and scripts/ hang off the root.
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from scripts import api_drift, api_surface # noqa: E402
from tests.snapshots._surface import cli_tree # noqa: E402
from ycli.yandex.core.resource import Resource # noqa: E402
from ycli.yandex.datalens.client import DataLensClient # noqa: E402
from ycli.yandex.forms.client import FormsClient # noqa: E402
from ycli.yandex.tracker.client import TrackerClient # noqa: E402
from ycli.yandex.wiki.client import WikiClient # noqa: E402
README = ROOT / "README.md"
README_RU = ROOT / "README.ru.md"
MCP_SIGNATURES = ROOT / "tests" / "snapshots" / "mcp_signatures.txt"
# Committed map of resource/operation → public Yandex API-reference page (relative paths).
# The vendored api-ref under references/ is git-ignored, so the links live here, not there.
COVERAGE_URLS = ROOT / "scripts" / "coverage_urls.toml"
# Tracker moved its reference from `api-ref/` to `api/` (the old URLs answer 301); Wiki and
# Forms still serve `api-ref/`. DataLens is documented with Yandex Cloud, a page an operation
# in a directory a section; the snapshot holds each operation's page (`_snapshot_links`).
API_DOCS = {
"tracker": "https://yandex.ru/support/tracker/en/api/{path}",
"wiki": "https://yandex.ru/support/wiki/en/api-ref/{path}",
"forms": "https://yandex.ru/support/forms/en/api-ref/{path}",
"datalens": "https://yandex.cloud/en/docs/datalens/api-ref/{path}",
}
# A service as a heading names it, and as the Russian README does (nominative, genitive).
TITLES = {
"tracker": ("Tracker", "Трекер", "Трекера"),
"wiki": ("Wiki", "Вики", "Вики"),
"forms": ("Forms", "Формы", "Форм"),
"datalens": ("DataLens", "DataLens", "DataLens"),
}
# The character, not a `:shortcode:`: the site would load a shortcode as an image from a CDN.
EMOJI = {
"tracker": "📋",
"wiki": "📖",
"forms": "📝",
"datalens": "📊",
}
# What a service is, in one line, on the Russian site; the English line is `Service.help`.
SUMMARIES_RU = {
"tracker": "Задачи, очереди, доски, спринты, поля, автоматизация.",
"wiki": "Страницы, динамические таблицы, комментарии, вложения.",
"forms": "Опросы, вопросы, ответы, публикация.",
"datalens": "Воркбуки, подключения, датасеты, чарты, дашборды.",
}
# The preview README shows above the tables, regenerated with them.
COVERAGE_SVG = ROOT / "docs" / "assets" / "coverage.svg"
COVERAGE_SVG_URL = "https://raw.githubusercontent.com/bim-ba/ycli/main/docs/assets/coverage.svg"
START = "<!-- COVERAGE:START (generated by scripts/gen_coverage.py — do not edit by hand) -->"
END = "<!-- COVERAGE:END -->"
YES = "✅"
NO = "—"
# The state of an operation against the published API: no mark means covered.
PARTIAL = "◐"
NOT_COVERED = "○"
# Per-domain category → resource-attribute grouping. Every resource on a client must appear
# in exactly one group; a resource that is missing here lands in a trailing "Other" group so
# the omission is visible rather than silently dropped.
TRACKER_CATEGORIES: list[tuple[str, list[str]]] = [
(
"Issues & work items",
[
"issues",
"comments",
"links",
"transitions",
"worklog",
"changelog",
"checklists",
"attachments",
"remotelinks",
],
),
("Agile boards", ["boards", "sprints", "columns"]),
("Dictionaries", ["priorities", "statuses", "resolutions", "issuetypes", "linktypes"]),
(
"Fields, queues & structure",
["fields", "localfields", "components", "queues", "workflows", "projects"],
),
("Automation & bulk", ["macros", "triggers", "autoactions", "dashboards", "bulk"]),
("Entities, users & search", ["entities", "users", "applications", "filters", "gaps", "me"]),
]
WIKI_CATEGORIES: list[tuple[str, list[str]]] = [
("Pages", ["pages", "resources", "recovery"]),
("Collaboration", ["comments", "attachments", "access"]),
("Grids (dynamic tables)", ["grids"]),
("Async & uploads", ["operations", "uploadsessions"]),
("Identity", ["me"]),
]
FORMS_CATEGORIES: list[tuple[str, list[str]]] = [
("Surveys & questions", ["surveys", "questions", "conditions", "access", "history"]),
("Responses & export", ["answers", "operations"]),
("Integrations", ["hooks", "subscriptions", "variables", "notifications"]),
("Distribution", ["keysets", "filling"]),
("Media", ["files", "images"]),
("Identity", ["me"]),
]
DATALENS_CATEGORIES: list[tuple[str, list[str]]] = [
("Organization", ["tenant", "members", "licensing"]),
(
"Collections & workbooks",
["collections", "workbooks", "workbookexports", "workbookimports"],
),
("Entries", ["entries", "entrylocks", "permissions", "sharedentries", "audit"]),
("Data", ["connections", "datasets"]),
(
"Charts, dashboards, reports & pages",
["charts", "dashboards", "reports", "htmlpages"],
),
("SQL", ["sqlqueries"]),
(
"Cloud environments",
[
"cloudenvironments",
"cloudenvironmentstorage",
"restcatalogs",
"lakehouseoperations",
"trinoclusters",
"sparkclusters",
"sparkapplications",
],
),
("Embedding", ["embeds", "embeddingsecrets"]),
]
@dataclass(frozen=True)
class DomainSpec:
"""One domain to document: its heading, CLI/MCP namespace slug, live client, and groups."""
title: str
slug: str
client: object
categories: list[tuple[str, list[str]]]
@dataclass(frozen=True)
class ResourceRow:
"""A single table row: a resource, its wrapped ops, and per-surface reachability.
``resource_url`` links the resource name (``None`` → plain text). ``operation_urls`` is
the final link target per operation — its own endpoint page, else the resource page as a
fallback, else ``None`` (plain text). ``operation_specific[i]`` is ``True`` when operation
``i`` had a dedicated page (vs. falling back to the resource link); it drives the gap stats.
``operation_gaps[i]`` is the anchor of the row that says how operation ``i`` differs from
the published API, or ``None`` when it does not (the operation is covered).
"""
display: str
operations: tuple[str, ...]
has_cli: bool
has_mcp: bool
resource_url: str | None
operation_urls: tuple[str | None, ...]
operation_specific: tuple[bool, ...]
operation_gaps: tuple[str | None, ...] = ()
@dataclass(frozen=True)
class DomainReport:
"""A rendered domain: its category groups (each a list of rows) plus headline totals."""
title: str
slug: str
groups: list[tuple[str, list[ResourceRow]]]
resource_count: int
operation_count: int
mcp_tool_count: int
@dataclass(frozen=True)
class LinkStats:
"""How the doc-link map covers the tables, and which items have no public link at all.
``gaps`` lists the ``<domain>.<resource>[.<operation>]`` identifiers rendered as plain text
(no known URL) so the shortfall is explicit, not silent.
"""
resources: int
linked_resources: int
operations: int
specific_ops: int
fallback_ops: int
plain_ops: int
gaps: tuple[str, ...]
def _cli_paths() -> list[str]:
"""Every CLI command path (space-joined), via the shared surface enumerator."""
return cli_tree()
def _mcp_tool_names() -> list[str]:
"""Every MCP tool name, from the committed signature snapshot (``name(params)`` lines)."""
lines = MCP_SIGNATURES.read_text(encoding="utf-8").splitlines()
return [line.split("(", 1)[0] for line in lines]
def _display_name(attribute: str) -> str:
"""Resource attribute → its CLI/MCP/display name (``import_`` → ``import``)."""
return attribute[:-1] if attribute.endswith("_") else attribute
def _sdk_operations(resource: object) -> tuple[str, ...]:
"""Public op names defined on the resource client class itself, in source order.
Dunder and leading-underscore internals do not count.
"""
ops: list[str] = []
for name, member in type(resource).__dict__.items():
if name.startswith("_"):
continue
if inspect.isfunction(member):
ops.append(name)
return tuple(ops)
def _cli_ops(slug: str, display: str, paths: list[str]) -> list[str]:
"""CLI sub-command remainders under ``<slug> <display>`` (segment-exact prefix match)."""
prefix = [slug, display]
return [" ".join(s[2:]) for path in paths if (s := path.split())[:2] == prefix and len(s) > 2]
def _mcp_tools(slug: str, display: str, tools: list[str]) -> list[str]:
"""MCP tool names under the ``<slug>_<display>_`` namespace."""
prefix = f"{slug}_{display}_"
return [tool for tool in tools if tool.startswith(prefix)]
def _snapshot_links(service: str) -> dict[str, dict]:
"""The link map of a service whose snapshot holds each operation's reference page.
An SDK operation links to the page of the operation it sends; its resource links to the
section those pages lie in. An operation without a page stays plain text.
"""
pages = {found.path: found.page for found in api_surface.load(service) if found.page}
links: dict[str, dict] = {}
for call in api_drift.calls():
domain, resource, operation = call.operation.split(".")
page = pages.get(call.path)
if domain == service and page:
entry = links.setdefault(_display_name(resource), {"operations": {}})
entry["operations"][operation] = page
entry["resource"] = page.rpartition("/")[0] + "/"
return links
def _load_link_map() -> dict[str, dict[str, dict]]:
"""The doc-link map, keyed ``domain → resource → {resource, operations}``.
Committed for the services whose pages are found by hand (``coverage_urls.toml``); read
from the snapshot for DataLens, whose refresh lists the pages there are.
"""
committed = tomllib.loads(COVERAGE_URLS.read_text(encoding="utf-8"))
return {**committed, "datalens": _snapshot_links("datalens")}
def _doc_url(slug: str, path: str) -> str:
"""A relative api-ref ``path`` → its absolute public Yandex documentation URL."""
return API_DOCS[slug].format(path=path)
def _link(text: str, url: str | None) -> str:
"""``text`` as a Markdown link to ``url``, or bare ``text`` when there is no URL."""
return f"[{text}]({url})" if url else text
def _make_row(
slug: str,
attribute: str,
resource: object,
urls: dict[str, dict],
paths: list[str],
tools: list[str],
gaps: Mapping[str, str],
) -> ResourceRow:
"""Assemble one :class:`ResourceRow`, resolving each op to its page / resource / plain text."""
display = _display_name(attribute)
operations = _sdk_operations(resource)
entry = urls.get(display, {})
resource_path = entry.get("resource")
operation_paths = entry.get("operations", {})
operation_urls: list[str | None] = []
operation_specific: list[bool] = []
for operation in operations:
own = operation_paths.get(operation)
operation_specific.append(own is not None)
target = own or resource_path
operation_urls.append(_doc_url(slug, target) if target else None)
return ResourceRow(
display=display,
operations=operations,
has_cli=bool(_cli_ops(slug, display, paths)),
has_mcp=bool(_mcp_tools(slug, display, tools)),
resource_url=_doc_url(slug, resource_path) if resource_path else None,
operation_urls=tuple(operation_urls),
operation_specific=tuple(operation_specific),
operation_gaps=tuple(gaps.get(f"{slug}.{attribute}.{name}") for name in operations),
)
def _report(
spec: DomainSpec,
paths: list[str],
tools: list[str],
urls: dict[str, dict],
gaps: Mapping[str, str],
) -> DomainReport:
"""Build a fully-computed :class:`DomainReport` from a live client + surface + link data."""
discovered = {name for name, value in vars(spec.client).items() if isinstance(value, Resource)}
placed: set[str] = set()
groups: list[tuple[str, list[ResourceRow]]] = []
operation_count = 0
for heading, attributes in spec.categories:
rows: list[ResourceRow] = []
for attribute in attributes:
resource = getattr(spec.client, attribute)
if not isinstance(resource, Resource):
raise SystemExit(f"gen_coverage: {spec.slug}.{attribute} is not a resource client")
placed.add(attribute)
row = _make_row(spec.slug, attribute, resource, urls, paths, tools, gaps)
if not row.operations:
raise SystemExit(f"gen_coverage: {spec.slug}.{attribute} exposes no SDK operations")
operation_count += len(row.operations)
rows.append(row)
groups.append((heading, rows))
unplaced = sorted(discovered - placed)
if unplaced:
rows = []
for attribute in unplaced:
resource = getattr(spec.client, attribute)
row = _make_row(spec.slug, attribute, resource, urls, paths, tools, gaps)
operation_count += len(row.operations)
rows.append(row)
groups.append(("Other", rows))
return DomainReport(
title=spec.title,
slug=spec.slug,
groups=groups,
resource_count=len(discovered),
operation_count=operation_count,
mcp_tool_count=sum(1 for tool in tools if tool.startswith(f"{spec.slug}_")),
)
def link_stats(reports: list[DomainReport]) -> LinkStats:
"""Aggregate doc-link coverage across ``reports`` (own page vs. resource fallback vs. none)."""
resources = linked_resources = 0
operations = specific = fallback = plain = 0
gaps: list[str] = []
for report in reports:
for _heading, rows in report.groups:
for row in rows:
resources += 1
identifier = f"{report.slug}.{row.display}"
if row.resource_url:
linked_resources += 1
else:
gaps.append(identifier)
for operation, url, own in zip(
row.operations, row.operation_urls, row.operation_specific, strict=True
):
operations += 1
if own:
specific += 1
elif url:
fallback += 1
else:
plain += 1
gaps.append(f"{identifier}.{operation}")
return LinkStats(
resources=resources,
linked_resources=linked_resources,
operations=operations,
specific_ops=specific,
fallback_ops=fallback,
plain_ops=plain,
gaps=tuple(sorted(gaps)),
)
def _render_table(rows: list[ResourceRow]) -> list[str]:
"""The Markdown lines for one resource-group table.
Every row comes from an SDK resource, so the table has no SDK column: it would always be
ticked.
"""
lines = [
"| Resource | Operations | CLI | MCP |",
"|----------|------------|:---:|:---:|",
]
for row in rows:
gaps = row.operation_gaps or (None,) * len(row.operations)
cells = zip(row.operations, row.operation_urls, gaps, strict=True)
operations = " · ".join(
_link(operation, url) + (f" [{PARTIAL}](#{gap})" if gap else "")
for operation, url, gap in cells
)
cli = YES if row.has_cli else NO
mcp = YES if row.has_mcp else NO
lines.append(f"| {_link(row.display, row.resource_url)} | {operations} | {cli} | {mcp} |")
return lines
@dataclass(frozen=True)
class Totals:
"""The headline numbers: operations, resources and every registered MCP tool."""
operations: int
resources: int
mcp_tools: int
domain_mcp_tools: int
cross_cutting_tools: tuple[str, ...]
def _totals(reports: list[DomainReport]) -> Totals:
"""Sum the domains, adding the MCP tools that belong to no domain (``status_get``)."""
domain_prefixes = tuple(f"{report.slug}_" for report in reports)
cross_cutting = tuple(
tool for tool in _mcp_tool_names() if not tool.startswith(domain_prefixes)
)
domain_mcp_tools = sum(report.mcp_tool_count for report in reports)
return Totals(
operations=sum(report.operation_count for report in reports),
resources=sum(report.resource_count for report in reports),
mcp_tools=domain_mcp_tools + len(cross_cutting),
domain_mcp_tools=domain_mcp_tools,
cross_cutting_tools=cross_cutting,
)
def _listed(names: list[str]) -> str:
"""``["Tracker", "Wiki", "Forms"]`` -> ``"Tracker, Wiki, and Forms"``."""
return ", ".join(names[:-1]) + f", and {names[-1]}"
def _render_not_covered(drift: api_drift.Drift) -> list[str]:
"""The published operations of a service that ycli does not wrap, each with its reason."""
reasons = dict(drift.excluded)
missing = [*drift.not_wrapped, *reasons]
if not missing:
return []
lines = ["", f"**Not covered** ({len(missing)})", ""]
for operation in missing:
why = reasons.get(operation)
published = _published(drift.service, operation)
lines.append(f"- {NOT_COVERED} {published}" + (f": {why}" if why else ""))
return lines
def _render(reports: list[DomainReport], found: tuple[api_drift.Drift, ...]) -> str:
"""The full inner Markdown block (without the surrounding markers)."""
drifts = {drift.service: drift for drift in found}
totals = _totals(reports)
cross_cutting_names = ", ".join(f"`{tool}`" for tool in sorted(totals.cross_cutting_tools))
stats = link_stats(reports)
lines = [
"## Coverage",
"",
f'<img src="{COVERAGE_SVG_URL}" alt="{totals.operations} operations across '
f"{totals.resources} resources: "
+ ", ".join(f"{report.title} {report.operation_count}" for report in reports)
+ '" width="760">',
"",
f"`ycli` wraps **{totals.operations} operations across {totals.resources} resources** of "
f"the {_listed([report.title for report in reports])} API. Every one is reachable "
"from the **Python SDK** "
f"and the **CLI**, and {totals.mcp_tools} **MCP** tools serve them to agents "
f"({totals.domain_mcp_tools} per service plus {cross_cutting_names}).",
"",
f"> **Legend.** {YES} in **CLI** or **MCP** means the resource is reachable on that "
"surface; MCP tools carry honest hints (reads are `readOnlyHint`, writes say whether "
"they are destructive or idempotent), and `ycli mcp start --read-only` serves only the "
"reads. Resource and operation names link to the official **Yandex API reference**. "
"An operation has one of three states against what Yandex publishes. **Covered** (no "
"mark): ycli sends every published parameter and reads every published field. "
f"**Partial** ({PARTIAL}): ycli wraps it and differs somewhere; the mark links to the "
f"row that says where and why. **Not covered** ({NOT_COVERED}): Yandex publishes it "
"and ycli does not wrap it; these are listed under each service. Wiki, Forms and "
"DataLens are measured against their OpenAPI documents; Tracker publishes none, so "
"its state is measured against the reference pages (operations, and query parameters "
"where a page lists them). DataLens is in progress, wrapped section by section: the "
"operations of a section ycli has not begun are pending, not missing. Generated from "
"the code by "
"[`scripts/gen_coverage.py`](scripts/gen_coverage.py); do not edit by hand.",
]
for report in reports:
lines += [
"",
f"### {report.title}",
"",
"<details>",
f"<summary><b>{report.resource_count} resources · {report.operation_count} "
f"operations · {report.mcp_tool_count} MCP tools</b></summary>",
]
for heading, rows in report.groups:
lines += ["", f"**{heading}**", "", *_render_table(rows)]
lines += [*_render_not_covered(drifts[report.slug]), "", "</details>"]
gaps = ", ".join(f"`{gap}`" for gap in stats.gaps)
unlinked = (
f" No public API reference exists yet for {gaps}, shown as plain text."
if stats.gaps
else ""
)
lines += [
"",
f"Every resource and operation above deep-links to the Yandex API reference: "
f"{stats.specific_ops} of {stats.operations} operations resolve to their own endpoint "
f"page and {stats.fallback_ops} to their resource's page.{unlinked} "
"See `CONTRIBUTING.md` for the intentional exclusions (UI-only endpoints with no public "
"REST API) and per-method notes.",
]
return "\n".join([*lines, "", *_render_drift(found)])
@cache
def api_drifts() -> tuple[api_drift.Drift, ...]:
"""Every service's differences from its published API (replays the contract cases once)."""
return tuple(api_drift.drifts())
PUBLISHED = {
"tracker": "[API reference](https://yandex.ru/support/tracker/en/api/about-api)",
"wiki": f"[OpenAPI]({api_surface.OPENAPI_URLS['wiki']})",
"forms": f"[OpenAPI]({api_surface.OPENAPI_URLS['forms']})",
"datalens": f"[OpenAPI]({api_surface.SOURCES['datalens'].url})",
}
# Where the page of a published operation lies, for the services whose snapshot names it.
REFERENCE = {
"tracker": "https://yandex.ru/support/tracker/en/",
"datalens": API_DOCS["datalens"].format(path=""),
}
# How each kind of difference reads in the table, in the order they are listed.
DIFFERENCES = {
"missing_query": "query parameters ycli cannot send",
"unknown_query": "query parameters ycli sends that are not published",
"missing_request": "body fields ycli cannot send",
"unknown_request": "body fields ycli sends that are not published",
"untyped_response": "response fields ycli passes through untyped",
"unknown_response": "model fields that are not published",
}
def _names(names: tuple[str, ...]) -> str:
return ", ".join(f"`{name}`" for name in names)
def _published(service: str, operation: api_surface.Operation) -> str:
"""A published operation as ``METHOD /path``, linked to its reference page if it has one."""
label = f"`{operation.method} {operation.path}`"
return _link(label, REFERENCE[service] + operation.page if operation.page else None)
def _sdk(operations: tuple[str, ...]) -> str:
"""SDK operations without their service: ``wiki.pages.get`` → ``pages.get``."""
return ", ".join(f"`{operation.split('.', 1)[1]}`" for operation in operations)
def _bodies(drift: api_drift.Drift) -> str:
"""How many published request bodies were compared: the rest have no typed model in ycli."""
if not drift.bodies_published:
return NO
return f"{drift.bodies_compared} of {drift.bodies_published}"
def _render_drift(drifts: tuple[api_drift.Drift, ...]) -> list[str]:
"""The "Against the published API" section: a summary row and the details per service."""
lines = [
"### Against the published API",
"",
"What ycli sends, replayed from its contract tests, compared with what Yandex publishes: "
"the Wiki, Forms and DataLens OpenAPI documents and Tracker's API reference (prose, so "
"only operations and the query parameters a page lists are compared). A request body is "
"compared only where ycli has a typed model for it and the model is closed; the "
"**Bodies compared** column says how many that is, so an empty list is not read as "
"a match. The published side is "
"the snapshot in [`scripts/api_snapshot/`](scripts/api_snapshot); a "
"[weekly job](.github/workflows/api-drift.yml) fetches it again and opens an issue when "
"Yandex has changed it.",
"",
"| Service | Published | Wrapped | Not wrapped | Operations that differ | "
"Bodies compared | Source |",
"|---------|:---------:|:-------:|:-----------:|:----------------------:|"
":---------------:|--------|",
]
for drift in drifts:
excluded = f" (+{len(drift.excluded)} on purpose)" if drift.excluded else ""
pending = f" (+{len(drift.pending)} pending)" if drift.pending else ""
lines.append(
f"| {TITLES[drift.service][0]} | {len(drift.published)} | {drift.wrapped} | "
f"{len(drift.not_wrapped)}{excluded}{pending} | {len(drift.gaps)} | "
f"{_bodies(drift)} | "
f"{PUBLISHED[drift.service]} |"
)
for drift in drifts:
lines += [
"",
"<details>",
f"<summary><b>{TITLES[drift.service][0]}: what differs</b></summary>",
]
if drift.not_wrapped:
lines += ["", "**Published, not wrapped**", ""]
lines += [
f"- {_published(drift.service, operation)}" for operation in drift.not_wrapped
]
if drift.excluded:
lines += ["", "**Not wrapped on purpose**", "", "| Operation | Why |", "|---|---|"]
lines += [
f"| {_published(drift.service, operation)} | {why} |"
for operation, why in drift.excluded
]
if drift.unpublished:
lines += [
"",
"**Sent by ycli, not published**",
"",
"| ycli | Its request |",
"|---|---|",
]
lines += [
f"| {_sdk((call.operation,))} | `{call.method} {call.template}` |"
for call in drift.unpublished
]
if drift.gaps:
lines += [
"",
"**Parameters and fields**",
"",
"| Operation | ycli | Difference | Why it stays |",
"|---|---|---|---|",
]
for gap in drift.gaps:
differences = "<br>".join(
f"{label}: {_names(getattr(gap, kind))}"
for kind, label in DIFFERENCES.items()
if getattr(gap, kind)
)
why = "<br>".join(api_drift.reasons(drift.service, gap))
anchor = f'<a id="{api_drift.anchor(drift.service, gap)}"></a>'
lines.append(
f"| {anchor}{_published(drift.service, gap.published)} "
f"| {_sdk(gap.operations)} "
f"| {differences} | {why} |"
)
lines += ["", "</details>"]
return lines
# The preview's geometry and colours. It is shown through <img>, so it has no script, no web
# font and no page theme; a media query would follow the operating system, not GitHub's theme,
# and paint light text on a light page when the two differ. Mid-tones read on both surfaces
# (text about 4.2:1 on white and 4.5:1 on GitHub's dark background).
_SVG_WIDTH = 760
_SVG_FONT = (
"-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif"
)
_SVG_STYLE = ".value{fill:#768390}.label{fill:#768390}.bar{fill:#3987e5}"
_BAR_X = 90
_BAR_MAX = 420
_BAR_HEIGHT = 22
_BAR_GAP = 14
_BARS_TOP = 112
def _bar_path(x: float, y: float, width: float, height: float, radius: float = 4) -> str:
"""A bar anchored at ``x`` with only its data end (the right side) rounded."""
radius = min(radius, width / 2)
right = x + width
return (
f"M{x:g},{y:g}H{right - radius:g}Q{right:g},{y:g} {right:g},{y + radius:g}"
f"V{y + height - radius:g}Q{right:g},{y + height:g} {right - radius:g},{y + height:g}"
f"H{x:g}Z"
)
def render_svg(reports: list[DomainReport]) -> str:
"""The coverage preview: three headline numbers, then one bar of operations per service."""
totals = _totals(reports)
tiles = [
(totals.operations, "operations"),
(totals.resources, "resources"),
(totals.mcp_tools, "MCP tools"),
]
height = _BARS_TOP + len(reports) * (_BAR_HEIGHT + _BAR_GAP)
widest = max(report.operation_count for report in reports)
parts = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{_SVG_WIDTH}" height="{height}" '
f'viewBox="0 0 {_SVG_WIDTH} {height}" font-family="{_SVG_FONT}" role="img" '
'aria-labelledby="title">',
f'<title id="title">ycli wraps {totals.operations} operations across '
f"{totals.resources} resources</title>",
f"<style>{_SVG_STYLE}</style>",
]
tile_width = _SVG_WIDTH / len(tiles)
for index, (value, label) in enumerate(tiles):
x = index * tile_width
parts += [
f'<text class="value" x="{x:g}" y="40" font-size="36" font-weight="600">{value}</text>',
f'<text class="label" x="{x:g}" y="66" font-size="15">{label}</text>',
]
for index, report in enumerate(reports):
y = _BARS_TOP + index * (_BAR_HEIGHT + _BAR_GAP)
width = _BAR_MAX * report.operation_count / widest
middle = y + _BAR_HEIGHT / 2 + 5
parts += [
f'<text class="value" x="0" y="{middle:g}" font-size="15" font-weight="600">'
f"{report.title}</text>",
f'<path class="bar" d="{_bar_path(_BAR_X, y, width, _BAR_HEIGHT)}"/>',
f'<text class="label" x="{_BAR_X + width + 10:g}" y="{middle:g}" font-size="14">'
f"{report.operation_count} operations · {report.mcp_tool_count} MCP tools</text>",
]
parts.append("</svg>")
return "\n".join(parts) + "\n"
def _reports() -> list[DomainReport]:
"""The per-domain reports, computed from the live clients + committed link map."""
paths = _cli_paths()
tools = _mcp_tool_names()
link_map = _load_link_map()
specs = [
DomainSpec(
"Tracker",
"tracker",
TrackerClient(oauth_token="x", organization_id="x"),
TRACKER_CATEGORIES,
),
DomainSpec(
"Wiki", "wiki", WikiClient(oauth_token="x", organization_id="x"), WIKI_CATEGORIES
),
DomainSpec(
"Forms", "forms", FormsClient(oauth_token="x", organization_id="x"), FORMS_CATEGORIES
),
DomainSpec(
"DataLens",
"datalens",
DataLensClient(oauth_token="x", cloud_organization_id="x"),
DATALENS_CATEGORIES,
),
]
gaps = api_drift.partial(api_drifts())
return [_report(spec, paths, tools, link_map.get(spec.slug, {}), gaps) for spec in specs]
def _render_ru(reports: list[DomainReport]) -> str:
"""The Russian README's short Coverage section: the preview, the totals, the tables link."""
totals = _totals(reports)
services = {slug: names[1] for slug, names in TITLES.items()}
of = [TITLES[report.slug][2] for report in reports]
per_service = ", ".join(
f"{services[report.slug]} — {report.operation_count}" for report in reports
)
return "\n".join(
[
"## Покрытие API",
"",
f'<img src="{COVERAGE_SVG_URL}" alt="Операций: {totals.operations}, ресурсов: '
f'{totals.resources}" width="760">',
"",
f"Операций API {', '.join(of[:-1])} и {of[-1]}: **{totals.operations}** "
f"({per_service}), "
f"ресурсов: **{totals.resources}**; все операции доступны из **Python SDK** и **CLI**. "
f"MCP-инструментов для агентов: **{totals.mcp_tools}**. Таблицы по ресурсам и "
"операциям — в [английском README](README.md#coverage).",
"",
"Из опубликованных Яндексом операций обёрнуто: "
+ ", ".join(
f"{services[drift.service]} — {drift.wrapped} из {len(drift.published)}"
for drift in api_drifts()
)
+ ". Чего ycli пока не умеет (параметры запросов, поля ответов), перечислено в "
"разделе [Against the published API](README.md#against-the-published-api); сверка "
"повторяется каждую неделю.",
]
)
def build_block() -> str:
"""The complete marker-wrapped Coverage block that README embeds."""
return f"{START}\n{_render(_reports(), api_drifts())}\n{END}"
def splice(text: str, block: str) -> str:
"""Return ``text`` with the part between its Coverage markers replaced by ``block``."""
if START not in text or END not in text:
raise SystemExit("gen_coverage: the COVERAGE markers are missing")
return text[: text.index(START)] + block + text[text.index(END) + len(END) :]
def outputs(reports: list[DomainReport]) -> dict[Path, str]:
"""Every generated file's full new text: both READMEs with their block spliced in, the SVG."""
blocks = {README: _render(reports, api_drifts()), README_RU: _render_ru(reports)}
texts = {
path: splice(path.read_text(encoding="utf-8"), f"{START}\n{block}\n{END}")
for path, block in blocks.items()
}
return {**texts, COVERAGE_SVG: render_svg(reports)}
def main(argv: list[str] | None = None) -> int:
"""CLI entry point; see the module docstring for the three modes."""
parser = argparse.ArgumentParser(description="Generate README's Coverage section.")
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--write", action="store_true", help="write both READMEs' blocks and the SVG"
)
group.add_argument(
"--check", action="store_true", help="exit 1 if a README block or the SVG is stale"
)
args = parser.parse_args(argv)
reports = _reports()
if args.write:
for path, text in outputs(reports).items():
path.write_text(text, encoding="utf-8")
return 0
if args.check:
stats = link_stats(reports)
print(
f"gen_coverage links: {stats.specific_ops}/{stats.operations} operations → their own "
f"page, {stats.fallback_ops} → resource page, {stats.plain_ops} plain-text; "
f"{stats.linked_resources}/{stats.resources} resources linked. "
f"Gaps (no public link): {', '.join(stats.gaps) or 'none'}.",
file=sys.stderr,
)
stale = [
path.name
for path, text in outputs(reports).items()
if not path.exists() or path.read_text(encoding="utf-8") != text
]
if stale:
print(
f"stale: {', '.join(stale)}; run: uv run python scripts/gen_coverage.py --write",
file=sys.stderr,
)
return 1
return 0
print(build_block())
return 0
if __name__ == "__main__":
raise SystemExit(main())