|
| 1 | +"""After this file is imported, all mkdocs.* imports get redirected to properdocs.* imports.""" |
| 2 | + |
| 3 | +import importlib.abc |
| 4 | +import importlib.util |
| 5 | +import sys |
| 6 | + |
| 7 | + |
| 8 | +class _AliasLoader(importlib.abc.Loader): |
| 9 | + """Loads the module with the given name and replaces the passed spec's module.""" |
| 10 | + |
| 11 | + def __init__(self, realname): |
| 12 | + self.realname = realname |
| 13 | + |
| 14 | + def create_module(self, spec): |
| 15 | + module = importlib.import_module(self.realname) |
| 16 | + sys.modules[spec.name] = module |
| 17 | + return module |
| 18 | + |
| 19 | + def exec_module(self, module): |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +class _AliasFinder: |
| 24 | + """When searching for any mkdocs.* module, find the corresponding properdocs.* module instead.""" |
| 25 | + |
| 26 | + def find_spec(self, fullname, path, target=None): |
| 27 | + if fullname.startswith("mkdocs."): |
| 28 | + realname = "properdocs." + fullname.removeprefix("mkdocs.") |
| 29 | + spec = importlib.util.find_spec(realname) |
| 30 | + if spec is None: |
| 31 | + raise ImportError(f"No module named {realname!r}") |
| 32 | + return importlib.util.spec_from_loader( |
| 33 | + fullname, |
| 34 | + _AliasLoader(realname), |
| 35 | + is_package=spec.submodule_search_locations is not None, |
| 36 | + ) |
| 37 | + return None |
| 38 | + |
| 39 | + |
| 40 | +sys.meta_path.insert(0, _AliasFinder()) |
| 41 | +# Plus, handle the topmost module directly and without waiting for it to be requested. |
| 42 | +sys.modules['mkdocs'] = sys.modules['properdocs'] |
0 commit comments