7
0
mirror of https://github.com/ChristianLight/tutor.git synced 2024-06-27 00:53:30 +00:00
tutor/tutor/hooks/contexts.py
Régis Behmo 15b219e235 feat: migrate to plugins.v1 with filters & actions
This is a very large refactoring which aims at making Tutor both more
extendable and more generic. Historically, the Tutor plugin system was
designed as an ad-hoc solution to allow developers to modify their own
Open edX platforms without having to fork Tutor. The plugin API was
simple, but limited, because of its ad-hoc nature. As a consequence,
there were many things that plugin developers could not do, such as
extending different parts of the CLI or adding custom template filters.

Here, we refactor the whole codebase to make use of a generic plugin
system. This system was inspired by the Wordpress plugin API and the
Open edX "hooks and filters" API. The various components are added to a
small core thanks to a set of actions and filters. Actions are callback
functions that can be triggered at different points of the application
lifecycle. Filters are functions that modify some data. Both actions and
filters are collectively named as "hooks". Hooks can optionally be
created within a certain context, which makes it easier to keep track of
which application created which callback.

This new hooks system allows us to provide a Python API that developers
can use to extend their applications. The API reference is added to the
documentation, along with a new plugin development tutorial.

The plugin v0 API remains supported for backward compatibility of
existing plugins.

Done:
- Do not load commands from plugins which are not enabled.
- Load enabled plugins once on start.
- Implement contexts for actions and filters, which allow us to keep track of
  the source of every hook.
- Migrate patches
- Migrate commands
- Migrate plugin detection
- Migrate templates_root
- Migrate config
- Migrate template environment globals and filters
- Migrate hooks to tasks
- Generate hook documentation
- Generate patch reference documentation
- Add the concept of action priority

Close #499.
2022-04-15 15:30:54 +02:00

85 lines
2.6 KiB
Python

# The Tutor plugin system is licensed under the terms of the Apache 2.0 license.
__license__ = "Apache 2.0"
import typing as t
from contextlib import contextmanager
class Context:
CURRENT: t.List[str] = []
def __init__(self, name: str):
self.name = name
@contextmanager
def enter(self) -> t.Iterator[None]:
try:
Context.CURRENT.append(self.name)
yield
finally:
Context.CURRENT.pop()
class ContextTemplate:
"""
Context templates are for filters for which the name needs to be formatted
before the filter can be applied.
"""
def __init__(self, name: str):
self.template = name
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.template}')"
def __call__(self, *args: t.Any, **kwargs: t.Any) -> Context:
return Context(self.template.format(*args, **kwargs))
class Contextualized:
"""
This is a simple class to store the current context in hooks.
The current context is stored as a static variable.
"""
def __init__(self) -> None:
self.contexts = Context.CURRENT[:]
def is_in_context(self, context: t.Optional[str]) -> bool:
return context is None or context in self.contexts
def enter(name: str) -> t.ContextManager[None]:
"""
Identify created hooks with one or multiple context strings.
:param name: name of the context that will be attached to hooks.
:rtype t.ContextManager[None]:
Usage::
from tutor import hooks
with hooks.contexts.enter("my-context"):
# declare new actions and filters
...
# Later on, actions and filters can be disabled with:
hooks.actions.clear_all(context="my-context")
hooks.filters.clear_all(context="my-context")
This is a context manager that will attach a context name to all hook callbacks
created within its scope. The purpose of contexts is to solve an issue that
is inherent to pluggable hooks: it is difficult to track in which part of the
code each hook callback was created. This makes things hard to debug when a single
hook callback goes wrong. It also makes it impossible to disable some hook callbacks after
they have been created.
We resolve this issue by storing the current contexts in a static list.
Whenever a hook is created, the list of current contexts is copied as a
``contexts`` attribute. This attribute can be later examined, either for
removal or for limiting the set of hook callbacks that should be applied.
"""
return Context(name).enter()