exports.py¶
clew/wiki/exports.py
The site's exports: the same trace in other tools' formats (round 3, P3b).
_dot_id
str clew.wiki.exports._dot_id(str text)
A DOT identifier: double-quoted, with quotes and backslashes escaped.
Source · 5 lines
def _dot_id(text: str) -> str:
"""@brief Quote. @return Identifier."""
return '"' + str(text).replace("\\", "\\\\").replace('"', '\\"') + '"'
Activity · 1 steps
Flows
flow_dot
str clew.wiki.exports.flow_dot(Any flow)
A flow as a Graphviz DOT graph: lanes as clusters, steps as numbered edges (S7).
Source · 34 lines
def flow_dot(flow: Any) -> str:
"""DOT IS A GRAPH FORMAT, so a flow is drawn as one: each lane a `cluster_` subgraph, each
function a node in its lane (named `name@file`, so two same-named functions stay two), each step
an edge labelled with its number in call order — the sequence survives as the numbers.
@brief DOT.
@return Text.
"""
nodes: dict[str, tuple[str, str]] = {}
edges = []
for i, step in enumerate(flow.steps, start=1):
if not step.callee:
continue
caller = f"{step.caller}@{step.site_file or step.file}"
callee = f"{step.callee}@{step.file}"
nodes.setdefault(caller, (step.caller, step.from_lane))
nodes.setdefault(callee, (step.callee, step.to_lane))
edges.append(f' {_dot_id(caller)} -> {_dot_id(callee)} [label="{i}"];')
lanes: dict[str, list[str]] = {}
for node, (_name, lane) in nodes.items():
lanes.setdefault(lane, []).append(node)
clusters = []
for n, (lane, members) in enumerate(lanes.items()):
body = "".join(f" {_dot_id(m)} [label={_dot_id(nodes[m][0])}];\n" for m in members)
clusters.append(f" subgraph cluster_{n} {{\n label={_dot_id(lane)};\n{body} }}")
return (
f"digraph {_dot_id(flow.entry)} {{\n rankdir=LR;\n node [shape=box];\n"
+ "\n".join(clusters)
+ "\n"
+ "\n".join(edges)
+ "\n}\n"
)
Activity · 18 steps
Requirements
Flows
flow_mermaid
str clew.wiki.exports.flow_mermaid(Any flow)
A flow as a Mermaid sequence diagram.
Source · 5 lines
def flow_mermaid(flow: Any) -> str:
"""@brief Mermaid. @return Text."""
return _Mermaid().render(flow)
Activity · 1 steps
Requirements
Flows
flow_plantuml
str clew.wiki.exports.flow_plantuml(Any flow)
A flow as a PlantUML sequence diagram.
Source · 5 lines
def flow_plantuml(flow: Any) -> str:
"""@brief PlantUML. @return Text."""
return _PlantUml().render(flow)
Activity · 1 steps
Requirements
Flows
llms_full
str clew.wiki.exports.llms_full(Any trace, list pages, Audience rules, dict[str, Any] ctx)
llms-full.txt: every requirement and flow as dense text.
Source · 17 lines
def llms_full(trace: Any, pages: list, rules: Audience, ctx: dict[str, Any]) -> str:
"""@brief llms-full.txt. @return Text."""
out = [f"# {ctx['title']}", "", "## Requirements", ""]
for row in trace.evidence:
title, text = _words(row, trace.declared.get(row.req_id, {}), rules)
impl = ", ".join(f"{n} ({f})" for n, f, _l in row.implementer_sites)
out.append(f"{row.req_id} [{row.tier}]{' ' + title if title else ''}")
if text:
out.append(f" criteria: {text}")
out.append(f" implemented by: {impl or 'none'}; tests: {len(row.tests)}")
out += ["", "## Flows", ""]
for p in pages:
out.append(f"{p.title.replace('`', '')} — {p.name}.html")
out += [f" {a} -> {b}" for a, b in p.calls]
return "\n".join(out) + "\n"
Activity · 13 steps
Requirements
llms_txt
str clew.wiki.exports.llms_txt(Any trace, list pages, dict[str, Any] ctx)
llms.txt: the site's index for agents.
Source · 30 lines
def llms_txt(trace: Any, pages: list, ctx: dict[str, Any]) -> str:
"""THE LLMSTXT.ORG SHAPE: an H1, a one-line summary as a quote, then H2 sections of links.
@brief llms.txt.
@return Text.
"""
ev = trace.evidence
lines = [
f"# {ctx['title']}",
"",
f"> {ctx.get('summary') or 'Generated by clew wiki from the repository index.'}",
"",
"## Requirements",
"",
f"- [Requirements](requirements.html): {len(ev)} requirements, "
f"{sum(1 for r in ev if r.tier == 'PASS')} passing",
"",
"## Flows",
"",
*(f"- [{p.title.replace('`', '')}]({p.name}.html): {p.steps} steps" for p in pages),
"",
"## Optional",
"",
"- [Full text](llms-full.txt): every requirement and flow as text",
"- [Map](map.html): the system's components",
"",
]
return "\n".join(lines)
Activity · 3 steps
Requirements
needs_json
str clew.wiki.exports.needs_json(Any trace, Audience rules, str title)
Sphinx-needs needs.json .
Source · 29 lines
def needs_json(trace: Any, rules: Audience, title: str) -> str:
"""THE NEEDS-JSON SHAPE (`needs_builder`): a project, a current version, and per version the
needs keyed by id with their amount.
@brief needs.json.
@return JSON.
"""
needs = {}
for row in trace.evidence:
name, text = _words(row, trace.declared.get(row.req_id, {}), rules)
needs[row.req_id] = {
"id": row.req_id,
"type": "req",
"title": name,
"content": text,
"status": row.tier,
"tags": [],
"links": [],
"sections": [],
}
payload = {
"created": datetime.now(timezone.utc).isoformat(),
"project": title,
"current_version": "current",
"versions": {"current": {"needs": needs, "needs_amount": len(needs)}},
}
return json.dumps(payload, indent=2)
Activity · 6 steps
Requirements
reqif
str clew.wiki.exports.reqif(Any trace, Audience rules, str title)
ReqIF 1.2.
Source · 54 lines
def reqif(trace: Any, rules: Audience, title: str) -> str:
"""ONE STRING DATATYPE, ONE SPEC-OBJECT-TYPE with four attributes (ID, Title, Text, Tier), one
SPEC-OBJECT per requirement and one SPECIFICATION listing them — the shape every ReqIF tool
imports.
@brief ReqIF.
@return XML.
"""
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
attrs = ("ID", "Title", "Text", "Tier")
defs = "".join(
f'<ATTRIBUTE-DEFINITION-STRING IDENTIFIER="ad-{a}" LONG-NAME="{a}" LAST-CHANGE="{now}">'
"<TYPE><DATATYPE-DEFINITION-STRING-REF>dt-string</DATATYPE-DEFINITION-STRING-REF></TYPE>"
"</ATTRIBUTE-DEFINITION-STRING>"
for a in attrs
)
objects, refs = [], []
for i, row in enumerate(trace.evidence):
words = _words(row, trace.declared.get(row.req_id, {}), rules)
values = dict(zip(attrs, (row.req_id, *words, row.tier), strict=True))
vals = "".join(
f"<ATTRIBUTE-VALUE-STRING THE-VALUE={quoteattr(v)}><DEFINITION>"
f"<ATTRIBUTE-DEFINITION-STRING-REF>ad-{a}</ATTRIBUTE-DEFINITION-STRING-REF>"
"</DEFINITION></ATTRIBUTE-VALUE-STRING>"
for a, v in values.items()
if v
)
objects.append(
f'<SPEC-OBJECT IDENTIFIER="so-{i}" LAST-CHANGE="{now}"><TYPE><SPEC-OBJECT-TYPE-REF>'
f"sot-req</SPEC-OBJECT-TYPE-REF></TYPE><VALUES>{vals}</VALUES></SPEC-OBJECT>"
)
refs.append(
f'<SPEC-HIERARCHY IDENTIFIER="sh-{i}" LAST-CHANGE="{now}"><OBJECT>'
f"<SPEC-OBJECT-REF>so-{i}</SPEC-OBJECT-REF></OBJECT></SPEC-HIERARCHY>"
)
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd">'
f'<THE-HEADER><REQ-IF-HEADER IDENTIFIER="clew-wiki"><CREATION-TIME>{now}</CREATION-TIME>'
"<REQ-IF-TOOL-ID>clew wiki</REQ-IF-TOOL-ID><REQ-IF-VERSION>1.2</REQ-IF-VERSION>"
f"<SOURCE-TOOL-ID>clew</SOURCE-TOOL-ID><TITLE>{xml_escape(title)}</TITLE>"
"</REQ-IF-HEADER></THE-HEADER><CORE-CONTENT><REQ-IF-CONTENT><DATATYPES>"
f'<DATATYPE-DEFINITION-STRING IDENTIFIER="dt-string" MAX-LENGTH="100000" LAST-CHANGE="{now}"/>'
f'</DATATYPES><SPEC-TYPES><SPEC-OBJECT-TYPE IDENTIFIER="sot-req" LONG-NAME="Requirement" '
f'LAST-CHANGE="{now}"><SPEC-ATTRIBUTES>{defs}</SPEC-ATTRIBUTES></SPEC-OBJECT-TYPE>'
f'<SPECIFICATION-TYPE IDENTIFIER="st-spec" LAST-CHANGE="{now}"/></SPEC-TYPES>'
f"<SPEC-OBJECTS>{''.join(objects)}</SPEC-OBJECTS><SPECIFICATIONS>"
f'<SPECIFICATION IDENTIFIER="spec-1" LONG-NAME={quoteattr(title)} LAST-CHANGE="{now}">'
"<TYPE><SPECIFICATION-TYPE-REF>st-spec</SPECIFICATION-TYPE-REF></TYPE>"
f"<CHILDREN>{''.join(refs)}</CHILDREN></SPECIFICATION></SPECIFICATIONS>"
"</REQ-IF-CONTENT></CORE-CONTENT></REQ-IF>\n"
)
Activity · 11 steps
Requirements
structurizr
str clew.wiki.exports.structurizr(dict graph, str title)
Structurizr DSL: the system, a container per component, a relation per link.
Source · 31 lines
def structurizr(graph: dict, title: str) -> str:
"""@brief Structurizr. @return DSL."""
ids = {c["id"]: f"c{i}" for i, c in enumerate(graph["components"])}
lines = [
"workspace {",
" model {",
f" system = softwareSystem {json.dumps(title)} {{",
]
lines += [
f" {ids[c['id']]} = container {json.dumps(c['id'])} "
f'"{c["functions"]} functions, {c["files"]} files"'
for c in graph["components"]
]
lines.append(" }")
lines += [
f' {ids[link["from"]]} -> {ids[link["to"]]} "{link["calls"]} calls"'
for link in graph["links"]
if link["from"] in ids and link["to"] in ids
]
lines += [
" }",
" views {",
" container system {",
" include *",
" autolayout tb",
" }",
" }",
"}",
"",
]
return "\n".join(lines)1 more lines, not shown
Activity · 7 steps
Requirements
write_exports
None clew.wiki.exports.write_exports(Path extra, Any trace, list pages, dict graph, dict[str, Any] ctx)
Write every export into the site's extra directory.
Source · 14 lines
def write_exports(extra: Path, trace: Any, pages: list, graph: dict, ctx: dict[str, Any]) -> None:
"""@brief Write exports. @return None."""
out = Path(extra) / "exports"
out.mkdir(parents=True, exist_ok=True)
rules: Audience = ctx["rules"]
(out / "requirements.reqif").write_text(reqif(trace, rules, ctx["title"]), encoding="utf-8")
(out / "needs.json").write_text(needs_json(trace, rules, ctx["title"]), encoding="utf-8")
(out / "system.dsl").write_text(structurizr(graph, ctx["title"]), encoding="utf-8")
(Path(extra) / "llms.txt").write_text(llms_txt(trace, pages, ctx), encoding="utf-8")
(Path(extra) / "llms-full.txt").write_text(
llms_full(trace, pages, rules, ctx), encoding="utf-8"
)