Add the hook file's directory to sys.path (#3568)

Also clean sys.path after the hook is done, for some semblance of isolation
This commit is contained in:
Oleh Prypin
2024-03-16 16:05:17 +01:00
committed by GitHub
parent 53ff03aad2
commit a793da267b
2 changed files with 15 additions and 2 deletions

View File

@@ -804,7 +804,7 @@ hooks:
- my_hooks.py
```
Then the file *my_hooks.py* can contain any [plugin event handlers](../dev-guide/plugins.md#events) (without `self`), e.g.:
Then the file `my_hooks.py` can contain any [plugin event handlers](../dev-guide/plugins.md#events) (without `self`), e.g.:
```python
def on_page_markdown(markdown, **kwargs):
@@ -843,6 +843,12 @@ You might have seen this feature in the [mkdocs-simple-hooks plugin](https://git
+ - my_hooks.py
```
> NEW: **New in MkDocs 1.6.**
>
> If a hook file has a file `foo.py` adjacent to it, it can use the normal Python syntax `import foo` to access its functions.
>
> In older versions of MkDocs, a workaround was necessary to make this work - adding the path to `sys.path`.
### plugins
A list of plugins (with optional configuration settings) to use when building

View File

@@ -1208,7 +1208,14 @@ class Hooks(BaseConfigOption[List[types.ModuleType]]):
sys.modules[name] = module
if spec.loader is None:
raise ValidationError(f"Cannot import path '{path}' as a Python module")
spec.loader.exec_module(module)
old_sys_path = sys.path.copy()
sys.path.insert(0, os.path.dirname(path))
try:
spec.loader.exec_module(module)
finally:
sys.path[:] = old_sys_path
return module
def post_validation(self, config: Config, key_name: str):