apiref.py¶
clew/wiki/apiref.py
The public-API reference: one page per declared public header, from the index (PAPI, 2.0.0).
api_html
str clew.wiki.apiref.api_html(str rel, list[Symbol] symbols, list[ClassInfo] classes=())
One header's reference page body.
Source · 34 lines
def api_html(rel: str, symbols: list[Symbol], classes: list[ClassInfo] = ()) -> str:
"""CLASS MEMBERS GO UNDER THEIR CLASS (a symbol whose scope names a class declared here); the
rest by kind; enum values under their enum.
@brief Render a header.
@return HTML.
"""
class_names = {c.name for c in classes} | {
s.scope for s in symbols if s.scope and s.kind != "enumvalue" and "::" in s.scope
}
top = [s for s in symbols if s.scope not in class_names and s.kind != "enumvalue"]
values = {}
for s in symbols:
if s.kind == "enumvalue":
values.setdefault(s.scope, []).append(s)
parts = [f'<p class="where"><code>{escape(rel)}</code></p>']
for kind, heading in _SECTIONS:
items = [s for s in top if s.kind == kind]
if items:
parts.append(f"<h2>{heading}</h2>" + "".join(_entry(s, values) for s in items))
info = {c.name: c for c in classes}
for scope in sorted(class_names):
members = [s for s in symbols if s.scope == scope]
if not members and scope not in info:
continue
c = info.get(scope)
brief = f"<p>{escape(c.brief)}</p>" if c and c.brief else ""
parts.append(
f'<h2 class="api-class" id="api-{escape(scope)}"><code>{escape(scope)}</code></h2>'
f"{brief}{_hierarchy(c)}" + "".join(_entry(s, values) for s in members)
)
return "".join(parts)
Activity · 20 steps
Requirements
api_pages
str clew.wiki.apiref.api_pages(Path db, tuple[str,...] globs, Path source, tuple[str,...] tags=())
Write the API tab: an index of headers and a page per header.
Source · 49 lines
def api_pages(db: Path, globs: tuple[str, ...], source: Path, tags: tuple[str, ...] = ()) -> str:
"""@brief Write api.md and api-*.md. @return Page name or ""."""
import re
from ..query._common import connect
with connect(db) as conn:
headers = header_symbols(conn, globs, tags)
classes = {
rel: header_classes(conn, rel, {s.scope for s in syms if s.scope})
for rel, syms in headers.items()
}
if not headers:
return ""
items = []
for rel, symbols in headers.items():
name = "api-" + re.sub(r"[^A-Za-z0-9]+", "-", rel).strip("-")
text = [
"---",
"orphan: true",
"---",
"",
f"# {rel}",
"",
"```{raw} html",
'<p class="crumbs"><a href="api.html">← API</a></p>',
api_html(rel, symbols, classes[rel]),
"```",
"",
]
(Path(source) / f"{name}.md").write_text("\n".join(text), encoding="utf-8")
items.append(
f'<li><a href="{name}.html"><code>{escape(rel)}</code></a> · {len(symbols)} symbols</li>'
)
index = [
"# API",
"",
f"The public API: {len(headers)} declared public headers (`wiki.api`), from the index. "
"Private members and `\\internal`-documented symbols are left out.",
"",
"```{raw} html",
f'<ul class="api-headers">{"".join(items)}</ul>',
"```",
"",
]
(Path(source) / "api.md").write_text("\n".join(index), encoding="utf-8")
return "api"
Activity · 16 steps
Requirements
doc_text
str clew.wiki.apiref.doc_text(str xml)
A doc comment's prose: doxygen XML removed, and the guard's traceability tags with it.
Source · 21 lines
def doc_text(xml: str) -> str:
"""FOUND ON ENTROPIC'S INDEX: `@req REQ-TYPE-002` and the `@version` simplesect read as API
prose. Traceability belongs to the requirement pages; an API reader gets the description.
@brief Clean a description.
@return Text.
"""
import xml.etree.ElementTree as ET
from ..query._common import strip_xml
## ENTROPIC'S AUDIT OF f6ff1f7c: a regex tag-strip ate `< 2)` and `<bool>` — code text doxygen
## stored verbatim. Parsed after `_well_formed`, so text stays text; the strip is the fallback.
source = _VERSION_SECT.sub("", xml or "")
try:
text = " ".join(ET.fromstring(f"<root>{_well_formed(source)}</root>").itertext())
except ET.ParseError:
text = strip_xml(source)
return " ".join(_GUARD_TAG.sub("", text).split())
Activity · 8 steps
Requirements
header_symbols
dict[str, list[Symbol]] clew.wiki.apiref.header_symbols(Any conn, tuple[str,...] globs, tuple[str,...] tags=())
Each declared public header's public symbols, from the index.
Called by api_pages
Tested by
Source · 43 lines
def header_symbols(
conn: Any, globs: tuple[str, ...], tags: tuple[str, ...] = ()
) -> dict[str, list[Symbol]]:
"""@brief Read the API. @return Symbols by header."""
if not globs:
return {}
out: dict[str, list[Symbol]] = {}
for rowid, rel in conn.execute("SELECT rowid, name FROM path WHERE type = 1 ORDER BY name"):
if not any(fnmatch.fnmatch(rel, g) for g in globs):
continue
rows = conn.execute(
"SELECT kind, name, COALESCE(scope, ''), COALESCE(definition, ''), "
"COALESCE(argsstring, ''), COALESCE(initializer, ''), COALESCE(briefdescription, ''), "
"COALESCE(detaileddescription, ''), line, COALESCE(type, '') FROM memberdef "
"WHERE file_id = ? AND COALESCE(prot, 0) = ? ORDER BY line",
(rowid, _PUBLIC),
)
symbols = []
for kind, name, scope, definition, args, value, brief, detail, line, type_ in rows:
if "<internal>" in detail:
continue
doc = parse_doc(detail, tags)
if kind == "function":
doc = _with_definition(conn, doc, name, scope, rowid, tags)
sig = _signature(kind, definition, args, type_, name)
symbols.append(
Symbol(
kind,
name,
scope,
sig,
doc_text(brief),
doc.prose,
int(line or 0),
value.strip(),
doc,
)
)
if symbols:
out[str(rel)] = symbols
return out
Activity · 19 steps
Requirements
parse_doc
Doc clew.wiki.apiref.parse_doc(str xml, tuple[str,...] tags=())
Parse doxygen's description XML into labelled parts (entropic's gaps 1 and 2).
Called by _with_definition, header_symbols
Tested by 7 tests
test_a_declared_tag_inside_a_return_or_param_is_split_out, test_a_declared_tag_is_a_labelled_field, test_a_return_repeated_inside_a_longer_one_is_shown_once, test_code_text_doxygen_stored_verbatim_is_kept_and_structured, test_params_returns_and_retvals_are_structured, test_the_entry_renders_labelled_lists, test_throws_are_rendered
Calls _distinct, _drop, _fields, _flat, doc_text
Source · 50 lines
def parse_doc(xml: str, tags: tuple[str, ...] = ()) -> Doc:
"""Doxygen stores parameters, the return and return values as `<parameterlist>` and
`<simplesect kind="return">`; they are read as structure rather than flattened into prose. A
declaration's block and its definition's often repeat the return: identical ones collapse. A
fragment that will not parse falls back to the flat text, never to nothing.
@brief Structure a description.
@return Doc.
"""
import xml.etree.ElementTree as ET
try:
root = ET.fromstring(f"<root>{_well_formed(xml)}</root>")
except ET.ParseError:
return Doc(prose=doc_text(xml))
params: list[tuple[str, str, str]] = []
retvals: list[tuple[str, str]] = []
throws: list[tuple[str, str]] = []
found: list[tuple[str, str]] = []
## ENTROPIC'S AUDIT (33 cases): with no ALIASES, doxygen runs a declared `@threadsafety` into
## the paragraph before it — a parameter's or the return's — so every part is split too.
def split(text: str) -> str:
clean, fields = _fields(text, tags)
found.extend(fields)
return clean
for plist in root.iter("parameterlist"):
bucket = {"retval": retvals, "exception": throws}.get(plist.get("kind", ""))
for item in plist.iter("parameteritem"):
text = split(_flat(item.find("parameterdescription")))
for name in item.iter("parametername"):
label = "".join(name.itertext()).strip()
if bucket is None:
params.append((label, name.get("direction", ""), text))
else:
bucket.append((label, text))
returns = [split(_flat(s)) for s in root.iter("simplesect") if s.get("kind") == "return"]
_drop(root, {"parameterlist", "simplesect"})
prose = split(" ".join("".join(root.itertext()).split()))
return Doc(
prose=prose,
params=tuple(dict.fromkeys(params)),
returns=_distinct(returns),
retvals=tuple(dict.fromkeys(retvals)),
fields=tuple(dict.fromkeys(found)),
throws=tuple(dict.fromkeys(throws)),
)