|
| 1 | +"""Resolve and sandbox workspace builders selected by a workspace config. |
| 2 | +
|
| 3 | +A workspace may point tmuxp at a builder other than the classic |
| 4 | +:class:`tmuxp.workspace.builder.WorkspaceBuilder` via the ``workspace_builder`` |
| 5 | +key (a Python dotted path, ``module:attr`` reference, or an entry-point name in |
| 6 | +the ``tmuxp.workspace_builders`` group). When the builder lives outside the |
| 7 | +active environment, ``workspace_builder_paths`` lists trusted directories that |
| 8 | +are temporarily added to ``sys.path`` for the import and build. |
| 9 | +
|
| 10 | +Security note: only literal directories are prepended to ``sys.path``. This |
| 11 | +deliberately avoids :func:`site.addsitedir`, which executes ``.pth`` startup |
| 12 | +files and is broader than making a module importable. The trust boundary is the |
| 13 | +author of the workspace file. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import contextlib |
| 19 | +import importlib |
| 20 | +import inspect |
| 21 | +import os |
| 22 | +import pathlib |
| 23 | +import sys |
| 24 | +import typing as t |
| 25 | +from importlib import metadata |
| 26 | + |
| 27 | +from tmuxp import exc |
| 28 | +from tmuxp._internal.private_path import PrivatePath |
| 29 | +from tmuxp.workspace.builder.classic import ClassicWorkspaceBuilder |
| 30 | +from tmuxp.workspace.loader import expandshell |
| 31 | + |
| 32 | +if t.TYPE_CHECKING: |
| 33 | + from collections.abc import Iterator |
| 34 | + |
| 35 | + from tmuxp.workspace.builder.protocol import WorkspaceBuilderProtocol |
| 36 | + |
| 37 | +WORKSPACE_BUILDERS_GROUP = "tmuxp.workspace_builders" |
| 38 | +"""Entry-point group packaged builders register under.""" |
| 39 | + |
| 40 | + |
| 41 | +def resolve_builder_paths( |
| 42 | + session_config: dict[str, t.Any], |
| 43 | + workspace_file: str | os.PathLike[str] | None = None, |
| 44 | +) -> list[pathlib.Path]: |
| 45 | + """Resolve and validate trusted ``workspace_builder_paths`` import roots. |
| 46 | +
|
| 47 | + Each entry is shell-expanded (``~`` and ``$VARS``), resolved relative to the |
| 48 | + workspace file's directory when not absolute, and required to be an existing |
| 49 | + directory. Returns ``[]`` when the key is absent, so existing workspaces add |
| 50 | + nothing to ``sys.path``. |
| 51 | +
|
| 52 | + Parameters |
| 53 | + ---------- |
| 54 | + session_config : dict |
| 55 | + the expanded workspace configuration |
| 56 | + workspace_file : str or os.PathLike, optional |
| 57 | + path to the workspace file; its parent anchors relative entries |
| 58 | +
|
| 59 | + Returns |
| 60 | + ------- |
| 61 | + list of pathlib.Path |
| 62 | +
|
| 63 | + Examples |
| 64 | + -------- |
| 65 | + Absent key resolves to an empty list (no-op for existing workspaces): |
| 66 | +
|
| 67 | + >>> resolve_builder_paths({}, None) |
| 68 | + [] |
| 69 | +
|
| 70 | + An existing directory is resolved: |
| 71 | +
|
| 72 | + >>> root = tmp_path / "roots" |
| 73 | + >>> root.mkdir() |
| 74 | + >>> resolve_builder_paths({"workspace_builder_paths": [str(root)]}, None) == [ |
| 75 | + ... root.resolve() |
| 76 | + ... ] |
| 77 | + True |
| 78 | +
|
| 79 | + A missing directory is rejected: |
| 80 | +
|
| 81 | + >>> resolve_builder_paths( |
| 82 | + ... {"workspace_builder_paths": [str(tmp_path / "missing")]}, None |
| 83 | + ... ) |
| 84 | + Traceback (most recent call last): |
| 85 | + ... |
| 86 | + tmuxp.exc.WorkspaceBuilderPathError: ... |
| 87 | + """ |
| 88 | + raw = session_config.get("workspace_builder_paths") or [] |
| 89 | + if isinstance(raw, (str, os.PathLike)): |
| 90 | + raw = [raw] |
| 91 | + |
| 92 | + base = ( |
| 93 | + pathlib.Path(workspace_file).parent |
| 94 | + if workspace_file is not None |
| 95 | + else pathlib.Path.cwd() |
| 96 | + ) |
| 97 | + |
| 98 | + resolved: list[pathlib.Path] = [] |
| 99 | + for entry in raw: |
| 100 | + if not isinstance(entry, (str, os.PathLike)): |
| 101 | + raise exc.WorkspaceBuilderPathError( |
| 102 | + str(entry), |
| 103 | + reason="entries must be path strings", |
| 104 | + ) |
| 105 | + candidate = pathlib.Path(expandshell(str(entry))) |
| 106 | + if not candidate.is_absolute(): |
| 107 | + candidate = base / candidate |
| 108 | + candidate = candidate.resolve() |
| 109 | + if not candidate.is_dir(): |
| 110 | + raise exc.WorkspaceBuilderPathError(str(PrivatePath(candidate))) |
| 111 | + resolved.append(candidate) |
| 112 | + return resolved |
| 113 | + |
| 114 | + |
| 115 | +@contextlib.contextmanager |
| 116 | +def prepended_sys_path( |
| 117 | + paths: list[pathlib.Path] | None, |
| 118 | +) -> Iterator[None]: |
| 119 | + """Temporarily prepend directories to ``sys.path``, restoring it on exit. |
| 120 | +
|
| 121 | + Paths are prepended in order (first entry ends up at ``sys.path[0]``). An |
| 122 | + empty or falsy ``paths`` is a no-op. Uses only literal directory entries; it |
| 123 | + avoids :func:`site.addsitedir` (which runs ``.pth`` startup code). |
| 124 | +
|
| 125 | + Parameters |
| 126 | + ---------- |
| 127 | + paths : list of pathlib.Path or None |
| 128 | + directories to prepend |
| 129 | +
|
| 130 | + Examples |
| 131 | + -------- |
| 132 | + >>> import sys |
| 133 | + >>> ext = tmp_path / "ext" |
| 134 | + >>> ext.mkdir() |
| 135 | + >>> before = list(sys.path) |
| 136 | + >>> with prepended_sys_path([ext]): |
| 137 | + ... sys.path[0] == str(ext) |
| 138 | + True |
| 139 | + >>> sys.path == before |
| 140 | + True |
| 141 | + """ |
| 142 | + if not paths: |
| 143 | + yield |
| 144 | + return |
| 145 | + saved = list(sys.path) |
| 146 | + for path in reversed(paths): |
| 147 | + sys.path.insert(0, str(path)) |
| 148 | + try: |
| 149 | + yield |
| 150 | + finally: |
| 151 | + sys.path[:] = saved |
| 152 | + |
| 153 | + |
| 154 | +def available_builders() -> list[str]: |
| 155 | + """Return the names of builders registered via entry points. |
| 156 | +
|
| 157 | + Examples |
| 158 | + -------- |
| 159 | + >>> isinstance(available_builders(), list) |
| 160 | + True |
| 161 | + """ |
| 162 | + return [ep.name for ep in metadata.entry_points(group=WORKSPACE_BUILDERS_GROUP)] |
| 163 | + |
| 164 | + |
| 165 | +def _load_entry_point(name: str) -> t.Any | None: |
| 166 | + """Load a builder registered under entry-point ``name``, else ``None``. |
| 167 | +
|
| 168 | + Examples |
| 169 | + -------- |
| 170 | + >>> _load_entry_point("definitely-not-a-registered-builder") is None |
| 171 | + True |
| 172 | + """ |
| 173 | + for ep in metadata.entry_points(group=WORKSPACE_BUILDERS_GROUP): |
| 174 | + if ep.name == name: |
| 175 | + try: |
| 176 | + return ep.load() |
| 177 | + except (ImportError, AttributeError) as e: |
| 178 | + raise exc.WorkspaceBuilderImportError(name, reason=str(e)) from e |
| 179 | + return None |
| 180 | + |
| 181 | + |
| 182 | +def _import_target(target: str) -> t.Any: |
| 183 | + """Import an object from a ``module:attr`` or dotted ``module.attr`` path. |
| 184 | +
|
| 185 | + Examples |
| 186 | + -------- |
| 187 | + >>> _import_target( |
| 188 | + ... "tmuxp.workspace.builder.classic:ClassicWorkspaceBuilder" |
| 189 | + ... ).__name__ |
| 190 | + 'ClassicWorkspaceBuilder' |
| 191 | +
|
| 192 | + The historical ``tmuxp.workspace.builder:WorkspaceBuilder`` alias resolves |
| 193 | + to the same class: |
| 194 | +
|
| 195 | + >>> _import_target("tmuxp.workspace.builder:WorkspaceBuilder").__name__ |
| 196 | + 'ClassicWorkspaceBuilder' |
| 197 | + """ |
| 198 | + if ":" in target: |
| 199 | + module_name, _, attr = target.partition(":") |
| 200 | + else: |
| 201 | + module_name, _, attr = target.rpartition(".") |
| 202 | + if not module_name or not attr: |
| 203 | + raise exc.WorkspaceBuilderNotFound(target) |
| 204 | + try: |
| 205 | + module = importlib.import_module(module_name) |
| 206 | + except ImportError as e: |
| 207 | + raise exc.WorkspaceBuilderImportError(target, reason=str(e)) from e |
| 208 | + obj: t.Any = module |
| 209 | + try: |
| 210 | + for part in attr.split("."): |
| 211 | + obj = getattr(obj, part) |
| 212 | + except AttributeError as e: |
| 213 | + raise exc.WorkspaceBuilderImportError(target, reason=str(e)) from e |
| 214 | + return obj |
| 215 | + |
| 216 | + |
| 217 | +def _validate_builder(obj: t.Any, target: str) -> None: |
| 218 | + """Validate that ``obj`` is a usable workspace builder. |
| 219 | +
|
| 220 | + A class must expose a callable ``build`` method and a constructor accepting |
| 221 | + ``session_config`` and ``server`` (or ``**kwargs``). Non-class callables |
| 222 | + (factories) are trusted and validated at instantiation. |
| 223 | +
|
| 224 | + Examples |
| 225 | + -------- |
| 226 | + >>> from tmuxp.workspace.builder.classic import ClassicWorkspaceBuilder |
| 227 | + >>> _validate_builder(ClassicWorkspaceBuilder, "classic") |
| 228 | +
|
| 229 | + >>> _validate_builder(object, "object") |
| 230 | + Traceback (most recent call last): |
| 231 | + ... |
| 232 | + tmuxp.exc.InvalidWorkspaceBuilder: 'object' is not a valid workspace builder: ... |
| 233 | + """ |
| 234 | + if inspect.isclass(obj): |
| 235 | + if not callable(getattr(obj, "build", None)): |
| 236 | + raise exc.InvalidWorkspaceBuilder( |
| 237 | + target, |
| 238 | + reason="class has no callable 'build' method", |
| 239 | + ) |
| 240 | + try: |
| 241 | + params = inspect.signature(obj).parameters |
| 242 | + except (TypeError, ValueError): |
| 243 | + return |
| 244 | + has_var_kw = any( |
| 245 | + p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values() |
| 246 | + ) |
| 247 | + missing = {"session_config", "server"} - set(params) |
| 248 | + if not has_var_kw and missing: |
| 249 | + joined = ", ".join(sorted(missing)) |
| 250 | + raise exc.InvalidWorkspaceBuilder( |
| 251 | + target, |
| 252 | + reason=f"constructor missing parameter(s): {joined}", |
| 253 | + ) |
| 254 | + elif not callable(obj): |
| 255 | + raise exc.InvalidWorkspaceBuilder(target, reason="not a class or callable") |
| 256 | + |
| 257 | + |
| 258 | +def resolve_builder_class( |
| 259 | + session_config: dict[str, t.Any], |
| 260 | +) -> type[WorkspaceBuilderProtocol]: |
| 261 | + """Resolve the workspace builder class selected by ``session_config``. |
| 262 | +
|
| 263 | + Resolution of the ``workspace_builder`` value: |
| 264 | +
|
| 265 | + 1. absent/empty → the classic |
| 266 | + :class:`~tmuxp.workspace.builder.classic.ClassicWorkspaceBuilder` (no |
| 267 | + import, no entry-point scan); |
| 268 | + 2. contains ``:`` → a ``module:attr`` object reference; |
| 269 | + 3. no ``.`` and no ``:`` → an entry-point name in the |
| 270 | + ``tmuxp.workspace_builders`` group; |
| 271 | + 4. dotted, no ``:`` → an entry-point name if registered, otherwise a |
| 272 | + ``module.attr`` dotted path. |
| 273 | +
|
| 274 | + Parameters |
| 275 | + ---------- |
| 276 | + session_config : dict |
| 277 | + the expanded workspace configuration |
| 278 | +
|
| 279 | + Returns |
| 280 | + ------- |
| 281 | + type |
| 282 | + a workspace builder class (or builder factory) satisfying |
| 283 | + :class:`~tmuxp.workspace.builder.protocol.WorkspaceBuilderProtocol` |
| 284 | +
|
| 285 | + Examples |
| 286 | + -------- |
| 287 | + The default resolves to the classic builder without importing anything: |
| 288 | +
|
| 289 | + >>> from tmuxp.workspace.builder.classic import ClassicWorkspaceBuilder |
| 290 | + >>> resolve_builder_class({}) is ClassicWorkspaceBuilder |
| 291 | + True |
| 292 | +
|
| 293 | + A dotted ``module:attr`` reference is imported and validated: |
| 294 | +
|
| 295 | + >>> resolve_builder_class( |
| 296 | + ... { |
| 297 | + ... "workspace_builder": ( |
| 298 | + ... "tmuxp.workspace.builder.classic:ClassicWorkspaceBuilder" |
| 299 | + ... ) |
| 300 | + ... } |
| 301 | + ... ) is ClassicWorkspaceBuilder |
| 302 | + True |
| 303 | + """ |
| 304 | + target = session_config.get("workspace_builder") |
| 305 | + if not target: |
| 306 | + return ClassicWorkspaceBuilder |
| 307 | + target_str = str(target).strip() |
| 308 | + |
| 309 | + obj: t.Any |
| 310 | + if ":" in target_str: |
| 311 | + obj = _import_target(target_str) |
| 312 | + elif "." not in target_str: |
| 313 | + obj = _load_entry_point(target_str) |
| 314 | + if obj is None: |
| 315 | + raise exc.WorkspaceBuilderNotFound( |
| 316 | + target_str, |
| 317 | + available=available_builders(), |
| 318 | + ) |
| 319 | + else: |
| 320 | + obj = _load_entry_point(target_str) |
| 321 | + if obj is None: |
| 322 | + obj = _import_target(target_str) |
| 323 | + |
| 324 | + _validate_builder(obj, target_str) |
| 325 | + return t.cast("type[WorkspaceBuilderProtocol]", obj) |
0 commit comments