|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import re |
| 4 | +from fnmatch import fnmatch |
| 5 | +from importlib import import_module |
| 6 | +from typing import Set |
| 7 | + |
| 8 | +from django.template import engines |
| 9 | +from django.utils.encoding import smart_str |
| 10 | + |
| 11 | +from django_idom.config import IDOM_REGISTERED_COMPONENTS |
| 12 | + |
| 13 | + |
| 14 | +COMPONENT_REGEX = re.compile(r"{% *idom_component ((\"[^\"']*\")|('[^\"']*')).*?%}") |
| 15 | +_logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +def _register_component(full_component_name: str) -> None: |
| 19 | + if full_component_name in IDOM_REGISTERED_COMPONENTS: |
| 20 | + return |
| 21 | + |
| 22 | + module_name, component_name = full_component_name.rsplit(".", 1) |
| 23 | + |
| 24 | + try: |
| 25 | + module = import_module(module_name) |
| 26 | + except ImportError as error: |
| 27 | + raise RuntimeError( |
| 28 | + f"Failed to import {module_name!r} while loading {component_name!r}" |
| 29 | + ) from error |
| 30 | + |
| 31 | + try: |
| 32 | + component = getattr(module, component_name) |
| 33 | + except AttributeError as error: |
| 34 | + raise RuntimeError( |
| 35 | + f"Module {module_name!r} has no component named {component_name!r}" |
| 36 | + ) from error |
| 37 | + |
| 38 | + IDOM_REGISTERED_COMPONENTS[full_component_name] = component |
| 39 | + |
| 40 | + |
| 41 | +class ComponentPreloader: |
| 42 | + def register_all(self): |
| 43 | + """Registers all IDOM components found within Django templates.""" |
| 44 | + # Get all template folder paths |
| 45 | + paths = self._get_paths() |
| 46 | + # Get all HTML template files |
| 47 | + templates = self._get_templates(paths) |
| 48 | + # Get all components |
| 49 | + components = self._get_components(templates) |
| 50 | + # Register all components |
| 51 | + self._register_components(components) |
| 52 | + |
| 53 | + def _get_loaders(self): |
| 54 | + """Obtains currently configured template loaders.""" |
| 55 | + template_source_loaders = [] |
| 56 | + for e in engines.all(): |
| 57 | + if hasattr(e, "engine"): |
| 58 | + template_source_loaders.extend( |
| 59 | + e.engine.get_template_loaders(e.engine.loaders) |
| 60 | + ) |
| 61 | + loaders = [] |
| 62 | + for loader in template_source_loaders: |
| 63 | + if hasattr(loader, "loaders"): |
| 64 | + loaders.extend(loader.loaders) |
| 65 | + else: |
| 66 | + loaders.append(loader) |
| 67 | + return loaders |
| 68 | + |
| 69 | + def _get_paths(self) -> Set: |
| 70 | + """Obtains a set of all template directories.""" |
| 71 | + paths = set() |
| 72 | + for loader in self._get_loaders(): |
| 73 | + try: |
| 74 | + module = import_module(loader.__module__) |
| 75 | + get_template_sources = getattr(module, "get_template_sources", None) |
| 76 | + if get_template_sources is None: |
| 77 | + get_template_sources = loader.get_template_sources |
| 78 | + paths.update(smart_str(origin) for origin in get_template_sources("")) |
| 79 | + except (ImportError, AttributeError, TypeError): |
| 80 | + pass |
| 81 | + |
| 82 | + return paths |
| 83 | + |
| 84 | + def _get_templates(self, paths: Set) -> Set: |
| 85 | + """Obtains a set of all HTML template paths.""" |
| 86 | + extensions = [".html"] |
| 87 | + templates = set() |
| 88 | + for path in paths: |
| 89 | + for root, dirs, files in os.walk(path, followlinks=False): |
| 90 | + templates.update( |
| 91 | + os.path.join(root, name) |
| 92 | + for name in files |
| 93 | + if not name.startswith(".") |
| 94 | + and any(fnmatch(name, "*%s" % glob) for glob in extensions) |
| 95 | + ) |
| 96 | + |
| 97 | + return templates |
| 98 | + |
| 99 | + def _get_components(self, templates: Set) -> Set: |
| 100 | + """Obtains a set of all IDOM components by parsing HTML templates.""" |
| 101 | + components = set() |
| 102 | + for template in templates: |
| 103 | + try: |
| 104 | + with open(template, "r", encoding="utf-8") as template_file: |
| 105 | + match = COMPONENT_REGEX.findall(template_file.read()) |
| 106 | + if not match: |
| 107 | + continue |
| 108 | + components.update( |
| 109 | + [group[0].replace('"', "").replace("'", "") for group in match] |
| 110 | + ) |
| 111 | + except Exception: |
| 112 | + pass |
| 113 | + |
| 114 | + return components |
| 115 | + |
| 116 | + def _register_components(self, components: Set) -> None: |
| 117 | + """Registers all IDOM components in an iterable.""" |
| 118 | + for component in components: |
| 119 | + try: |
| 120 | + _register_component(component) |
| 121 | + _logger.info("IDOM has registered component %s", component) |
| 122 | + except Exception: |
| 123 | + _logger.warning("IDOM failed to register component %s", component) |
0 commit comments