Coverage for lode / builder.py: 94%
142 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-11-22 15:54 +0000
1"""Static-site builder: renders an artefact as a folder of plain HTML pages.
3Produces an index page, one page per documented resource and the serializations
4of the whole artefact and of each resource, ready to publish on any static host.
5"""
6import os
7import re
8import shutil
9from pathlib import Path
10from jinja2 import Environment, FileSystemLoader, select_autoescape
11from rdflib import URIRef
12from typing import List
14# internal modules
15from lode.helpers.formats import SERIALIZATION_FORMATS
16from lode.helpers.html_utils import minify as _minify
17from lode.exceptions import ArtefactValidationError
18from typing import Optional
19from lode.helpers.links import Links
21_SER = [(f["fmt"], f["ext"]) for f in SERIALIZATION_FORMATS]
23def _get_template_env(template_dirs: List[Path], static_path: str = "static") -> Environment:
24 """Create the Jinja2 environment used to render the static pages.
26 `template_dirs` is the search path of the viewer (BaseViewer.template_dirs): a template of
27 the format replaces the base one with the same name. `static_path` is the relative path
28 from the page to the static folder, so it differs between the index and the resource
29 pages. The web app's url_for does not exist here, hence the minimal replacement below.
30 """
31 env = Environment(
32 loader=FileSystemLoader([str(d) for d in template_dirs]),
33 autoescape=select_autoescape(["html"]),
34 )
36 def url_for(name: str, path: str = "") -> str:
37 """Resolve static files relative to the page; every other route goes to the root."""
38 if name == "static":
39 return f"{static_path}/{path}"
40 return "/"
42 env.globals["url_for"] = url_for
43 return env
46def _prefix_map(graph):
47 """Map each namespace IRI of the graph to its prefix ('default' for the empty one)."""
48 return {str(ns): (p or 'default') for p, ns in graph.namespaces()}
50def _safe_segment(seg: str) -> str:
51 """Restrict a slug path segment to a filesystem-safe whitelist.
53 Prefix and local name come from IRIs in the loaded ontology, i.e. from
54 user-controlled input: path separators, '..', NUL etc. must never reach
55 the filesystem (path injection). An empty result means "no usable local
56 part" and is treated by callers as a namespace IRI (page skipped).
57 """
58 seg = re.sub(r"[^A-Za-z0-9._-]", "-", seg).strip("-.")
59 if not seg or set(seg) == {"."}:
60 return ""
61 return seg[:100]
64def _rel_slug(uri, graph):
65 """Return the 'prefix/local' path of a resource, with both parts made filesystem-safe.
67 The local part is empty for a bare namespace IRI: callers skip those.
68 """
69 prefix, ns, local = graph.namespace_manager.compute_qname(URIRef(str(uri)), generate=True)
70 prefix = _safe_segment(prefix or "default") or "default"
71 return f"{prefix}/{_safe_segment(local)}"
74def _check_artefact_name(name: str) -> str:
75 """Return `name` if it is a plain file stem, else raise.
77 The name is user-chosen (CLI) and becomes file names in the output folder
78 and links in every page: path separators or '..' would let the root files
79 escape the output directory.
80 """
81 if not re.fullmatch(r"[A-Za-z0-9._-]+", name) or set(name) == {"."}:
82 raise ArtefactValidationError(
83 "Invalid artefact name: use only letters, digits, '.', '_' and '-' (no extension)",
84 context={"artefact_name": name},
85 )
86 return name
89def _write_in(base: Path, name: str, text: str) -> None:
90 """Write `text` to `base / name`, refusing any path that leaves `base`.
92 `base` is the output folder and `name` a root file (<artefact_name>.html, ...):
93 both are user-chosen, so the resolved target is checked against `base`
94 before anything touches the filesystem (path injection).
95 """
96 root = os.path.realpath(base)
97 target = os.path.realpath(os.path.join(root, name))
98 if not target.startswith(root + os.sep):
99 raise ArtefactValidationError(
100 "Refusing to write outside the output folder",
101 context={"base": str(base), "name": name},
102 )
103 with open(target, "w", encoding="utf-8") as f:
104 f.write(text)
107def _copy_static(out_dir: Path) -> None:
108 """Copy the package's static assets into the output folder, once.
110 An existing static folder is left untouched, so rebuilding does not overwrite it.
111 """
112 static_src = Path(__file__).parent / "static"
113 static_dst = out_dir / "static"
114 if static_src.exists() and not static_dst.exists():
115 shutil.copytree(static_src, static_dst)
117def _write_warnings_report(warnings: list, out_dir: Path) -> None:
118 """Write the reader warnings to report.txt in the output folder.
120 Written only when there is something to report, so a build without warnings
121 leaves no file. An older report.txt is not removed: it may be the user's own.
122 """
123 if not warnings:
124 return
125 lines = [f"[{w['code']}] {w['message']}" for w in warnings]
126 _write_in(out_dir, "report.txt", "\n".join(lines) + "\n")
128def _page_data(viewer, lang: str, links: "_StaticLinks", resource: Optional[str] = None) -> dict:
129 """Return the contract data of one static page, without the reader warnings.
131 A published page cannot send the reader to a server log, and the same warnings are
132 already written to report.txt, so the page does not repeat them as toasts.
133 """
134 data = viewer.view(resource_uri=resource, language=lang, links=links)
135 data["model"]["warnings"] = []
136 return data
139def build_html(viewer, out_dir: Path, lang: str = "en",
140 artefact_name: str = "index") -> None:
141 """Write the whole static site for a viewer into `out_dir`.
143 Writes the index page, the serializations of the artefact and, under resources/,
144 one page plus serializations for each resource that belongs to the ontology
145 namespace or has local triples. Blocking and disk-heavy; existing files are
146 overwritten. A page is never written outside resources/, whatever the IRI.
147 `artefact_name` is the file stem of the root files (<name>.html, <name>.ttl, ...):
148 links back to the index use it, so a renamed index stays reachable. Resource
149 files are not affected, they are named after their IRI.
150 """
151 from collections import defaultdict
153 artefact_name = _check_artefact_name(artefact_name)
154 out_dir.mkdir(parents=True, exist_ok=True)
155 _copy_static(out_dir)
156 _write_warnings_report(viewer.format_warnings(viewer.artefact.warnings), out_dir)
158 artefact_ns = viewer.get_artefact_ns()
159 graph = viewer.artefact.graph
160 main_graph = viewer.artefact.main_graph()
162 def _in_main_graph(uri) -> bool:
163 """Tell whether the loaded artefact itself says something about this IRI.
165 Resources described only by imported modules get no page: their export
166 would be empty, as exports carry the triples of the loaded artefact only.
167 """
168 return (URIRef(str(uri)), None, None) in main_graph
170 grouped = defaultdict(list)
171 for inst in viewer.artefact.get_entities():
172 grouped[type(inst).__name__].append(inst)
174 toc_config = viewer.get_toc_config()
176 # URI that will actually get a file (same criterion as the loop below)
177 materialized = set()
178 for class_key, _sid, _t in toc_config:
179 for inst in grouped.get(class_key, []):
180 u = inst.get_has_identifier()
181 if not u:
182 continue
183 if not (u.startswith(artefact_ns) or _in_main_graph(u)):
184 continue
185 if _rel_slug(u, graph).rsplit("/", 1)[-1] == "": # namespace IRI, no local
186 continue
187 materialized.add(str(u))
189 env_index = _get_template_env(viewer.template_dirs(), static_path="static")
190 env_resource = _get_template_env(viewer.template_dirs(), static_path="../../static")
192 for fmt, ext in _SER:
193 _write_in(out_dir, f"{artefact_name}.{ext}", viewer.export_main(fmt))
195 template_index = env_index.get_template("page.html")
196 template_resource = env_resource.get_template("page.html")
198 # --- index.html ---
199 data = _page_data(viewer, lang, _StaticLinks(graph, materialized, artefact_name))
200 _write_in(out_dir, f"{artefact_name}.html", _minify(template_index.render(**data)))
202 if not toc_config:
203 return
205 res_dir = out_dir / "resources"
206 res_dir.mkdir(parents=True, exist_ok=True)
208 for class_key, section_id, _ in toc_config:
209 for inst in grouped.get(class_key, []):
210 uri = inst.get_has_identifier()
211 if not uri:
212 continue
213 native = uri.startswith(artefact_ns)
214 if not (native or _in_main_graph(uri)):
215 continue
217 rel = _rel_slug(uri, graph)
218 if rel.rsplit("/", 1)[-1] == "": # namespace IRI, no local part
219 continue
221 page = res_dir / f"{rel}.html"
222 # Defense in depth: even if a slug ever slipped through the
223 # whitelist, never write outside the resources directory.
224 if not page.resolve().is_relative_to(res_dir.resolve()):
225 continue
226 page.parent.mkdir(parents=True, exist_ok=True)
228 outputs = viewer.export_resource_all(uri, [fmt for fmt, _ in _SER])
229 for fmt, ext in _SER:
230 out = outputs[fmt]
231 if isinstance(out, bytes):
232 out = out.decode("utf-8")
233 (res_dir / f"{rel}.{ext}").write_text(out, encoding="utf-8")
235 links = _StaticLinks(graph, materialized, artefact_name, focus=uri)
236 data_r = _page_data(viewer, lang, links, uri)
237 page.write_text(_minify(template_resource.render(**data_r)), encoding="utf-8")
239class _StaticLinks(Links):
240 """The addresses inside a static site, seen from the page that is being written.
242 A site has two kinds of page: the index, at its root, and the page of a resource, two folders
243 deep (resources/<prefix>/<name>.html). A resource that gets no page of its own, such as one only
244 the imports describe, has no address here.
245 """
247 def __init__(self, graph, kept: set, artefact_name: str, focus: Optional[str] = None):
248 """`kept` holds the IRIs that get a page; `focus` is the resource this page is about, None for the index."""
249 self._graph = graph
250 self._kept = kept
251 self._name = artefact_name
252 self._focus = focus
254 def _up(self) -> str:
255 """The path from this page back to the root of the site."""
256 return "" if self._focus is None else "../../"
258 def _file(self, iri: str, ext: str) -> Optional[str]:
259 """The path of the file `ext` of a resource, or None when it has none."""
260 if str(iri) not in self._kept:
261 return None
262 rel = _rel_slug(iri, self._graph)
263 if rel.rsplit("/", 1)[-1] == "": # a bare namespace IRI stands for the whole artefact
264 return f"{self._up()}{self._name}.{ext}"
265 return f"resources/{rel}.{ext}" if self._focus is None else f"../{rel}.{ext}"
267 def resource(self, iri: str) -> Optional[str]:
268 """Return the page of a resource, or None when it has none."""
269 return self._file(iri, "html")
271 def export(self, ext: str, iri: Optional[str] = None) -> Optional[str]:
272 """Return the file of the artefact, or of a resource, in the format with extension `ext`."""
273 if iri is None:
274 return f"{self._up()}{self._name}.{ext}"
275 return self._file(iri, ext)
277 def home(self) -> str:
278 """Return the page of the whole artefact."""
279 return f"{self._up()}{self._name}.html"