Coverage for trlcdoc/html.py: 96%
212 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
1"""Generate the Sphinx sources from the configured documents and build the HTML site."""
3# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents.
4# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de
5#
6# This file is part of trlcdoc program.
7#
8# The trlcdoc program is free software: you can redistribute it and/or modify it under
9# the terms of the GNU General Public License as published by the Free Software Foundation,
10# either version 3 of the License, or (at your option) any later version.
11#
12# The trlcdoc program is distributed in the hope that it will be useful, but
13# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License along with pyTRLCConverter.
17# If not, see <https://www.gnu.org/licenses/>.
19# Imports **********************************************************************
21import json
22import logging
23import os
24import platform
25import re
26import shutil
27import subprocess
28import webbrowser
29from pathlib import Path
30from typing import Any
32from sphinx.cmd.build import build_main
34from .config import PACKAGE_DIR, Config
35from .log import TRACE
36from .pages import replace_placeholders
37from .util import TrlcdocError, clean_dir, find_graphviz, git_output, git_root, repository_url, run
39# Variables ********************************************************************
41SPHINX_TEMPLATE_DIR = PACKAGE_DIR / "sphinx"
43LOG = logging.getLogger(__name__)
45# Included converter output gets this suffix, so Sphinx does not treat it as a document.
46INCLUDE_SUFFIX = ".inc"
48# Sphinx extensions of the reStructuredText tracing report: dropdown cards and the tracing policy diagram.
49RST_TRACE_REPORT_EXTENSIONS = ["sphinx_design", "sphinx.ext.graphviz"]
51# Underline character of the page titles. reStructuredText derives the heading level
52# from the order the characters appear in a page. pyTRLCConverter underlines its
53# levels with = # ~ ^ " + ', so '-' keeps the page title above the included content.
54PAGE_TITLE_CHAR = "-"
56# Classes **********************************************************************
58# Functions ********************************************************************
61def build_html(cfg: Config) -> Path:
62 # lobster-trace: SwRequirements.sw_req_html_site
63 # lobster-trace: SwRequirements.sw_req_external_tools
64 """Generate the Sphinx source folder and build the HTML site.
66 Args:
67 cfg (Config): Project configuration.
69 Returns:
70 Path: The HTML output folder.
72 Raises:
73 TrlcdocError: If an input or Graphviz is missing, or Sphinx reports an error.
74 """
75 if "sphinx.ext.graphviz" in _extensions(cfg):
76 find_graphviz("by the Sphinx extension sphinx.ext.graphviz")
77 src_dir = clean_dir(cfg.sphinx_dir, cfg.output)
78 shutil.copy(SPHINX_TEMPLATE_DIR / "conf.py", src_dir / "conf.py")
79 shutil.copytree(SPHINX_TEMPLATE_DIR / "_static", src_dir / "_static")
81 pages: list[str] = []
82 copy_dirs: list[dict[str, str]] = []
83 for doc in cfg.documents:
84 pages.append(_write_page(cfg, doc, src_dir, copy_dirs))
86 _write_index(cfg, src_dir, pages)
87 _write_sphinx_config(cfg, src_dir, copy_dirs)
89 out_dir = clean_dir(cfg.html_dir, cfg.output)
90 # The Sphinx doctree cache is kept out of the HTML site.
91 doctrees_dir = clean_dir(cfg.output / "doctrees", cfg.output)
92 LOG.info("Building HTML -> %s", out_dir)
93 if build_main(["-b", "html", *_sphinx_verbosity(), "-d", str(doctrees_dir), str(src_dir), str(out_dir)]) != 0:
94 raise TrlcdocError("Sphinx HTML build failed.")
95 return out_dir
98def _sphinx_verbosity() -> list[str]:
99 # lobster-trace: SwRequirements.sw_req_verbose_output
100 """Get the Sphinx option for the verbosity of trlcdoc.
102 Returns:
103 list[str]: '-q' (warnings and errors only) by default, nothing with -v, '-v' with -vv.
104 """
105 if LOG.isEnabledFor(TRACE):
106 return ["-v"]
107 if LOG.isEnabledFor(logging.DEBUG):
108 return []
109 return ["-q"]
112def show_html(cfg: Config) -> Path:
113 # lobster-trace: SwRequirements.sw_req_show
114 """Open the start page of the built HTML site in the web browser.
116 Under WSL, the site opens in the Windows default browser (wslview or explorer.exe).
117 Without Windows interop, and on all other systems, the Python webbrowser module
118 selects the browser, which the BROWSER environment variable can override.
120 Args:
121 cfg (Config): Project configuration.
123 Returns:
124 Path: The opened start page.
126 Raises:
127 TrlcdocError: If the site is not built or no web browser is available.
128 """
129 index = cfg.html_dir / "index.html"
130 if not index.is_file():
131 raise TrlcdocError(f"No HTML site found at {index}, run the html step first.")
133 LOG.info("Opening %s", index)
134 if not (_is_wsl() and _open_in_windows(index)):
135 try:
136 opened = webbrowser.get().open(index.as_uri())
137 except webbrowser.Error:
138 opened = False
139 if not opened:
140 raise TrlcdocError(
141 f"No web browser found to open {index}. Set the BROWSER environment variable "
142 "to the command of a web browser, or open the file manually."
143 )
144 return index
147def _is_wsl() -> bool:
148 # lobster-trace: SwRequirements.sw_req_show
149 """Check whether trlcdoc runs in the Windows Subsystem for Linux.
151 Returns:
152 bool: True under WSL.
153 """
154 return "WSL_DISTRO_NAME" in os.environ or "microsoft" in platform.uname().release.lower()
157def _open_in_windows(index: Path) -> bool:
158 # lobster-trace: SwRequirements.sw_req_show
159 """Open a file of the WSL file system in the Windows default browser.
161 Args:
162 index (Path): The page to open.
164 Returns:
165 bool: True if the page was handed to Windows, False without Windows interop.
166 """
167 cmd: list[str] | None = None
168 wslview = shutil.which("wslview")
169 explorer = shutil.which("explorer.exe")
170 if wslview is not None:
171 cmd = [wslview, str(index)]
172 elif explorer is not None:
173 windows_path = _windows_path(index)
174 if windows_path is not None:
175 cmd = [explorer, windows_path]
177 if cmd is not None:
178 # explorer.exe returns 1 also on success, so the exit code is not checked.
179 subprocess.run(cmd, check=False)
181 return cmd is not None
184def _windows_path(path: Path) -> str | None:
185 # lobster-trace: SwRequirements.sw_req_show
186 """Convert a WSL path into a Windows path with wslpath.
188 Args:
189 path (Path): Path in the WSL file system.
191 Returns:
192 str | None: The Windows path, or None if wslpath failed.
193 """
194 result = None
195 try:
196 proc = subprocess.run(["wslpath", "-w", str(path)], capture_output=True, text=True, check=False)
197 if proc.returncode == 0 and proc.stdout.strip():
198 result = proc.stdout.strip()
199 except OSError:
200 result = None
202 return result
205def _heading(title: str, char: str = PAGE_TITLE_CHAR) -> str:
206 # lobster-trace: SwRequirements.sw_req_html_site
207 """Create a reStructuredText heading.
209 Args:
210 title (str): Heading text.
211 char (str): Underline character, defaults to the page title character.
213 Returns:
214 str: The heading with a trailing empty line.
215 """
216 return f"{title}\n{char * len(title)}\n\n"
219def _write_page(cfg: Config, doc: dict[str, Any], src_dir: Path, copy_dirs: list[dict[str, str]]) -> str:
220 # lobster-trace: SwRequirements.sw_req_documents
221 # lobster-trace: SwRequirements.sw_req_document_types
222 """Write the Sphinx page of a document.
224 Args:
225 cfg (Config): Project configuration.
226 doc (dict[str, Any]): Document configuration.
227 src_dir (Path): Sphinx source folder.
228 copy_dirs (list[dict[str, str]]): Collects HTML folders to copy into the site.
230 Returns:
231 str: Page name for the table of contents.
233 Raises:
234 TrlcdocError: If an input of the document is missing.
235 """
236 doc_type = doc["type"]
237 page_file = src_dir / f"{doc['id']}.rst"
238 LOG.log(TRACE, "Page %s: document %s of type %s", cfg.page_name(doc), doc["id"], doc_type)
240 # The schema allows only these document types, so every type has a case.
241 match doc_type:
242 case "trlc" | "test_results":
243 _write_converted_page(cfg, doc, src_dir)
245 case "trace_report" if cfg.trace_report_format == "rst":
246 _write_rst_trace_report(cfg, doc, src_dir)
248 case "trace_report":
249 _require(cfg.trace_report_html, "run the trace step first")
250 _write_generated(cfg, page_file, doc, f".. raw:: html\n :file: {cfg.trace_report_html.as_posix()}\n")
252 case "html" | "command":
253 if doc_type == "command":
254 run(doc["command"], cfg.root, source=f"documents[{doc['id']}].command")
255 html_source = cfg.html_source(doc)
256 _require(html_source / "index.html", "generate it first")
257 copy_dirs.append({"source": str(html_source), "destination": doc["id"]})
258 LOG.debug("HTML folder %s is copied into the site as %s", html_source, doc["id"])
259 _write_generated(
260 cfg,
261 page_file,
262 doc,
263 f'.. raw:: html\n\n <iframe src="{doc["id"]}/index.html" width="100%" height="1024px"></iframe>\n',
264 )
266 case "text":
267 source = _require(cfg.path(doc["source"]), "check the source path")
268 # Sphinx treats absolute include paths as relative to the source folder.
269 relative = Path(os.path.relpath(source, src_dir)).as_posix()
270 _write_generated(cfg, page_file, doc, f".. literalinclude:: {relative}\n :language: none\n")
272 case "rst" | "markdown":
273 source = _require(cfg.path(doc["source"]), "check the source path")
274 page_file = page_file.with_suffix(".md" if doc_type == "markdown" else ".rst")
275 _write_project_page(cfg, source, page_file, doc.get("placeholders", True))
277 return cfg.page_name(doc)
280def _write_project_page(cfg: Config, source: Path, page_file: Path, placeholders: bool = True) -> Path:
281 # lobster-trace: SwRequirements.sw_req_document_types
282 # lobster-trace: SwRequirements.sw_req_html_customization
283 """Write a project owned page into the Sphinx source folder.
285 Args:
286 cfg (Config): Project configuration.
287 source (Path): The project page.
288 page_file (Path): The page in the Sphinx source folder.
289 placeholders (bool): Replace the placeholders, False copies the page unchanged.
291 Returns:
292 Path: The written page.
293 """
294 text = source.read_text(encoding="utf-8")
295 if placeholders:
296 text = replace_placeholders(cfg, text, page_file)
297 page_file.write_text(text, encoding="utf-8")
298 return page_file
301def _write_generated(cfg: Config, page_file: Path, doc: dict[str, Any], body: str) -> Path:
302 # lobster-trace: SwRequirements.sw_req_documents
303 # lobster-trace: SwRequirements.sw_req_html_customization
304 """Write a generated page: the page header, the title of the document and the body.
306 Args:
307 cfg (Config): Project configuration.
308 page_file (Path): The page in the Sphinx source folder.
309 doc (dict[str, Any]): Document configuration, a page without title gets no heading.
310 body (str): Page content below the title.
312 Returns:
313 Path: The written page.
314 """
315 content = _page_header(cfg, page_file)
316 if "title" in doc:
317 content += _heading(doc["title"])
318 page_file.write_text(content + body, encoding="utf-8")
319 return page_file
322def _page_header(cfg: Config, page_file: Path) -> str:
323 # lobster-trace: SwRequirements.sw_req_html_customization
324 """Get the configured page header for a generated page.
326 Args:
327 cfg (Config): Project configuration.
328 page_file (Path): The page in the Sphinx source folder.
330 Returns:
331 str: The page header followed by a blank line, or an empty string without page header.
332 """
333 if "page_header" not in cfg.html:
334 return ""
335 header = cfg.path(cfg.html["page_header"]).read_text(encoding="utf-8")
336 return replace_placeholders(cfg, header, page_file).rstrip("\n") + "\n\n"
339def _write_rst_trace_report(cfg: Config, doc: dict[str, Any], src_dir: Path) -> str:
340 # lobster-trace: SwRequirements.sw_req_trace_report_rst
341 """Write the reStructuredText tracing report as a folder of pages.
343 The LOBSTER start page is included below the configured title, the level pages get the page header.
345 Args:
346 cfg (Config): Project configuration.
347 doc (dict[str, Any]): Document of type trace_report.
348 src_dir (Path): Sphinx source folder.
350 Returns:
351 str: Page name for the table of contents.
352 """
353 _require(cfg.trace_report_rst / "index.rst", "run the trace step first")
354 page_dir = src_dir / doc["id"]
355 shutil.copytree(cfg.trace_report_rst, page_dir)
357 for page_file in page_dir.glob("*.rst"):
358 if page_file.name != "index.rst":
359 page_file.write_text(_page_header(cfg, page_file) + page_file.read_text(encoding="utf-8"), encoding="utf-8")
361 # The configured title replaces the LOBSTER title, a heading with over- and underline.
362 start = (page_dir / "index.rst").read_text(encoding="utf-8")
363 start = re.sub(r"\A(#+)\n.+\n\1\n+", "", start)
364 include = page_dir / ("report" + INCLUDE_SUFFIX)
365 include.write_text(start, encoding="utf-8")
366 _write_generated(cfg, page_dir / "index.rst", doc, f".. include:: {include.name}\n")
367 return cfg.page_name(doc)
370def _write_converted_page(cfg: Config, doc: dict[str, Any], src_dir: Path) -> str:
371 # lobster-trace: SwRequirements.sw_req_documents
372 # lobster-trace: SwRequirements.sw_req_document_types
373 """Write the page of a converted TRLC document.
375 The converter output and its images are placed into a folder per document,
376 next to the page including them, so relative image references resolve.
378 Args:
379 cfg (Config): Project configuration.
380 doc (dict[str, Any]): Document of type trlc or test_results.
381 src_dir (Path): Sphinx source folder.
383 Returns:
384 str: Page name for the table of contents.
386 Raises:
387 TrlcdocError: If the converted document is missing.
388 """
389 converted = cfg.convert_dir("rst", doc["id"])
390 rst_files = sorted(converted.glob("*.rst"))
391 if not rst_files:
392 raise TrlcdocError(f"No converted files in {converted}, run the convert step first.")
394 page_dir = src_dir / doc["id"]
395 shutil.copytree(converted, page_dir)
396 content = ""
397 for rst_file in rst_files:
398 include = (page_dir / rst_file.name).rename(page_dir / (rst_file.stem + INCLUDE_SUFFIX))
399 content += f".. include:: {include.name}\n\n"
400 _write_generated(cfg, page_dir / "index.rst", doc, content)
401 return cfg.page_name(doc)
404def _require(path: Path, hint: str) -> Path:
405 # lobster-trace: SwRequirements.sw_req_document_types
406 """Ensure an input file exists.
408 Args:
409 path (Path): The required file.
410 hint (str): What to do if it is missing.
412 Returns:
413 Path: The file.
415 Raises:
416 TrlcdocError: If the file is missing.
417 """
418 if not path.exists():
419 raise TrlcdocError(f"{path} not found, {hint}.")
420 return path
423def _write_index(cfg: Config, src_dir: Path, pages: list[str]) -> Path:
424 # lobster-trace: SwRequirements.sw_req_html_site
425 # lobster-trace: SwRequirements.sw_req_html_customization
426 """Write the start page with the table of contents, or the project owned start page.
428 Args:
429 cfg (Config): Project configuration.
430 src_dir (Path): Sphinx source folder.
431 pages (list[str]): Page names in table of contents order.
433 Returns:
434 Path: The written index.rst.
435 """
436 index = src_dir / "index.rst"
437 if "index" in cfg.html:
438 _write_project_page(cfg, cfg.path(cfg.html["index"]), index)
439 else:
440 content = _heading(f"{_project_title(cfg)} documentation", "=")
441 content += ".. toctree::\n :maxdepth: 1\n :caption: Contents:\n\n"
442 content += "".join(f" {page}\n" for page in pages)
443 _write_generated(cfg, index, {}, content)
444 return index
447def _project_title(cfg: Config) -> str:
448 # lobster-trace: SwRequirements.sw_req_project_settings
449 """Get the project name, followed by the project version if configured.
451 Args:
452 cfg (Config): Project configuration.
454 Returns:
455 str: Name and version of the project.
456 """
457 return " ".join(filter(None, [cfg.project["name"], cfg.project.get("version")]))
460def _write_sphinx_config(cfg: Config, src_dir: Path, copy_dirs: list[dict[str, str]]) -> Path:
461 # lobster-trace: SwRequirements.sw_req_project_settings
462 # lobster-trace: SwRequirements.sw_req_html_customization
463 """Write the project settings read by the generic conf.py.
465 Args:
466 cfg (Config): Project configuration.
467 src_dir (Path): Sphinx source folder.
468 copy_dirs (list[dict[str, str]]): HTML folders to copy into the site.
470 Returns:
471 Path: The written settings file.
472 """
473 logo = cfg.project.get("logo")
474 favicon = cfg.project.get("favicon")
475 conf = cfg.html.get("conf")
476 settings = {
477 "project": cfg.project["name"],
478 "version": cfg.project.get("version"),
479 "author": cfg.project["author"],
480 "copyright": cfg.project["copyright"],
481 "logo": str(cfg.path(logo)) if logo else None,
482 "favicon": str(cfg.path(favicon)) if favicon else None,
483 "theme": cfg.html.get("theme", "haiku"),
484 "extensions": _extensions(cfg),
485 "extra_conf": cfg.html.get("extra_conf", {}),
486 "conf": str(cfg.path(conf)) if conf else None,
487 "copy_dirs": copy_dirs,
488 "project_root": str(cfg.root),
489 "build_info": _build_info(cfg),
490 "links": _link_settings(cfg),
491 # Configured titles of project pages, which override the first heading of the file.
492 "page_titles": {
493 doc["id"]: doc["title"] for doc in cfg.documents if doc["type"] in ("rst", "markdown") and "title" in doc
494 },
495 }
496 settings_file = src_dir / "trlcdoc_settings.json"
497 settings_file.write_text(json.dumps(settings, indent=4), encoding="utf-8")
498 return settings_file
501def _extensions(cfg: Config) -> list[str]:
502 # lobster-trace: SwRequirements.sw_req_trace_report_rst
503 """Get the configured Sphinx extensions, plus the ones the reStructuredText tracing report needs.
505 Args:
506 cfg (Config): Project configuration.
508 Returns:
509 list[str]: Sphinx extensions in addition to the default ones.
510 """
511 extensions = list(cfg.html.get("extensions", []))
512 if cfg.trace_report_format == "rst" and any(doc["type"] == "trace_report" for doc in cfg.documents):
513 extensions += [ext for ext in RST_TRACE_REPORT_EXTENSIONS if ext not in extensions]
514 return extensions
517def _build_info(cfg: Config) -> str:
518 # lobster-trace: SwRequirements.sw_req_html_version_info
519 """Describe the version control state the site is built from, for the page footer.
521 Args:
522 cfg (Config): Project configuration.
524 Returns:
525 str: ' from <git describe output>', followed by ' on branch <name>' if HEAD is on a branch,
526 e.g. ' from V1.0.0-3-g1a2b3c4-dirty on branch develop'. Empty outside of a git repository.
527 """
528 info = ""
529 # --always falls back to the short commit hash if there is no tag,
530 # --dirty marks uncommitted changes of tracked files.
531 describe = git_output(["describe", "--tags", "--always", "--dirty"], cfg.root)
532 if describe:
533 info = f" from {describe}"
534 # Empty for a detached HEAD, e.g. a tag checkout or a pull request merge commit in CI.
535 branch = git_output(["branch", "--show-current"], cfg.root)
536 if branch:
537 info += f" on branch {branch}"
538 return info
541def _link_settings(cfg: Config) -> dict[str, Any]:
542 # lobster-trace: SwRequirements.sw_req_markdown_links
543 """Collect the settings to resolve the relative links of Markdown pages against the project.
545 Args:
546 cfg (Config): Project configuration.
548 Returns:
549 dict[str, Any]: The project root, the Markdown file of each Markdown page, the site page
550 of each project file and folder shown in the site, and the repository, the path of the
551 project root in the repository and the commit for links to other project files
552 (repository and commit None if not available).
553 """
554 pages: dict[str, str] = {}
555 markdown_sources: dict[str, str] = {}
556 for doc in cfg.documents:
557 if "source" in doc and doc["type"] in ("trlc", "rst", "markdown", "text"):
558 source = Path(os.path.relpath(cfg.path(doc["source"]), cfg.root)).as_posix()
559 pages[source] = cfg.page_name(doc)
560 if doc["type"] == "markdown":
561 markdown_sources[doc["id"]] = source
563 commit = git_output(["rev-parse", "HEAD"], cfg.root)
564 repo_root = git_root(cfg.root)
565 repository = None
566 repository_path = "."
567 if commit is not None and repo_root is not None:
568 try:
569 repository = repository_url(cfg.repository, cfg.root)
570 except TrlcdocError:
571 repository = None
572 # The project may be a subfolder of the repository.
573 repository_path = Path(os.path.relpath(cfg.root, repo_root)).as_posix()
574 return {
575 "root": str(cfg.root),
576 "markdown_sources": markdown_sources,
577 "pages": pages,
578 "repository": repository,
579 "repository_path": repository_path,
580 "commit": commit,
581 }
584# Main *************************************************************************