Skip to content

Commit

Permalink
Add the hook file's directory to sys.path (#3568)
Browse files Browse the repository at this point in the history
Also clean sys.path after the hook is done, for some semblance of isolation
  • Loading branch information
oprypin committed Mar 16, 2024
1 parent 53ff03a commit a793da2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 7 additions & 1 deletion docs/user-guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion mkdocs/config/config_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -1208,7 +1208,14 @@ def _load_hook(self, name, path):
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):
Expand Down

0 comments on commit a793da2

Please sign in to comment.