-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregistry.py
More file actions
93 lines (68 loc) · 2.37 KB
/
registry.py
File metadata and controls
93 lines (68 loc) · 2.37 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
from __future__ import annotations
import importlib.abc
import importlib.machinery
import sys
from collections.abc import Callable, Sequence
from types import ModuleType
from typing_extensions import override
PatchFn = Callable[[ModuleType], None]
_registry: dict[str, PatchFn] = {}
_installed = False
def register_patch(module_name: str, patch_fn: PatchFn) -> None:
_registry[module_name] = patch_fn
# If the module is already imported, patch it immediately
module = sys.modules.get(module_name)
if module:
_apply_patch(module, patch_fn)
def install_hooks() -> None:
_install_meta_path_finder()
_patch_preimported_modules()
class _DriftLoader(importlib.abc.Loader):
_loader: importlib.abc.Loader
_patch_fn: PatchFn
def __init__(self, loader: importlib.abc.Loader, patch_fn: PatchFn) -> None:
self._loader = loader
self._patch_fn = patch_fn
@override
def create_module(self, spec: importlib.machinery.ModuleSpec):
# TODO: is this always callable?
create = self._loader.create_module
if callable(create):
return create(spec)
return None
@override
def exec_module(self, module: ModuleType) -> None:
self._loader.exec_module(module)
_apply_patch(module, self._patch_fn)
class _DriftFinder(importlib.abc.MetaPathFinder):
@override
def find_spec(
self,
fullname: str,
path: Sequence[str] | None,
target: ModuleType | None = None,
):
patch_fn = _registry.get(fullname)
if not patch_fn:
return None
spec = importlib.machinery.PathFinder.find_spec(fullname, path)
if not spec or not spec.loader:
return None
spec.loader = _DriftLoader(spec.loader, patch_fn)
return spec
def _install_meta_path_finder() -> None:
global _installed
if _installed:
return
sys.meta_path.insert(0, _DriftFinder())
_installed = True
def _patch_preimported_modules() -> None:
for name, module in list(sys.modules.items()):
patch_fn = _registry.get(name)
if patch_fn and module:
_apply_patch(module, patch_fn)
def _apply_patch(module: ModuleType, patch_fn: PatchFn) -> None:
if getattr(module, "__drift_patched__", False):
return
patch_fn(module)
module.__drift_patched__ = True # type: ignore[attr-defined]