Coverage for /builds/svesch/cikit/src/cikit/sphinx_ext/metrics.py: 100%

23 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-09 14:17 +0000

1# SPDX-License-Identifier: GPL-3.0-or-later 

2"""Sphinx extension for embedding cikit metrics in reStructuredText. 

3 

4The extension provides the ``cikit-metric`` role. Metric values are loaded 

5from the local cikit data cache and rendered as inline text during the Sphinx 

6build. Role targets use the form ``<run>.<key>``. 

7 

8Author: 

9 Sven Schlender 

10Date: 

11 2026-08-31 

12""" 

13 

14from pathlib import Path 

15 

16from docutils import nodes 

17from sphinx.errors import SphinxError 

18from sphinx.util.docutils import SphinxRole 

19 

20from cikit.data.common import load_run_data, lookup_key 

21 

22 

23class CikitMetricRole(SphinxRole): 

24 """Render one cikit metric as inline text. 

25 

26 The role resolves a target in ``<run>.<key>`` format. The run selects the 

27 corresponding JSON file in ``cikit_data_dir`` and the remaining dotted key 

28 is resolved inside that run data. 

29 """ 

30 

31 def run(self): 

32 """Resolve and render the referenced cikit metric. 

33 

34 Returns: 

35 Tuple containing generated inline nodes and system messages. 

36 

37 Raises: 

38 SphinxError: If the role target, data directory, or metric is invalid. 

39 """ 

40 run_name, separator, key = self.text.strip().partition(".") 

41 if not separator or not run_name or not key: 

42 raise SphinxError(f"Invalid cikit metric '{self.text}', expected '<run>.<key>'.") 

43 

44 data_dir = self.config.cikit_data_dir 

45 if not data_dir: 

46 raise SphinxError("The cikit_data_dir Sphinx configuration is not set.") 

47 

48 run_file = Path(data_dir) / f"{run_name}.json" 

49 data = load_run_data(run_file) 

50 value = lookup_key(data, key) 

51 

52 if value is None: 

53 raise SphinxError(f"Cikit metric '{self.text}' does not exist in '{run_file}'.") 

54 

55 return [nodes.inline(self.rawtext, str(value))], [] 

56 

57 

58def setup(app): 

59 """Register the cikit metrics Sphinx extension. 

60 

61 Args: 

62 app: Active Sphinx application. 

63 

64 Returns: 

65 Sphinx extension metadata. 

66 """ 

67 app.add_config_value("cikit_data_dir", "", "env") 

68 app.add_role("cikit-metric", CikitMetricRole()) 

69 

70 return {"version": "1.0", "parallel_read_safe": True,}