Coverage for lode / profiles / __init__.py: 97%
94 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"""Profile registry: the single place where an artefact format is wired.
3A profile is a package (lode/profiles/<name>/) holding everything one format needs: its
4reader mapper (reader.yaml), its viewer config (viewer.yaml), optional templates, and the
5reader and viewer classes. Its __init__ registers a Profile. Classes are given as
6"module:Name" strings and resolved on use, so this module imports neither the reader nor
7the viewers and every layer can read it.
8"""
10import logging
11from dataclasses import dataclass
12from importlib import import_module
13from importlib.metadata import entry_points
14from pathlib import Path
15from typing import Any, Dict, List, Optional
17from lode.exceptions import ArtefactValidationError
19logger = logging.getLogger(__name__)
21# ==========================================================================
22# 1. PROFILE
23# ==========================================================================
25@dataclass(frozen=True)
26class Profile:
27 """Everything LODE needs to read and show one artefact format.
29 `package` is the profile's own package: reader.yaml, viewer.yaml and templates/ live
30 there. `reader`, `viewer` and `artefact` are "module:Name" paths to the reader class, the
31 viewer class and the Artefact subclass of the format; `post_checks` is an optional path
32 to a function that takes the reader after extraction. A module that starts with a dot is
33 relative to `package` (".reader:OwlReader"), so a profile never repeats its own package
34 name. `enabled` gates the format where it is named by a string (lode.read, hence the
35 API and the CLI).
36 """
38 name: str
39 package: str
40 reader: str
41 viewer: str
42 artefact: str
43 post_checks: Optional[str] = None
44 enabled: bool = True
46 def path(self) -> Path:
47 """Return the folder of the profile's package.
49 Taken from the module file, like the other data folders, so it also works when
50 the package is installed from the wheel.
51 """
52 return Path(import_module(self.package).__file__).parent
54 def artefact_class(self) -> type:
55 """Return the Artefact subclass of this format, imported on use."""
56 return resolve(self.artefact, self.package)
58 def make_reader(self, graph: Any, cache: dict, configuration: Any) -> Any:
59 """Build the reader of this format on `graph`, filling `cache`.
61 The class is imported now and not at registration, so this module stays free of
62 reader imports; the reader asks the profile and never resolves the path itself.
63 """
64 return resolve(self.reader, self.package)(graph, cache, configuration)
66 def make_viewer(self, artefact: Any) -> Any:
67 """Build the viewer of this format for `artefact` (imported on use, like the reader)."""
68 return resolve(self.viewer, self.package)(artefact)
70 def run_post_checks(self, reader: Any) -> None:
71 """Run the post-extraction checks of this format on `reader`; no-op without any."""
72 if self.post_checks:
73 resolve(self.post_checks, self.package)(reader)
76# ==========================================================================
77# 2. REGISTRY
78# ==========================================================================
80_PROFILES: Dict[str, Profile] = {}
82# Imported on first use, by name: the engine must not import a profile package, and the
83# import registers it. Third-party profiles join them through the entry point group below.
84_BUILTIN = ("lode.profiles.owl", "lode.profiles.skos")
85_ENTRY_POINT_GROUP = "lode.profiles"
86_loaded = False
88def _ensure_loaded() -> None:
89 """Register the built-in profiles and the plugins, once.
91 Built-ins first, so a plugin can never take the name of a format LODE ships.
92 """
93 global _loaded
94 if _loaded:
95 return
96 _loaded = True # set first: a profile's __init__ imports this module again
97 for module in _BUILTIN:
98 import_module(module)
99 for entry_point in entry_points(group=_ENTRY_POINT_GROUP):
100 _register_plugin(entry_point)
103def _register_plugin(entry_point) -> None:
104 """Load the Profile an entry point names and register it.
106 A broken plugin must not take LODE down, so a failure is logged with the plugin's
107 name (the traceback stays in the server log) and the plugin is skipped. A plugin
108 that reuses the name of a registered profile is refused for the same reason.
109 """
110 try:
111 profile = entry_point.load()
112 except Exception:
113 logger.warning("Profile plugin '%s' failed to load", entry_point.name, exc_info=True)
114 return
115 if not isinstance(profile, Profile):
116 logger.warning("Profile plugin '%s' is not a Profile, skipped", entry_point.name)
117 elif profile.name in _PROFILES:
118 logger.warning("Profile plugin '%s' redefines '%s', skipped", entry_point.name, profile.name)
119 else:
120 register(profile)
122def register(profile: Profile) -> None:
123 """Add a profile to the registry, replacing any profile with the same name."""
124 _PROFILES[profile.name] = profile
127def _find(name: Optional[str]) -> Optional[Profile]:
128 """Return the profile called `name`, ignoring case, or None when there is none.
130 The only place where a format name is normalised: the reader, the viewer and the
131 artefact all ask here, so 'OWL' and 'owl' can never be treated differently.
132 """
133 _ensure_loaded()
134 return _PROFILES.get((name or "").lower())
137def get(name: str) -> Profile:
138 """Return the profile called `name`; raise ValueError listing the available ones."""
139 profile = _find(name)
140 if profile is None:
141 raise ValueError(f"Unknown configuration: '{name}'. Available: {', '.join(names())}")
142 return profile
145def get_enabled(name: Optional[str]) -> Profile:
146 """Return the enabled profile called `name`, ignoring case.
148 The gate of every caller that names a format with a string (lode.read, hence the API
149 and the CLI). An unknown name and a disabled one get the same error, with the list of
150 valid formats. Asked every time, not cached, because plugins register on first use.
151 """
152 profile = _find(name)
153 if profile is None or not profile.enabled:
154 raise ArtefactValidationError(
155 f"Format '{name}' is not available",
156 context={"requested": name, "supported": names(enabled_only=True)},
157 )
158 return profile
161def _artefact_classes() -> List[tuple]:
162 """Return (profile, Artefact class) for every profile whose class can be imported.
164 A plugin whose class cannot be imported is logged and skipped: it must not stop the
165 others from reading.
166 """
167 found = []
168 for profile in _PROFILES.values():
169 try:
170 found.append((profile, profile.artefact_class()))
171 except (ImportError, AttributeError):
172 logger.warning("Profile '%s': artefact class '%s' cannot be imported",
173 profile.name, profile.artefact, exc_info=True)
174 return found
177def of(cls: type) -> Optional[Profile]:
178 """Return the profile whose Artefact subclass is `cls` or one of its bases, or None.
180 Walks the MRO, so a user's subclass of OwlOntology is still read as OWL. Built-ins are
181 registered first, so they win when a plugin points to the same class.
182 """
183 _ensure_loaded()
184 classes = _artefact_classes()
185 for klass in cls.__mro__:
186 for profile, artefact in classes:
187 if artefact is klass:
188 return profile
189 return None
192def artefact_class_named(name: str) -> Optional[type]:
193 """Return the Artefact subclass called `name` among the registered profiles, or None.
195 Backs `from lode import OwlOntology`: the package root imports no profile, it asks here
196 on first use, and the classes of plugins are found too. Disabled profiles are included:
197 `enabled` gates the formats named by a string, not the classes a program imports.
198 """
199 _ensure_loaded()
200 for _, artefact in _artefact_classes():
201 if artefact.__name__ == name:
202 return artefact
203 return None
206def names(enabled_only: bool = False) -> List[str]:
207 """Return the sorted profile names, optionally only the enabled ones."""
208 _ensure_loaded()
209 return sorted(p.name for p in _PROFILES.values() if p.enabled or not enabled_only)
212def resolve(path: str, package: Optional[str] = None) -> Any:
213 """Import and return the object a "module:Name" path points to.
215 A module that starts with a dot is relative to `package`; without a package a relative
216 path raises TypeError, so a typo fails loudly. Done at call time, not at registration,
217 to keep this module free of reader and viewer imports (and of circular imports).
218 """
219 module, _, attr = path.partition(":")
220 return getattr(import_module(module, package), attr)