Coverage for trlcdoc/trace.py: 99%
187 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"""Create the LOBSTER tracing report from the configured trace levels."""
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 html
22import json
23import logging
24import os
25import re
26from pathlib import Path
27from typing import Any
29import yaml
31from .config import Config
32from .log import TRACE
33from .util import TrlcdocError, clean_dir, find_graphviz, find_tool, git_output, git_root, repository_url, run
35# Variables ********************************************************************
37LOG = logging.getLogger(__name__)
39# LOBSTER tracing status of items that are traced as required. Justified items
40# (e.g. marked with "lobster-exclude") count as covered in LOBSTER, too.
41TRACED_STATUS = ("OK", "JUSTIFIED")
43# Classes **********************************************************************
45# Functions ********************************************************************
48def build_trace_report(cfg: Config, online: bool) -> int:
49 # lobster-trace: SwRequirements.sw_req_trace_report
50 # lobster-trace: SwRequirements.sw_req_trace_findings
51 # lobster-trace: SwRequirements.sw_req_external_tools
52 # lobster-trace: SwRequirements.sw_req_verbose_output
53 """Extract the trace data of all levels and create the tracing report.
55 Args:
56 cfg (Config): Project configuration with a trace section.
57 online (bool): Link the report to the repository instead of local files.
59 Returns:
60 int: Number of items that are not traced as required.
62 Raises:
63 TrlcdocError: If Graphviz is missing, which the LOBSTER reports need for the tracing policy diagram.
64 """
65 # Without dot, the LOBSTER reports only warn and leave out the tracing policy diagram.
66 find_graphviz("for the tracing policy diagram of the tracing report")
67 trace_dir = clean_dir(cfg.trace_dir, cfg.output)
68 sources: dict[str, Path] = {}
70 for level in cfg.trace["levels"]:
71 out_file = trace_dir / f"{_slug(level['name'])}.lobster"
72 LOG.debug("Trace level %s (%s) -> %s", level["name"], level.get("kind", "requirements"), out_file)
73 match level.get("kind", "requirements"):
74 case "requirements":
75 _extract_trlc(cfg, level, out_file)
76 case "implementation":
77 _extract_code(cfg, level, out_file)
78 sources[level["name"]] = out_file
80 policy_file = _write_policy(cfg, sources, trace_dir / "lobster-report.conf")
81 report_file = trace_dir / "report.lobster"
82 run([find_tool("lobster-report"), "--lobster-config", str(policy_file), "--out", str(report_file)], cfg.root)
84 if online:
85 LOG.debug("Online report: item links point to the repository at the current commit")
86 _make_online(cfg, report_file)
88 LOG.debug("Tracing report format: %s", cfg.trace_report_format)
89 if cfg.trace_report_format == "rst":
90 _write_rst_report(cfg, report_file)
91 else:
92 _write_html_report(cfg, report_file)
93 return _print_summary(report_file)
96def _write_html_report(cfg: Config, report_file: Path) -> Path:
97 # lobster-trace: SwRequirements.sw_req_trace_report
98 """Create the HTML tracing report, which the html step embeds in a page at the root of the site.
100 The items of test results link to their row on the page of their document, relative to the site root.
102 Args:
103 cfg (Config): Project configuration.
104 report_file (Path): LOBSTER report.
106 Returns:
107 Path: The HTML tracing report.
108 """
109 with open(report_file, encoding="utf-8") as file:
110 report = json.load(file)
111 links = _link_test_results(cfg, report, ".html")
112 html_input = report_file.with_name("report_html.lobster")
113 html_input.write_text(json.dumps(report, indent=2), encoding="utf-8")
115 command = [find_tool("lobster-html-report"), "--out", str(cfg.trace_report_html)]
116 if cfg.trace.get("markdown", False):
117 command.append("--render-md")
118 run([*command, str(html_input)], cfg.root)
119 _replace_link_texts(cfg.trace_report_html, links)
120 return cfg.trace_report_html
123def _write_rst_report(cfg: Config, report_file: Path) -> Path:
124 # lobster-trace: SwRequirements.sw_req_trace_report_rst
125 """Create the tracing report as reStructuredText pages for the HTML site.
127 The local file references are made relative to the project root and prefixed with the path from a report page
128 back to the project root, so they work from the site. Repository links of an online report are kept.
129 The items of test results link to their row on the page of their document.
131 Args:
132 cfg (Config): Project configuration.
133 report_file (Path): LOBSTER report.
135 Returns:
136 Path: Folder with the report pages.
137 """
138 with open(report_file, encoding="utf-8") as file:
139 report = json.load(file)
140 for level in report["levels"]:
141 for item in level["items"]:
142 location = item.get("location", {})
143 if location.get("kind") == "file" and Path(location["file"]).is_relative_to(cfg.root):
144 location["file"] = Path(location["file"]).relative_to(cfg.root).as_posix()
145 links = _link_test_results(cfg, report, "")
146 rst_input = report_file.with_name("report_rst.lobster")
147 rst_input.write_text(json.dumps(report, indent=2), encoding="utf-8")
149 # The pages end up in a folder per document: <html>/<id>/<level>.html
150 source_root = Path(os.path.relpath(cfg.root, cfg.html_dir / "document")).as_posix()
151 run(
152 [
153 find_tool("lobster-rst-report"),
154 "--out-dir",
155 str(cfg.trace_report_rst),
156 "--source-root",
157 source_root,
158 str(rst_input),
159 ],
160 cfg.root,
161 )
162 _replace_page_links(cfg.trace_report_rst, source_root, links)
163 return cfg.trace_report_rst
166def _link_test_results(cfg: Config, report: dict[str, Any], suffix: str) -> dict[str, str]:
167 # lobster-trace: SwRequirements.sw_req_trace_report
168 # lobster-trace: SwRequirements.sw_req_trace_report_rst
169 """Link the items of test result levels to their row on the page of their test_results document.
171 The test result records are generated into the output folder, which neither the repository
172 nor the site contains. The reader wants to see the results anyway, not their records.
173 The items are found by their level, not by their location, which may be a local file or,
174 for an online report, a repository link.
176 Args:
177 cfg (Config): Project configuration with a trace section.
178 report (dict[str, Any]): LOBSTER report, updated in place.
179 suffix (str): Appended to the page name, e.g. '.html'.
181 Returns:
182 dict[str, str]: The new link targets, e.g. 'sw_test_results/index.html#<anchor>', with the record
183 names to show as link text.
184 """
185 level_pages: dict[str, str] = {}
186 for level in cfg.trace["levels"]:
187 if "document" not in level:
188 continue
189 doc = cfg.document(level["document"])
190 if doc["type"] == "test_results":
191 level_pages[level["name"]] = cfg.page_name(doc)
193 links: dict[str, str] = {}
194 for level in report["levels"]:
195 page = level_pages.get(level["name"])
196 if page is None:
197 continue
198 for item in level["items"]:
199 target = page + suffix
200 anchor = _test_result_anchor(item)
201 if anchor:
202 target += "#" + anchor
203 item["location"] = {"kind": "file", "file": target, "line": None, "column": None}
204 links[target] = _record_name(item)
205 LOG.log(TRACE, "Test result %s links to %s", item["name"], target)
206 return links
209def _record_name(item: dict[str, Any]) -> str:
210 # lobster-trace: SwRequirements.sw_req_trace_report
211 """Get the TRLC record name of a LOBSTER item.
213 Args:
214 item (dict[str, Any]): LOBSTER item of a TRLC record, named '<package>.<record>'.
216 Returns:
217 str: The record name without package, e.g. 'test_cli_result'.
218 """
219 return item["name"].rsplit(".", 1)[-1]
222def _test_result_anchor(item: dict[str, Any]) -> str:
223 # lobster-trace: SwRequirements.sw_req_trace_report
224 """Get the anchor of a test result row on the test results page.
226 builtin:create_test_report_in_rst.py gives every row the ID '<file>.rst-<record>', with the
227 name of the converted TRLC file and the record name in lowercase, e.g.
228 'sw_test_result_report.rst-test_cli_result'.
230 Args:
231 item (dict[str, Any]): LOBSTER item of a test result record, still with its TRLC location.
233 Returns:
234 str: The anchor, empty if the item has no file location.
235 """
236 file_name = item.get("location", {}).get("file")
237 if not file_name:
238 return ""
239 record = _record_name(item).lower().replace(" ", "-")
240 return f"{Path(file_name).stem}.rst-{record}"
243def _replace_link_texts(report_html: Path, links: dict[str, str]) -> None:
244 # lobster-trace: SwRequirements.sw_req_trace_report
245 """Show the record names as text of the test result links in the HTML report.
247 lobster-html-report shows the link target as text, which is long with the anchor.
249 Args:
250 report_html (Path): HTML tracing report, updated in place.
251 links (dict[str, str]): Link targets with the text to show.
252 """
253 text = report_html.read_text(encoding="utf-8")
254 for target, name in links.items():
255 old_text = f">{html.escape(target)}</a>"
256 count = text.count(old_text)
257 LOG.log(TRACE, "%s: link text %s replaced by %s (%d times)", report_html.name, target, name, count)
258 text = text.replace(old_text, f">{html.escape(name)}</a>")
259 report_html.write_text(text, encoding="utf-8")
262def _replace_page_links(rst_dir: Path, source_root: str, links: dict[str, str]) -> None:
263 # lobster-trace: SwRequirements.sw_req_trace_report_rst
264 """Replace the links of the reStructuredText report to site pages by links relative to the report page.
266 lobster-rst-report prefixes every file link with the path back to the project root, which is
267 wrong for a site page. The report pages are in a folder below the site root, and the pages of the
268 built site are '<page>.html'. The record name is the link text.
270 Args:
271 rst_dir (Path): Folder with the report pages, updated in place.
272 source_root (str): The prefix lobster-rst-report adds to file links.
273 links (dict[str, str]): Link targets '<page>' or '<page>#<anchor>' with the text to show.
274 """
275 for page_file in rst_dir.glob("*.rst"):
276 text = page_file.read_text(encoding="utf-8")
277 for target, name in links.items():
278 page, _, anchor = target.partition("#")
279 href = f"../{page}.html" + (f"#{anchor}" if anchor else "")
280 lobster_link = r"`[^`]*<" + re.escape(f"{source_root.rstrip('/')}/{target}") + r">`__"
281 # Record names and page names contain no backslash, which re.sub would interpret.
282 text, count = re.subn(lobster_link, f"`{name} <{href}>`__", text)
283 if count:
284 LOG.log(TRACE, "%s: link to %s replaced by %s (%d times)", page_file.name, target, href, count)
285 page_file.write_text(text, encoding="utf-8")
288def _slug(name: str) -> str:
289 # lobster-trace: SwRequirements.sw_req_trace_levels
290 """Convert a level name into a file name.
292 Args:
293 name (str): Level name, e.g. 'SW Requirement'.
295 Returns:
296 str: File name stem, e.g. 'sw_requirement'.
297 """
298 return re.sub(r"\W+", "_", name).strip("_").lower()
301def _extract_trlc(cfg: Config, level: dict[str, Any], out_file: Path) -> Path:
302 # lobster-trace: SwRequirements.sw_req_trace_levels
303 """Extract a TRLC requirements level with lobster-trlc.
305 Args:
306 cfg (Config): Project configuration.
307 level (dict[str, Any]): Trace level of kind requirements.
308 out_file (Path): LOBSTER output file.
310 Returns:
311 Path: The LOBSTER output file.
312 """
313 doc = cfg.document(level["document"])
314 package, record_type = level["record_type"].split(".")
315 inputs = [cfg.trlc_model, *cfg.trlc_sources(doc), *cfg.included_sources(doc)]
316 rule: dict[str, Any] = {
317 "package": package,
318 "record-type": record_type,
319 "namespace": cfg.trace.get("namespace", "req"),
320 "description-fields": level.get("description_fields", ["description"]),
321 }
322 if level.get("tags"):
323 rule["tags"] = level["tags"]
325 config_file = out_file.with_suffix(".yaml")
326 with open(config_file, "w", encoding="utf-8") as file:
327 yaml.safe_dump({"inputs": [str(path) for path in inputs], "conversion-rules": [rule]}, file, sort_keys=False)
329 run([find_tool("lobster-trlc"), "--config", str(config_file), "--out", str(out_file)], cfg.root)
330 return out_file
333def _extract_code(cfg: Config, level: dict[str, Any], out_file: Path) -> Path:
334 # lobster-trace: SwRequirements.sw_req_trace_levels
335 # lobster-trace: SwRequirements.sw_req_trace_doxygen
336 """Extract an implementation level from source code.
338 Args:
339 cfg (Config): Project configuration.
340 level (dict[str, Any]): Trace level of kind implementation.
341 out_file (Path): LOBSTER output file.
343 Returns:
344 Path: The LOBSTER output file.
345 """
346 if level["extractor"] == "lobster-doxygen":
347 return _extract_doxygen(cfg, level, out_file)
348 sources = [str(cfg.path(source)) for source in level["sources"]]
349 run([find_tool(level["extractor"]), "--out", str(out_file), *sources], cfg.root)
350 return out_file
353def _extract_doxygen(cfg: Config, level: dict[str, Any], out_file: Path) -> Path:
354 # lobster-trace: SwRequirements.sw_req_trace_doxygen
355 """Extract an implementation level from C/C++ sources with doxygen and lobster-doxygen.
357 Doxygen runs in the folder of the configured Doxyfile, so its relative paths keep
358 working. The Doxyfile is included unchanged and followed by settings that write
359 only the XML output into the trace folder.
361 Args:
362 cfg (Config): Project configuration.
363 level (dict[str, Any]): Trace level of kind implementation with a doxyfile.
364 out_file (Path): LOBSTER output file.
366 Returns:
367 Path: The LOBSTER output file.
368 """
369 doxygen = find_tool(
370 "doxygen",
371 f"It is needed by the lobster-doxygen extractor of trace level '{level['name']}', see https://www.doxygen.nl.",
372 )
373 doxyfile = cfg.path(level["doxyfile"])
374 doxygen_dir = out_file.with_name(f"{out_file.stem}-doxygen")
375 settings = [
376 f'@INCLUDE = "{doxyfile.as_posix()}"',
377 f'OUTPUT_DIRECTORY = "{doxygen_dir.as_posix()}"',
378 "GENERATE_XML = YES",
379 "XML_OUTPUT = xml",
380 "GENERATE_HTML = NO",
381 "GENERATE_LATEX = NO",
382 "GENERATE_RTF = NO",
383 "GENERATE_MAN = NO",
384 "GENERATE_DOCBOOK = NO",
385 ]
386 run([doxygen, "-"], doxyfile.parent, stdin="\n".join(settings) + "\n")
387 run([find_tool("lobster-doxygen"), "-o", str(out_file), str(doxygen_dir / "xml")], cfg.root)
388 return _absolute_locations(out_file, doxyfile.parent)
391def _absolute_locations(lobster_file: Path, base: Path) -> Path:
392 # lobster-trace: SwRequirements.sw_req_trace_doxygen
393 """Make the relative file locations of a LOBSTER file absolute.
395 Doxygen strips the folder it runs in from the file paths (STRIP_FROM_PATH), so lobster-doxygen
396 writes them relative to the folder of the Doxyfile. The report links need them absolute, like
397 the locations of the other levels.
399 See also: https://github.com/NewTec-GmbH/lobster-doxygen/issues/68
401 Args:
402 lobster_file (Path): LOBSTER file, updated in place.
403 base (Path): Folder the relative paths refer to.
405 Returns:
406 Path: The updated LOBSTER file.
407 """
408 data = json.loads(lobster_file.read_text(encoding="utf-8"))
409 for item in data.get("data", []):
410 location = item.get("location", {})
411 if location.get("kind") == "file" and not Path(location["file"]).is_absolute():
412 location["file"] = str((base / location["file"]).resolve())
413 lobster_file.write_text(json.dumps(data, indent=2), encoding="utf-8")
414 return lobster_file
417def _write_policy(cfg: Config, sources: dict[str, Path], policy_file: Path) -> Path:
418 # lobster-trace: SwRequirements.sw_req_trace_levels
419 """Write the lobster-report policy for the configured levels.
421 Args:
422 cfg (Config): Project configuration.
423 sources (dict[str, Path]): LOBSTER file per level name.
424 policy_file (Path): Policy file to write.
426 Returns:
427 Path: The written policy file.
428 """
429 blocks: list[str] = []
430 for level in cfg.trace["levels"]:
431 lines = [
432 f'{level.get("kind", "requirements")} "{level["name"]}" {{',
433 f' source: "{sources[level["name"]].as_posix()}";',
434 ]
435 lines.extend(f' trace to: "{target}";' for target in level.get("trace_to", []))
436 lines.extend(f' requires: "{target}";' for target in level.get("requires", []))
437 lines.append("}")
438 blocks.append("\n".join(lines))
439 policy_file.write_text("\n\n".join(blocks) + "\n", encoding="utf-8")
440 return policy_file
443def _make_online(cfg: Config, report_file: Path) -> Path:
444 # lobster-trace: SwRequirements.sw_req_trace_report
445 """Replace the local file references of the report by repository links.
447 Args:
448 cfg (Config): Project configuration.
449 report_file (Path): LOBSTER report, updated in place.
451 Returns:
452 Path: The updated report file.
454 Raises:
455 TrlcdocError: If the commit id cannot be determined.
456 """
457 commit_id = git_output(["rev-parse", "HEAD"], cfg.root)
458 repo_root = git_root(cfg.root)
459 if commit_id is None or repo_root is None:
460 raise TrlcdocError("Online report needs a git repository ('git rev-parse HEAD' failed).")
462 online_cfg = report_file.with_name("online_report_config.yaml")
463 with open(online_cfg, "w", encoding="utf-8") as file:
464 yaml.safe_dump(
465 {
466 "report": str(report_file),
467 "commit_id": commit_id,
468 "repo_root": str(repo_root),
469 "base_url": repository_url(cfg.repository, cfg.root),
470 },
471 file,
472 )
474 online_report = report_file.with_suffix(".online")
475 run([find_tool("lobster-online-report"), "--config", str(online_cfg), "--out", str(online_report)], cfg.root)
476 online_report.replace(report_file)
477 return report_file
480def _print_summary(report_file: Path) -> int:
481 # lobster-trace: SwRequirements.sw_req_trace_findings
482 """Print the number of items per level that are not traced as required.
484 Items that LOBSTER reports as justified (e.g. by a "lobster-exclude" comment)
485 count as traced, like in the coverage of the LOBSTER report.
487 Args:
488 report_file (Path): LOBSTER report.
490 Returns:
491 int: Total number of items that are not traced as required.
492 """
493 with open(report_file, encoding="utf-8") as file:
494 report = json.load(file)
496 total = 0
497 LOG.info("Tracing:")
498 for level in report["levels"]:
499 missing = [item["tag"] for item in level["items"] if item.get("tracing_status") not in TRACED_STATUS]
500 justified = sum(item.get("tracing_status") == "JUSTIFIED" for item in level["items"])
501 total += len(missing)
502 line = f" {level['name']}: {len(level['items'])} items, {len(missing)} not traced"
503 if justified:
504 line += f", {justified} justified"
505 LOG.info("%s", line)
506 for tag in missing:
507 LOG.info(" %s", tag)
508 return total
511# Main *************************************************************************