-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook_registry.py
More file actions
67 lines (52 loc) · 1.85 KB
/
Copy pathhook_registry.py
File metadata and controls
67 lines (52 loc) · 1.85 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
"""Registry for optional language hook modules consumed by detectors."""
from __future__ import annotations
import importlib
import logging
import sys
from collections import defaultdict
_LANG_HOOKS: dict[str, dict[str, object]] = defaultdict(dict)
_LOGGER = logging.getLogger(__name__)
def register_lang_hooks(
lang_name: str,
*,
test_coverage: object | None = None,
) -> None:
"""Register optional detector hook modules for a language."""
hooks = _LANG_HOOKS[lang_name]
if test_coverage is not None:
hooks["test_coverage"] = test_coverage
def get_lang_hook(lang_name: str | None, hook_name: str) -> object | None:
"""Get a previously-registered language hook module."""
if not lang_name:
return None
hook = _LANG_HOOKS.get(lang_name, {}).get(hook_name)
if hook is not None:
return hook
module_name = f"languages.{lang_name}"
module = sys.modules.get(module_name)
# Lazy-load only the requested language package.
if module is None:
try:
importlib.import_module(module_name)
except (ImportError, ValueError, TypeError, RuntimeError, OSError) as exc:
_LOGGER.warning(
"Unable to import language hook package %s: %s", lang_name, exc
)
return None
elif lang_name not in _LANG_HOOKS:
try:
importlib.reload(module)
except (ImportError, ValueError, TypeError, RuntimeError, OSError) as exc:
_LOGGER.warning(
"Unable to reload language hook package %s: %s", lang_name, exc
)
return None
return _LANG_HOOKS.get(lang_name, {}).get(hook_name)
def clear_lang_hooks_for_tests() -> None:
"""Clear registry (test helper)."""
_LANG_HOOKS.clear()
__all__ = [
"clear_lang_hooks_for_tests",
"get_lang_hook",
"register_lang_hooks",
]