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

1"""Stateless helpers shared by the viewers. 

2 

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 

11 

12from lode.profiles import Profile 

13 

14_CONFIG_DIR = Path(__file__).parent / "config" 

15 

16 

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. 

22 

23def safe_serialize(g, fmt: str) -> str: 

24 """Serialize a graph, returning a comment with the error instead of raising. 

25 

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}" 

32 

33 

34# ========================================================================== 

35# 2. HEADER METADATA ORDER 

36# ========================================================================== 

37 

38_ANNOTATION_ORDER_FILE = _CONFIG_DIR / "model_annotations_deterministic_sorting.yaml" 

39 

40 

41def _normalize_annotation_key(key: str) -> str: 

42 """Reduce a displayed metadata key to a comparable form. 

43 

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()) 

48 

49 

50def _load_annotation_order() -> Dict[str, int]: 

51 """Read the YAML order list and map each normalized key to its rank. 

52 

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)} 

59 

60 

61_ANNOTATION_RANK = _load_annotation_order() 

62 

63 

64def annotation_sort_key(key: str) -> Tuple[int, str]: 

65 """Sort key for a header metadata entry: configured rank, then alphabetical. 

66 

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()) 

71 

72 

73# ========================================================================== 

74# 3. LABELS AND URLS 

75# ========================================================================== 

76 

77def clean_name(name: str, vocabulary: Optional[Dict[str, str]] = None) -> str: 

78 """Turn an attribute or getter name into a display label. 

79 

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 "" 

87 

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('_', ' ') 

92 

93 # Strip extra spaces and lowercase everything 

94 name = ' '.join(name.split()).lower() 

95 

96 for word, shown in (vocabulary or {}).items(): 

97 name = re.sub(rf'\b{re.escape(word)}\b', shown, name) 

98 

99 return name 

100 

101 

102# ========================================================================== 

103# 4. PER-FORMAT VIEWER CONFIGURATION 

104# ========================================================================== 

105 

106_REQUIRED_CONFIG_KEYS = ("type_map", "toc") 

107 

108 

109def load_viewer_config(profile: Profile) -> dict: 

110 """Read viewer.yaml from the folder of `profile` and fill in the optional keys. 

111 

112 

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