Coverage for lode / viewer / helpers.py: 93%
42 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"""Stateless helpers shared by the viewers.
3Nothing here needs a Reader or a model entity: serialization formats, the
4deterministic order of the header metadata, label cleaning, URL heuristics and
5the loader of the per-format YAML configuration.
6"""
7import re
8from pathlib import Path
9from typing import Dict, Optional, Tuple
10import yaml
12from lode.profiles import Profile
14_CONFIG_DIR = Path(__file__).parent / "config"
17# ==========================================================================
18# 1. SERIALIZATION
19# ==========================================================================
20# The format lists live in lode.helpers.formats: the builder and the API need
21# them too and must not import a viewer for a constant.
23def safe_serialize(g, fmt: str) -> str:
24 """Serialize a graph, returning a comment with the error instead of raising.
26 One format that fails must not break the page that shows all of them.
27 """
28 try:
29 return g.serialize(format=fmt)
30 except Exception as e:
31 return f"# serialization error ({fmt}): {e}"
34# ==========================================================================
35# 2. HEADER METADATA ORDER
36# ==========================================================================
38_ANNOTATION_ORDER_FILE = _CONFIG_DIR / "model_annotations_deterministic_sorting.yaml"
41def _normalize_annotation_key(key: str) -> str:
42 """Reduce a displayed metadata key to a comparable form.
44 Case, spaces, underscores and hyphens are dropped so that 'version info',
45 'versionInfo' and 'version_info' land in the same slot of the order list.
46 """
47 return re.sub(r"[\s_\-]+", "", key.lower())
50def _load_annotation_order() -> Dict[str, int]:
51 """Read the YAML order list and map each normalized key to its rank.
53 Loaded once at import time. A missing or malformed file raises: a silent
54 fallback would make the page order depend on the environment again.
55 """
56 with open(_ANNOTATION_ORDER_FILE, encoding="utf-8") as f:
57 order = yaml.safe_load(f)["order"]
58 return {_normalize_annotation_key(k): i for i, k in enumerate(order)}
61_ANNOTATION_RANK = _load_annotation_order()
64def annotation_sort_key(key: str) -> Tuple[int, str]:
65 """Sort key for a header metadata entry: configured rank, then alphabetical.
67 Unlisted keys get a rank past the last listed one, so they follow the known
68 ones and stay in alphabetical order among themselves.
69 """
70 return (_ANNOTATION_RANK.get(_normalize_annotation_key(key), len(_ANNOTATION_RANK)), key.lower())
73# ==========================================================================
74# 3. LABELS AND URLS
75# ==========================================================================
77def clean_name(name: str, vocabulary: Optional[Dict[str, str]] = None) -> str:
78 """Turn an attribute or getter name into a display label.
80 Drops the has_/get_ prefix, splits camelCase, replaces underscores with
81 spaces and lowercases. The vocabulary of the viewer (internal word -> shown
82 word) is applied last, on whole words only, so that e.g. "concept" does not
83 touch "conceptual".
84 """
85 if not name:
86 return ""
88 name = re.sub(r'^(get_has_|get_|has_)', '', name)
89 # Put space between camelCase letters
90 name = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', name)
91 name = name.replace('_', ' ')
93 # Strip extra spaces and lowercase everything
94 name = ' '.join(name.split()).lower()
96 for word, shown in (vocabulary or {}).items():
97 name = re.sub(rf'\b{re.escape(word)}\b', shown, name)
99 return name
102# ==========================================================================
103# 4. PER-FORMAT VIEWER CONFIGURATION
104# ==========================================================================
106_REQUIRED_CONFIG_KEYS = ("type_map", "toc")
109def load_viewer_config(profile: Profile) -> dict:
110 """Read viewer.yaml from the folder of `profile` and fill in the optional keys.
113 The file holds the data that differs between formats (display names, table
114 of contents, display vocabulary), so the viewer classes carry no per-format data.
115 A missing file or required key raises: a silent default would change the page without any trace.
116 """
117 path = profile.path() / "viewer.yaml"
118 with open(path, encoding="utf-8") as f:
119 config = yaml.safe_load(f)
120 missing = [k for k in _REQUIRED_CONFIG_KEYS if k not in config]
121 if missing:
122 raise ValueError(f"{path.name}: missing required keys {missing}")
123 config.setdefault("vocabulary", {})
124 config.setdefault("characteristics", [])
125 return config