throughline-transform 0.1.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.
- throughline_transform/__init__.py +13 -0
- throughline_transform/blocks.py +156 -0
- throughline_transform/cli.py +155 -0
- throughline_transform/html.py +157 -0
- throughline_transform/markdown.py +82 -0
- throughline_transform/model.py +171 -0
- throughline_transform/notes.py +215 -0
- throughline_transform/office.py +334 -0
- throughline_transform/package.py +70 -0
- throughline_transform/project.py +108 -0
- throughline_transform/provenance.py +91 -0
- throughline_transform/shape.py +32 -0
- throughline_transform/tables.py +165 -0
- throughline_transform-0.1.0.dist-info/METADATA +108 -0
- throughline_transform-0.1.0.dist-info/RECORD +20 -0
- throughline_transform-0.1.0.dist-info/WHEEL +5 -0
- throughline_transform-0.1.0.dist-info/entry_points.txt +3 -0
- throughline_transform-0.1.0.dist-info/licenses/LICENSE +201 -0
- throughline_transform-0.1.0.dist-info/licenses/NOTICE +12 -0
- throughline_transform-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Copyright (c) 2026 Henry J Grech-Cini
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""throughline-transform: a throughline graph on disk, in the forms its readers open.
|
|
4
|
+
|
|
5
|
+
Everything here reads what the tool writes. The Markdown comes from ``tl docs``
|
|
6
|
+
over a document of directives; the structure comes from ``tl dump``. What this
|
|
7
|
+
package adds is the containers — a workbook, a Word document, a folder of notes,
|
|
8
|
+
a print-ready page — and never a second rendering of an item's words.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .project import TransformError
|
|
12
|
+
|
|
13
|
+
__all__ = ["TransformError"]
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# Copyright (c) 2026 Henry J Grech-Cini
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The Markdown, as the blocks a document is made of (SR-0008).
|
|
4
|
+
|
|
5
|
+
Deliberately shallow. This reads the headings and paragraphs out of what the
|
|
6
|
+
tool wrote rather than interpreting Markdown properly — a full parser here
|
|
7
|
+
would be a second opinion about a document the tool already rendered.
|
|
8
|
+
|
|
9
|
+
What it adds is structure the tool's Markdown states only by shape: an item's
|
|
10
|
+
opening line becomes a heading with its type and status beneath, items are
|
|
11
|
+
grouped under a section per register (or per source, in the mirrored clauses),
|
|
12
|
+
and the attribute line is marked as the small print it is.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
|
|
20
|
+
from .shape import ATTRS_LINE, ITEM_LINE
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Block:
|
|
25
|
+
text: str
|
|
26
|
+
#: 1–4 for a heading; ``None`` for body text.
|
|
27
|
+
heading: int | None = None
|
|
28
|
+
#: Rendered as a quotation, which is how an item's own words are set.
|
|
29
|
+
quote: bool = False
|
|
30
|
+
#: The tool's attribute line — small print beneath an item.
|
|
31
|
+
small: bool = False
|
|
32
|
+
#: Front matter: the provenance lines before the first section.
|
|
33
|
+
front: bool = False
|
|
34
|
+
#: A heading that opens a register's or a source's group of items.
|
|
35
|
+
group: bool = False
|
|
36
|
+
#: A line beneath a heading saying where an appendix's source comes from.
|
|
37
|
+
subtitle: str | None = None
|
|
38
|
+
#: A heading that opens one item: ``{"uid", "type", "status"}``.
|
|
39
|
+
item: dict[str, str] | None = None
|
|
40
|
+
#: A table the tool wrote, kept as a table: ``{"header": [...], "rows": [[...]]}``.
|
|
41
|
+
table: dict[str, list] | None = None
|
|
42
|
+
#: The contents entries beneath this heading, filled by the writers that need them.
|
|
43
|
+
children: list["Block"] = field(default_factory=list, repr=False)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_HEADING = re.compile(r"^(#{1,3})\s+(.*)$")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def strip(text: str) -> str:
|
|
50
|
+
"""Drop the emphasis marks a document has no use for, keeping the words."""
|
|
51
|
+
text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
|
|
52
|
+
text = re.sub(r"\*(.+?)\*", r"\1", text)
|
|
53
|
+
return text.replace("`", "")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _is_row(line: str) -> bool:
|
|
57
|
+
return line.startswith("|") and line.endswith("|") and len(line) > 2
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _cells(row: str) -> list[str]:
|
|
61
|
+
return [strip(cell.strip()) for cell in row[1:-1].split("|")]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def as_blocks(
|
|
65
|
+
markdown: str,
|
|
66
|
+
registers: dict[str, str] | None = None,
|
|
67
|
+
sources: dict[str, str] | None = None,
|
|
68
|
+
) -> list[Block]:
|
|
69
|
+
registers = registers or {}
|
|
70
|
+
sources = sources or {}
|
|
71
|
+
blocks: list[Block] = []
|
|
72
|
+
lines = markdown.split("\n")
|
|
73
|
+
group: str | None = None
|
|
74
|
+
front = True
|
|
75
|
+
in_sources = False
|
|
76
|
+
appendices = 0
|
|
77
|
+
|
|
78
|
+
i = 0
|
|
79
|
+
while i < len(lines):
|
|
80
|
+
text = lines[i].strip()
|
|
81
|
+
i += 1
|
|
82
|
+
if not text:
|
|
83
|
+
continue
|
|
84
|
+
# A region marker is instruction to the tool, not something to read.
|
|
85
|
+
if text.startswith("<!--"):
|
|
86
|
+
continue
|
|
87
|
+
|
|
88
|
+
item = ITEM_LINE.match(text)
|
|
89
|
+
if item:
|
|
90
|
+
uid, ref, title, type_, status = item.groups()
|
|
91
|
+
colon = uid.find(":")
|
|
92
|
+
prefix = uid[: uid.rfind("-")] if colon == -1 else uid[:colon]
|
|
93
|
+
if prefix != group:
|
|
94
|
+
group = prefix
|
|
95
|
+
if in_sources:
|
|
96
|
+
letter = chr(65 + (appendices % 26))
|
|
97
|
+
appendices += 1
|
|
98
|
+
blocks.append(
|
|
99
|
+
Block(
|
|
100
|
+
heading=2,
|
|
101
|
+
text=f"Appendix {letter} — {prefix}",
|
|
102
|
+
group=True,
|
|
103
|
+
subtitle=sources.get(prefix),
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
else:
|
|
107
|
+
blocks.append(Block(heading=3, text=registers.get(prefix, prefix), group=True))
|
|
108
|
+
blocks.append(
|
|
109
|
+
Block(
|
|
110
|
+
heading=3 if in_sources else 4,
|
|
111
|
+
text=f"{uid}{f' ({ref})' if ref else ''} — {strip(title)}",
|
|
112
|
+
item={"uid": uid, "type": type_, "status": status},
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
continue
|
|
116
|
+
|
|
117
|
+
if _is_row(text):
|
|
118
|
+
rows: list[list[str]] = []
|
|
119
|
+
i -= 1
|
|
120
|
+
while i < len(lines) and _is_row(lines[i].strip()):
|
|
121
|
+
row = lines[i].strip()
|
|
122
|
+
if not re.match(r"^\|[\s:|-]+\|$", row):
|
|
123
|
+
rows.append(_cells(row))
|
|
124
|
+
i += 1
|
|
125
|
+
if rows:
|
|
126
|
+
blocks.append(Block(text="", table={"header": rows[0], "rows": rows[1:]}))
|
|
127
|
+
continue
|
|
128
|
+
|
|
129
|
+
heading = _HEADING.match(text)
|
|
130
|
+
if heading:
|
|
131
|
+
level = len(heading.group(1))
|
|
132
|
+
if level >= 2:
|
|
133
|
+
front = False
|
|
134
|
+
group = None
|
|
135
|
+
in_sources = level == 2 and bool(re.search(r"adopted sources", heading.group(2), re.I))
|
|
136
|
+
if in_sources:
|
|
137
|
+
blocks.append(Block(heading=2, text="Appendices"))
|
|
138
|
+
blocks.append(
|
|
139
|
+
Block(
|
|
140
|
+
text=(
|
|
141
|
+
"The clauses of the adopted sources that this intent graph cites, "
|
|
142
|
+
"one appendix per source, in the words the source states them."
|
|
143
|
+
)
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
continue
|
|
147
|
+
blocks.append(Block(heading=level, text=strip(heading.group(2))))
|
|
148
|
+
continue
|
|
149
|
+
if text.startswith(">"):
|
|
150
|
+
blocks.append(Block(quote=True, text=strip(re.sub(r"^>\s?", "", text))))
|
|
151
|
+
continue
|
|
152
|
+
if ATTRS_LINE.match(text):
|
|
153
|
+
blocks.append(Block(text=strip(text), small=True))
|
|
154
|
+
continue
|
|
155
|
+
blocks.append(Block(text=strip(re.sub(r"^[-*]\s+", "", text)), front=front))
|
|
156
|
+
return blocks
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Copyright (c) 2026 Henry J Grech-Cini
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""``tl-transform``: a graph on disk, in the form a reader opens (UR-0001, UR-0002).
|
|
4
|
+
|
|
5
|
+
tl-transform md [-C DIR] [-o FILE] [--body …] [--matrix] [--no-stats] [--markers]
|
|
6
|
+
tl-transform notes [-C DIR] [-o FILE|DIR] [--folder]
|
|
7
|
+
tl-transform csv [-C DIR] [-o FILE|DIR] [--folder] [--split …]
|
|
8
|
+
tl-transform xlsx [-C DIR] [-o FILE] [--split …]
|
|
9
|
+
tl-transform docx [-C DIR] [-o FILE] [--body …] [--matrix] [--no-stats]
|
|
10
|
+
tl-transform html [-C DIR] [-o FILE] [--body …] [--matrix] [--no-stats]
|
|
11
|
+
|
|
12
|
+
Exit codes: 0 written · 1 the tool or the file system refused · 2 usage.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import sys
|
|
19
|
+
from dataclasses import replace
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from throughline.version import distribution_version as _v
|
|
23
|
+
|
|
24
|
+
from . import markdown as md
|
|
25
|
+
from .blocks import as_blocks
|
|
26
|
+
from .html import to_html
|
|
27
|
+
from .model import Graph, register_titles, source_titles
|
|
28
|
+
from .notes import to_notes
|
|
29
|
+
from .office import to_docx, to_xlsx
|
|
30
|
+
from .package import Entry, archive, unpack, utf8
|
|
31
|
+
from .project import TransformError, find_graph, load
|
|
32
|
+
from .provenance import Provenance, provenance_of
|
|
33
|
+
from .tables import Table, cited_sources, file_name, links_of, per_register, to_csv, whole_graph
|
|
34
|
+
|
|
35
|
+
FORMATS = ("md", "notes", "csv", "xlsx", "docx", "html")
|
|
36
|
+
PROSE = ("md", "docx", "html")
|
|
37
|
+
FOLDERS = ("notes", "csv")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def version_string() -> str:
|
|
41
|
+
return (
|
|
42
|
+
f"tl-transform {_v('throughline-transform')} "
|
|
43
|
+
f"(throughline-compose {_v('throughline-compose')}, throughline {_v('throughline')})"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
48
|
+
p = argparse.ArgumentParser(
|
|
49
|
+
prog="tl-transform",
|
|
50
|
+
description="Turn a throughline graph on disk, committed or not, into the form a reader opens.",
|
|
51
|
+
)
|
|
52
|
+
p.add_argument("--version", action="version", version=version_string())
|
|
53
|
+
p.add_argument("format", choices=FORMATS, help="what to produce")
|
|
54
|
+
p.add_argument("-C", dest="directory", metavar="DIR", help="the directory holding throughline.toml")
|
|
55
|
+
p.add_argument("-o", dest="output", metavar="PATH", help="where to write; a name is chosen from the graph if omitted")
|
|
56
|
+
p.add_argument("--folder", action="store_true", help="notes, csv: write the files into a folder instead of a zip")
|
|
57
|
+
p.add_argument(
|
|
58
|
+
"--body",
|
|
59
|
+
choices=("catalog", "table", "both"),
|
|
60
|
+
default="catalog",
|
|
61
|
+
help="md, docx, html: every item in full, a table of items, or both",
|
|
62
|
+
)
|
|
63
|
+
p.add_argument("--matrix", action="store_true", help="md, docx, html: add a traceability matrix per grounding link")
|
|
64
|
+
p.add_argument("--no-stats", dest="stats", action="store_false", help="md, docx, html: leave out the tool's summary")
|
|
65
|
+
p.add_argument("--markers", action="store_true", help="md: keep the tool's region markers so `tl docs` can refill the file")
|
|
66
|
+
p.add_argument(
|
|
67
|
+
"--split",
|
|
68
|
+
choices=("one", "per-register"),
|
|
69
|
+
default="one",
|
|
70
|
+
help="csv, xlsx: one table of everything, or one per register",
|
|
71
|
+
)
|
|
72
|
+
return p
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _tables(graph: Graph, split: str) -> tuple[list[Table], Table, list[Table]]:
|
|
76
|
+
tables = per_register(graph) if split == "per-register" else [whole_graph(graph)]
|
|
77
|
+
return tables, links_of(tables), cited_sources(graph)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _about(provenance: Provenance, extra: list[list[str]] | None = None) -> Table:
|
|
81
|
+
rows = [line.split(": ", 1) for line in provenance.lines()]
|
|
82
|
+
return Table(name="About this export", columns=["Field", "Value"], rows=rows + (extra or []))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def produce(graph: Graph, root: Path, fmt: str, opts: md.Options, provenance: Provenance) -> tuple[bytes | list[Entry], str]:
|
|
86
|
+
"""The output and its default file name; a list of entries for the folder formats."""
|
|
87
|
+
stem = provenance.stem
|
|
88
|
+
if fmt in PROSE:
|
|
89
|
+
text = md.to_markdown(root, graph, opts, provenance)
|
|
90
|
+
if fmt == "md":
|
|
91
|
+
return utf8(text), f"{stem}.md"
|
|
92
|
+
blocks = as_blocks(text, register_titles(graph), source_titles(graph))
|
|
93
|
+
if fmt == "docx":
|
|
94
|
+
return to_docx(blocks), f"{stem}.docx"
|
|
95
|
+
return utf8(to_html(blocks, provenance)), f"{stem}.html"
|
|
96
|
+
|
|
97
|
+
if fmt == "notes":
|
|
98
|
+
text = md.to_markdown(
|
|
99
|
+
root, graph, replace(opts, body="catalog", matrix=False, stats=False, markers=False), provenance
|
|
100
|
+
)
|
|
101
|
+
return to_notes(text, graph, provenance), f"{stem}-notes"
|
|
102
|
+
|
|
103
|
+
tables, links, sources = _tables(graph, opts.split)
|
|
104
|
+
if fmt == "xlsx":
|
|
105
|
+
return to_xlsx([*tables, links, *sources, _about(provenance)]), f"{stem}.xlsx"
|
|
106
|
+
|
|
107
|
+
about = _about(
|
|
108
|
+
provenance,
|
|
109
|
+
[["Read-only", "No. csv cannot be protected; the xlsx output of the same graph is."]],
|
|
110
|
+
)
|
|
111
|
+
entries: list[Entry] = [(file_name(t), utf8(to_csv(t))) for t in tables]
|
|
112
|
+
entries.append(("links.csv", utf8(to_csv(links))))
|
|
113
|
+
entries += [(f"{t.name}.csv", utf8(to_csv(t))) for t in sources]
|
|
114
|
+
entries.append(("about-this-export.csv", utf8(to_csv(about))))
|
|
115
|
+
return entries, f"{stem}-csv"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def write(result: bytes | list[Entry], default: str, output: str | None, folder: bool) -> Path:
|
|
119
|
+
if isinstance(result, bytes):
|
|
120
|
+
target = Path(output) if output else Path(default)
|
|
121
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
target.write_bytes(result)
|
|
123
|
+
return target
|
|
124
|
+
if folder:
|
|
125
|
+
target = Path(output) if output else Path(default)
|
|
126
|
+
unpack(result, target)
|
|
127
|
+
return target
|
|
128
|
+
target = Path(output) if output else Path(f"{default}.zip")
|
|
129
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
130
|
+
target.write_bytes(archive(result))
|
|
131
|
+
return target
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def main(argv: list[str] | None = None) -> int:
|
|
135
|
+
parser = build_parser()
|
|
136
|
+
args = parser.parse_args(argv)
|
|
137
|
+
if args.folder and args.format not in FOLDERS:
|
|
138
|
+
parser.error(f"--folder applies to {' and '.join(FOLDERS)}, not {args.format}")
|
|
139
|
+
opts = md.Options(body=args.body, matrix=args.matrix, stats=args.stats, markers=args.markers, split=args.split)
|
|
140
|
+
try:
|
|
141
|
+
root = find_graph(args.directory)
|
|
142
|
+
graph = load(root)
|
|
143
|
+
provenance = provenance_of(root, graph.tool_version)
|
|
144
|
+
result, default = produce(graph, root, args.format, opts, provenance)
|
|
145
|
+
target = write(result, default, args.output, args.folder)
|
|
146
|
+
except (TransformError, OSError, ValueError) as exc:
|
|
147
|
+
print(f"tl-transform: {exc}", file=sys.stderr)
|
|
148
|
+
return 1
|
|
149
|
+
count = "" if isinstance(result, bytes) else f" ({len(result)} files)"
|
|
150
|
+
print(f"{target}{count} — {provenance.repository}, {provenance.tree}")
|
|
151
|
+
return 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
if __name__ == "__main__": # pragma: no cover
|
|
155
|
+
sys.exit(main())
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Copyright (c) 2026 Henry J Grech-Cini
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""A print-ready HTML document (SR-0008).
|
|
4
|
+
|
|
5
|
+
One self-contained file: a title page, a contents list, a section per register,
|
|
6
|
+
a heading per item, and the cited clauses as appendices, with the print
|
|
7
|
+
typography embedded and A4 page rules for the browser that prints it. There is
|
|
8
|
+
no PDF writer here and that is the decision rather than a gap — every browser
|
|
9
|
+
prints to PDF with a renderer that is already on the machine.
|
|
10
|
+
|
|
11
|
+
Every string reaches the page through ``html.escape``. Nothing in an item's
|
|
12
|
+
text can become markup.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from html import escape
|
|
18
|
+
|
|
19
|
+
from .blocks import Block
|
|
20
|
+
from .provenance import Provenance
|
|
21
|
+
|
|
22
|
+
_STYLE = """
|
|
23
|
+
:root { color-scheme: light; }
|
|
24
|
+
body { margin: 0; background: #f4f4f4; color: #000; font-family: Georgia, "Times New Roman", serif; }
|
|
25
|
+
article { max-width: 190mm; margin: 0 auto; padding: 24mm 20mm; background: #fff; font-size: 10.5pt; line-height: 1.45; }
|
|
26
|
+
h1 { font-size: 26pt; line-height: 1.2; margin: 0 0 1.2em; }
|
|
27
|
+
.front { min-height: 120mm; padding-top: 60mm; }
|
|
28
|
+
.front p { font-size: 11pt; margin: 0.2em 0; color: #333; }
|
|
29
|
+
h2 { font-size: 18pt; margin: 0 0 0.8em; padding-bottom: 0.25em; border-bottom: 1.5pt solid #000; }
|
|
30
|
+
h3 { font-size: 14pt; margin: 1.4em 0 0.6em; }
|
|
31
|
+
h4 { font-size: 11.5pt; margin: 1.1em 0 0.15em; }
|
|
32
|
+
section.part { margin-top: 2em; }
|
|
33
|
+
section.item { margin-bottom: 0.6em; }
|
|
34
|
+
.meta { font-size: 9pt; color: #444; margin: 0 0 0.4em; }
|
|
35
|
+
p, blockquote { margin: 0.35em 0; }
|
|
36
|
+
blockquote { margin: 0.4em 0 0.4em 1.5em; font-style: italic; }
|
|
37
|
+
.attrs { font-size: 8.5pt; color: #555; overflow-wrap: anywhere; }
|
|
38
|
+
table { border-collapse: collapse; width: 100%; font-size: 9pt; margin: 0.6em 0; }
|
|
39
|
+
th, td { border: 0.5pt solid #888; padding: 0.25em 0.4em; text-align: left; vertical-align: top; }
|
|
40
|
+
th { background: #eee; }
|
|
41
|
+
nav.contents ol { list-style: none; padding-left: 0; margin: 0; }
|
|
42
|
+
nav.contents ol ol { padding-left: 1.4em; font-size: 9.5pt; }
|
|
43
|
+
nav.contents li { margin: 0.12em 0; }
|
|
44
|
+
nav.contents a { color: #000; text-decoration: none; }
|
|
45
|
+
@media print {
|
|
46
|
+
@page { size: A4; margin: 22mm 20mm 24mm; }
|
|
47
|
+
body { background: #fff; }
|
|
48
|
+
article { max-width: none; margin: 0; padding: 0; }
|
|
49
|
+
.front { break-after: page; }
|
|
50
|
+
nav.contents { break-after: page; }
|
|
51
|
+
section.part { break-before: page; margin-top: 0; }
|
|
52
|
+
h2, h3, h4 { break-after: avoid; }
|
|
53
|
+
section.item { break-inside: avoid; }
|
|
54
|
+
thead { display: table-header-group; }
|
|
55
|
+
tr { break-inside: avoid; }
|
|
56
|
+
}
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _beneath(block: Block) -> str | None:
|
|
61
|
+
if block.item:
|
|
62
|
+
return f"{block.item['type'].replace('_', ' ')} · {block.item['status']}"
|
|
63
|
+
return block.subtitle
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def to_html(blocks: list[Block], provenance: Provenance) -> str:
|
|
67
|
+
title = next((b.text for b in blocks if b.heading == 1), f"{provenance.repository} — requirements")
|
|
68
|
+
|
|
69
|
+
body: list[str] = []
|
|
70
|
+
contents: list[str] = []
|
|
71
|
+
depth = 0
|
|
72
|
+
headings = 0
|
|
73
|
+
open_part = False
|
|
74
|
+
open_item = False
|
|
75
|
+
|
|
76
|
+
def close_item() -> None:
|
|
77
|
+
nonlocal open_item
|
|
78
|
+
if open_item:
|
|
79
|
+
body.append("</section>")
|
|
80
|
+
open_item = False
|
|
81
|
+
|
|
82
|
+
def close_part() -> None:
|
|
83
|
+
nonlocal open_part
|
|
84
|
+
close_item()
|
|
85
|
+
if open_part:
|
|
86
|
+
body.append("</section>")
|
|
87
|
+
open_part = False
|
|
88
|
+
|
|
89
|
+
def entry(level: int, anchor: str, text: str) -> None:
|
|
90
|
+
nonlocal depth
|
|
91
|
+
# Levels 2–4 become nesting depths 1–3 in the contents list.
|
|
92
|
+
wanted = level - 1
|
|
93
|
+
while depth < wanted:
|
|
94
|
+
contents.append("<ol>")
|
|
95
|
+
depth += 1
|
|
96
|
+
while depth > wanted:
|
|
97
|
+
contents.append("</ol>")
|
|
98
|
+
depth -= 1
|
|
99
|
+
contents.append(f'<li><a href="#{anchor}">{escape(text)}</a></li>')
|
|
100
|
+
|
|
101
|
+
front: list[str] = []
|
|
102
|
+
for block in blocks:
|
|
103
|
+
if block.table:
|
|
104
|
+
head = "".join(f"<th>{escape(c)}</th>" for c in block.table["header"])
|
|
105
|
+
rows = "".join(
|
|
106
|
+
"<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>" for row in block.table["rows"]
|
|
107
|
+
)
|
|
108
|
+
body.append(f"<table><thead><tr>{head}</tr></thead><tbody>{rows}</tbody></table>")
|
|
109
|
+
continue
|
|
110
|
+
if block.heading == 1:
|
|
111
|
+
front.append(f"<h1>{escape(block.text)}</h1>")
|
|
112
|
+
continue
|
|
113
|
+
if block.front:
|
|
114
|
+
front.append(f"<p>{escape(block.text)}</p>")
|
|
115
|
+
continue
|
|
116
|
+
if block.heading:
|
|
117
|
+
headings += 1
|
|
118
|
+
anchor = f"h-{headings}"
|
|
119
|
+
level = min(block.heading, 6)
|
|
120
|
+
if block.heading == 2:
|
|
121
|
+
close_part()
|
|
122
|
+
body.append('<section class="part">')
|
|
123
|
+
open_part = True
|
|
124
|
+
elif block.item:
|
|
125
|
+
close_item()
|
|
126
|
+
body.append('<section class="item">')
|
|
127
|
+
open_item = True
|
|
128
|
+
else:
|
|
129
|
+
close_item()
|
|
130
|
+
body.append(f'<h{level} id="{anchor}">{escape(block.text)}</h{level}>')
|
|
131
|
+
beneath = _beneath(block)
|
|
132
|
+
if beneath:
|
|
133
|
+
body.append(f'<p class="meta">{escape(beneath)}</p>')
|
|
134
|
+
if block.heading <= 4:
|
|
135
|
+
entry(block.heading, anchor, block.text)
|
|
136
|
+
continue
|
|
137
|
+
if block.quote:
|
|
138
|
+
body.append(f"<blockquote>{escape(block.text)}</blockquote>")
|
|
139
|
+
elif block.small:
|
|
140
|
+
body.append(f'<p class="attrs">{escape(block.text)}</p>')
|
|
141
|
+
else:
|
|
142
|
+
body.append(f"<p>{escape(block.text)}</p>")
|
|
143
|
+
close_part()
|
|
144
|
+
while depth > 0:
|
|
145
|
+
contents.append("</ol>")
|
|
146
|
+
depth -= 1
|
|
147
|
+
|
|
148
|
+
return (
|
|
149
|
+
"<!doctype html>\n"
|
|
150
|
+
'<html lang="en">\n<head>\n<meta charset="utf-8">\n'
|
|
151
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">\n'
|
|
152
|
+
f"<title>{escape(title)}</title>\n<style>{_STYLE}</style>\n</head>\n<body>\n<article>\n"
|
|
153
|
+
'<header class="front">\n' + "\n".join(front) + "\n</header>\n"
|
|
154
|
+
'<nav class="contents">\n<h2>Contents</h2>\n' + "\n".join(contents) + "\n</nav>\n"
|
|
155
|
+
+ "\n".join(body)
|
|
156
|
+
+ "\n</article>\n</body>\n</html>\n"
|
|
157
|
+
)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Copyright (c) 2026 Henry J Grech-Cini
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""The Markdown document, written by the tool (SR-0002).
|
|
4
|
+
|
|
5
|
+
A document of directives and empty regions is handed to the docs command, and
|
|
6
|
+
what comes back is what the tool wrote. Which entry point runs is the graph's
|
|
7
|
+
decision (SR-0001).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .model import Graph, ground_links
|
|
17
|
+
from .project import docs
|
|
18
|
+
from .provenance import Provenance
|
|
19
|
+
from .shape import MARKER
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Options:
|
|
24
|
+
#: Full item blocks, a compact table, or both.
|
|
25
|
+
body: str = "catalog"
|
|
26
|
+
#: A traceability matrix per grounding link type.
|
|
27
|
+
matrix: bool = False
|
|
28
|
+
#: The tool's own summary of the graph's shape.
|
|
29
|
+
stats: bool = True
|
|
30
|
+
#: Keep the tool's region markers, so the document is one ``tl docs`` can refill.
|
|
31
|
+
markers: bool = False
|
|
32
|
+
#: For the tabular outputs: one table for everything, or one per register.
|
|
33
|
+
split: str = "one"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _region(directive: str) -> str:
|
|
37
|
+
return f"<!-- tl:{directive} -->\n<!-- tl:end -->"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def directive_document(graph: Graph, opts: Options, provenance: Provenance) -> str:
|
|
41
|
+
"""The document the tool is asked to fill."""
|
|
42
|
+
lines: list[str] = [f"# {provenance.repository} — requirements", ""]
|
|
43
|
+
lines += [f"- {line}" for line in provenance.lines()]
|
|
44
|
+
lines.append("")
|
|
45
|
+
|
|
46
|
+
if opts.stats:
|
|
47
|
+
lines += ["## Summary", "", _region("stats True"), ""]
|
|
48
|
+
if opts.body in ("table", "both"):
|
|
49
|
+
lines += ["## Items", "", _region("table True"), ""]
|
|
50
|
+
if opts.matrix:
|
|
51
|
+
# One matrix per grounding link type the graph declares, each over the
|
|
52
|
+
# items something actually reaches by that link. Over every item a
|
|
53
|
+
# matrix is mostly a column of dashes.
|
|
54
|
+
lines += ["## Traceability", ""]
|
|
55
|
+
for link_type in ground_links(graph):
|
|
56
|
+
lines += [
|
|
57
|
+
f"### {link_type.replace('_', ' ')}",
|
|
58
|
+
"",
|
|
59
|
+
_region(f"matrix incoming:{link_type} links.incoming('{link_type}')"),
|
|
60
|
+
"",
|
|
61
|
+
]
|
|
62
|
+
if opts.body in ("catalog", "both"):
|
|
63
|
+
lines += ["## Every item", "", _region("catalog True"), ""]
|
|
64
|
+
# The words every cited clause answers to. Only over a composed graph: the
|
|
65
|
+
# directive is the composer's, and a graph adopting no source has nothing
|
|
66
|
+
# to mirror.
|
|
67
|
+
if graph.composed:
|
|
68
|
+
lines += ["## Clauses of adopted sources", "", _region("sourced True"), ""]
|
|
69
|
+
return "\n".join(lines)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def strip_markers(markdown: str) -> str:
|
|
73
|
+
"""Take out the tool's region markers, leaving what it wrote between them."""
|
|
74
|
+
kept = [line for line in markdown.split("\n") if not MARKER.match(line)]
|
|
75
|
+
# A removed marker leaves the blank line that was around it, so runs of
|
|
76
|
+
# three or more collapse to the one a Markdown reader expects.
|
|
77
|
+
return re.sub(r"\n{3,}", "\n\n", "\n".join(kept))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def to_markdown(root: Path, graph: Graph, opts: Options, provenance: Provenance) -> str:
|
|
81
|
+
written = docs(root, directive_document(graph, opts, provenance), graph.composed)
|
|
82
|
+
return written if opts.markers else strip_markers(written)
|