Repository navigation
Expand file tree
/
Copy path_loader.py
More file actions
176 lines (136 loc) · 5.7 KB
/
Copy path_loader.py
File metadata and controls
176 lines (136 loc) · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""Import `.hyper` files as Python modules and package attributes."""
from __future__ import annotations
import importlib.abc
import importlib.machinery
import linecache
import sys
import threading
from pathlib import Path
from types import ModuleType
from typing import Iterable
class HyperFinder(importlib.abc.MetaPathFinder):
"""Find packages and modules backed by `.hyper` files."""
def find_spec(self, fullname: str, path=None, target=None):
name = fullname.rpartition(".")[2]
for base in _search_paths(path):
# Normal Python modules keep their standard import precedence.
if (base / f"{name}.py").is_file():
return None
module_path = base / f"{name}.hyper"
if module_path.is_file():
code, component_name = _compile_file(module_path)
if component_name is not None:
return None
return importlib.machinery.ModuleSpec(
fullname,
HyperModuleLoader(module_path, code),
origin=str(module_path),
)
package_path = base / name
if package_path.is_dir() and _contains_hyper_file(package_path):
loader = HyperPackageLoader(package_path)
spec = importlib.machinery.ModuleSpec(
fullname,
loader,
origin=str(package_path / "__init__.py"),
is_package=True,
)
spec.submodule_search_locations = [str(package_path)]
return spec
return None
class HyperPackageLoader(importlib.abc.Loader):
"""Load a directory package and expose `{Name}.hyper` as `Name`."""
def __init__(self, path: Path):
self.path = path
self._lock = threading.RLock()
def create_module(self, spec):
return None
def exec_module(self, module: ModuleType) -> None:
module.__file__ = str(self.path / "__init__.py")
module.__path__ = [str(self.path)]
init_path = self.path / "__init__.py"
if init_path.is_file():
source = init_path.read_text()
exec(compile(source, str(init_path), "exec"), module.__dict__)
user_getattr = module.__dict__.get("__getattr__")
def __getattr__(name: str):
if user_getattr is not None:
try:
return user_getattr(name)
except AttributeError:
pass
if name.startswith("__"):
raise AttributeError(name)
python_path = self.path / f"{name}.py"
if python_path.is_file():
return importlib.import_module(f"{module.__name__}.{name}")
hyper_path = self.path / f"{name}.hyper"
if not hyper_path.is_file():
raise AttributeError(name)
with self._lock:
if name in module.__dict__:
return module.__dict__[name]
code, component_name = _compile_file(hyper_path)
if component_name is None:
return importlib.import_module(f"{module.__name__}.{name}")
namespace = {
"__name__": f"{module.__name__}.{name}",
"__package__": module.__name__,
"__file__": str(hyper_path),
"__loader__": HyperModuleLoader(hyper_path),
}
execute_compiled(code, hyper_path, namespace)
try:
component = namespace[component_name]
except KeyError as exc:
raise ImportError(
f"{hyper_path} did not define its component {component_name!r}"
) from exc
module.__dict__[name] = component
return component
module.__getattr__ = __getattr__
class HyperModuleLoader(importlib.abc.Loader):
"""Load one `.hyper` file as a normal Python module."""
def __init__(self, path: Path, code: str | None = None):
self.path = path
self.code = code
def create_module(self, spec):
return None
def exec_module(self, module: ModuleType) -> None:
module.__file__ = str(self.path)
module.__package__ = module.__name__.rpartition(".")[0]
code = self.code if self.code is not None else _compile_file(self.path)[0]
execute_compiled(code, self.path, module.__dict__)
def execute_compiled(code: str, path: Path, namespace: dict) -> None:
filename = f"<hyper:{path}>"
lines = code.splitlines(keepends=True)
linecache.cache[filename] = len(code), None, lines, filename
exec(compile(code, filename, "exec"), namespace)
def _search_paths(path) -> Iterable[Path]:
entries = sys.path if path is None else path
for entry in entries:
if not entry:
entry = "."
try:
yield Path(entry)
except TypeError:
continue
def _contains_hyper_file(path: Path) -> bool:
try:
next(path.rglob("*.hyper"))
return True
except (StopIteration, OSError):
return False
def _compile_file(path: Path) -> tuple[str, str | None]:
try:
from hyperhtml import _native
except Exception as exc: # pragma: no cover - depends on wheel build health
raise ImportError(
"Hyper's native compiler extension is not available. "
"Reinstall the hyperhtml package for your platform."
) from exc
try:
source = path.read_text()
return _native.transpile_file(source, str(path))
except Exception as exc:
raise ImportError(f"Failed to compile {path}: {exc}") from exc