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.

clew/wiki/exports.py:294

Source · 5 lines
def _dot_id(text: str) -> str:
    """@brief Quote. @return Identifier."""
    return '"' + str(text).replace("\\", "\\\\").replace('"', '\\"') + '"'

Activity · 1 steps
lines 296–296return '"' + str(text).replace("\\", "\\\\").replace('"', '\\"') + '"'

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).

clew/wiki/exports.py:255

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
lines 263–263nodes: dict[str, tuple[str, str]] = {}lines 264–264edges = []lines 265–265◇ for i, step in enumerate(flow.steps, start=1)lines 266–266◇ if not step.calleelines 267–267continuelines 268–268caller = f"{step.caller}@{step.site_file or step.file}"lines 269–269callee = f"{step.callee}@{step.file}"lines 270–270nodes.setdefault(caller, (step.caller, step.from_lane))lines 271–271nodes.setdefault(callee, (step.callee, step.to_lane))lines 272–272edges.append(f' {_dot_id(caller)} -> {_dot_id(callee)} [label="{i}"];')lines 273–273lanes: dict[str, list[str]] = {}lines 274–274◇ for node, (_name, lane) in nodes.items()lines 275–275lanes.setdefault(lane, []).append(node)lines 276–276clusters = []lines 277–277◇ for n, (lane, members) in enumerate(lanes.items())lines 278–278body = "".join(f" {_dot_id(m)} [label={_dot_id(nodes[m][0])}];\n" for m in members)lines 279–279clusters.append(f" subgraph cluster_{n} {{\n label={_dot_id(lane)};\n{body} }}")lines 280–286return ( f"digraph {_dot_id(flow.entry)} {{\n rankdir=LR;\n node [shape=box];\n" + "\n".join(clusters) + "\n" + "\n".join(edges) + "\n}\n" )

Requirements

REQ-DDB-WIKI-029

Flows

flow_mermaid

str clew.wiki.exports.flow_mermaid(Any flow)

A flow as a Mermaid sequence diagram.

clew/wiki/exports.py:235

Show on the map →

Called by _diagram_exports, _flow_page

Calls none

Source · 5 lines
def flow_mermaid(flow: Any) -> str:
    """@brief Mermaid. @return Text."""
    return _Mermaid().render(flow)

Activity · 1 steps
lines 237–237return _Mermaid().render(flow)

Requirements

REQ-DDB-WIKI-029

Flows

flow_plantuml

str clew.wiki.exports.flow_plantuml(Any flow)

A flow as a PlantUML sequence diagram.

clew/wiki/exports.py:245

Source · 5 lines
def flow_plantuml(flow: Any) -> str:
    """@brief PlantUML. @return Text."""
    return _PlantUml().render(flow)

Activity · 1 steps
lines 247–247return _PlantUml().render(flow)

Requirements

REQ-DDB-WIKI-029

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.

clew/wiki/exports.py:384

Show on the map →

Called by write_exports

Calls _words

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
lines 386–386out = [f"# {ctx['title']}", "", "## Requirements", ""]lines 387–387◇ for row in trace.evidencelines 388–388title, text = _words(row, trace.declared.get(row.req_id, {}), rules)lines 389–389impl = ", ".join(f"{n} ({f})" for n, f, _l in row.implementer_sites)lines 390–390out.append(f"{row.req_id} [{row.tier}]{' ' + title if title else ''}")lines 391–391◇ if textlines 392–392out.append(f" criteria: {text}")lines 393–393out.append(f" implemented by: {impl or 'none'}; tests: {len(row.tests)}")lines 394–394out += ["", "## Flows", ""]lines 395–395◇ for p in pageslines 396–396out.append(f"{p.title.replace('`', '')} — {p.name}.html")lines 397–397out += [f" {a} -> {b}" for a, b in p.calls]lines 398–398return "\n".join(out) + "\n"

Requirements

REQ-DDB-WIKI-029

llms_txt

str clew.wiki.exports.llms_txt(Any trace, list pages, dict[str, Any] ctx)

llms.txt: the site's index for agents.

clew/wiki/exports.py:346

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
lines 352–352ev = trace.evidencelines 353–372lines = [ 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", "", ]lines 373–373return "\n".join(lines)

Requirements

REQ-DDB-WIKI-029

needs_json

str clew.wiki.exports.needs_json(Any trace, Audience rules, str title)

Sphinx-needs needs.json .

clew/wiki/exports.py:469

Show on the map →

Called by write_exports

Calls _words

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
lines 476–476needs = {}lines 477–477◇ for row in trace.evidencelines 478–478name, text = _words(row, trace.declared.get(row.req_id, {}), rules)lines 479–488needs[row.req_id] = { "id": row.req_id, "type": "req", "title": name, "content": text, "status": row.tier, "tags": [], "links": [], "sections": [], }lines 489–494payload = { "created": datetime.now(timezone.utc).isoformat(), "project": title, "current_version": "current", "versions": {"current": {"needs": needs, "needs_amount": len(needs)}}, }lines 495–495return json.dumps(payload, indent=2)

Requirements

REQ-DDB-WIKI-029

reqif

str clew.wiki.exports.reqif(Any trace, Audience rules, str title)

ReqIF 1.2.

clew/wiki/exports.py:408

Show on the map →

Called by write_exports

Calls _words

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
lines 416–416now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")lines 417–417attrs = ("ID", "Title", "Text", "Tier")lines 418–423defs = "".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 )lines 424–424objects, refs = [], []lines 425–425◇ for i, row in enumerate(trace.evidence)lines 426–426words = _words(row, trace.declared.get(row.req_id, {}), rules)lines 427–427values = dict(zip(attrs, (row.req_id, *words, row.tier), strict=True))lines 428–434vals = "".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 )lines 435–438objects.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>" )lines 439–442refs.append( f'<SPEC-HIERARCHY IDENTIFIER="sh-{i}" LAST-CHANGE="{now}"><OBJECT>' f"<SPEC-OBJECT-REF>so-{i}</SPEC-OBJECT-REF></OBJECT></SPEC-HIERARCHY>" )lines 443–459return ( '<?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" )

Requirements

REQ-DDB-WIKI-029

structurizr

str clew.wiki.exports.structurizr(dict graph, str title)

Structurizr DSL: the system, a container per component, a relation per link.

clew/wiki/exports.py:504

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
lines 506–506ids = {c["id"]: f"c{i}" for i, c in enumerate(graph["components"])}lines 507–511lines = [ "workspace {", " model {", f" system = softwareSystem {json.dumps(title)} {{", ]lines 512–516lines += [ f" {ids[c['id']]} = container {json.dumps(c['id'])} " f'"{c["functions"]} functions, {c["files"]} files"' for c in graph["components"] ]lines 517–517lines.append(" }")lines 518–522lines += [ 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 523–533lines += [ " }", " views {", " container system {", " include *", " autolayout tb", " }", " }", "}", "", ]lines 534–534return "\n".join(lines)

Requirements

REQ-DDB-WIKI-029

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.

clew/wiki/exports.py:325

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"
    )

Activity · 8 steps
lines 327–327out = Path(extra) / "exports"lines 328–328out.mkdir(parents=True, exist_ok=True)lines 329–329rules: Audience = ctx["rules"]lines 330–330(out / "requirements.reqif").write_text(reqif(trace, rules, ctx["title"]), encoding="utf-8")lines 331–331(out / "needs.json").write_text(needs_json(trace, rules, ctx["title"]), encoding="utf-8")lines 332–332(out / "system.dsl").write_text(structurizr(graph, ctx["title"]), encoding="utf-8")lines 333–333(Path(extra) / "llms.txt").write_text(llms_txt(trace, pages, ctx), encoding="utf-8")lines 334–336(Path(extra) / "llms-full.txt").write_text( llms_full(trace, pages, rules, ctx), encoding="utf-8" )

Requirements

REQ-DDB-WIKI-029