2020-01-14 12:32:45 +00:00
|
|
|
import importlib
|
2020-01-14 14:42:20 +00:00
|
|
|
import os
|
2021-04-06 10:09:00 +00:00
|
|
|
from copy import deepcopy
|
|
|
|
from glob import glob
|
2021-03-29 07:48:53 +00:00
|
|
|
from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union
|
2019-05-29 09:14:06 +00:00
|
|
|
|
2020-01-14 14:42:20 +00:00
|
|
|
import appdirs
|
2021-03-29 07:48:53 +00:00
|
|
|
import click
|
2021-02-25 08:09:14 +00:00
|
|
|
import pkg_resources
|
2020-01-14 14:42:20 +00:00
|
|
|
|
2021-09-16 14:48:16 +00:00
|
|
|
from .__about__ import __app__
|
2021-04-06 10:09:00 +00:00
|
|
|
from . import exceptions, fmt, serialize
|
|
|
|
from .types import Config, get_typed
|
2019-05-29 09:14:06 +00:00
|
|
|
|
|
|
|
CONFIG_KEY = "PLUGINS"
|
|
|
|
|
|
|
|
|
2020-01-14 12:32:45 +00:00
|
|
|
class BasePlugin:
|
2019-05-29 09:14:06 +00:00
|
|
|
"""
|
2020-01-14 12:32:45 +00:00
|
|
|
Tutor plugins are defined by a name and an object that implements one or more of the
|
2019-06-06 19:58:21 +00:00
|
|
|
following properties:
|
|
|
|
|
2021-09-30 02:27:40 +00:00
|
|
|
`config` (dict str->dict(str->str)): contains "add", "defaults", "set" keys. Entries
|
2020-01-14 12:32:45 +00:00
|
|
|
in these dicts will be added or override the global configuration. Keys in "add" and
|
2021-09-30 02:27:40 +00:00
|
|
|
"defaults" will be prefixed by the plugin name in uppercase.
|
2020-01-14 12:32:45 +00:00
|
|
|
|
2019-06-06 19:58:21 +00:00
|
|
|
`patches` (dict str->str): entries in this dict will be used to patch the rendered
|
|
|
|
Tutor templates. For instance, to add "somecontent" to a template that includes '{{
|
|
|
|
patch("mypatch") }}', set: `patches["mypatch"] = "somecontent"`. It is recommended
|
|
|
|
to store all patches in separate files, and to dynamically list patches by listing
|
|
|
|
the contents of a "patches" subdirectory.
|
|
|
|
|
|
|
|
`templates` (str): path to a directory that includes new template files for the
|
|
|
|
plugin. It is recommended that all files in the template directory are stored in a
|
|
|
|
`myplugin` folder to avoid conflicts with other plugins. Plugin templates are useful
|
|
|
|
for content re-use, e.g: "{% include 'myplugin/mytemplate.html'}".
|
|
|
|
|
|
|
|
`hooks` (dict str->list[str]): hooks are commands that will be run at various points
|
|
|
|
during the lifetime of the platform. For instance, to run `service1` and `service2`
|
|
|
|
in sequence during initialization, you should define:
|
|
|
|
|
|
|
|
hooks["init"] = ["service1", "service2"]
|
|
|
|
|
|
|
|
It is then assumed that there are `myplugin/hooks/service1/init` and
|
|
|
|
`myplugin/hooks/service2/init` templates in the plugin `templates` directory.
|
2020-01-14 12:32:45 +00:00
|
|
|
|
|
|
|
`command` (click.Command): if a plugin exposes a `command` attribute, users will be able to run it from the command line as `tutor pluginname`.
|
|
|
|
"""
|
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
INSTALLED: List["BasePlugin"] = []
|
2020-10-15 14:28:55 +00:00
|
|
|
_IS_LOADED = False
|
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def __init__(self, name: str, obj: Any) -> None:
|
2020-01-14 12:32:45 +00:00
|
|
|
self.name = name
|
2021-03-29 07:48:53 +00:00
|
|
|
self.config = self.load_config(obj, self.name)
|
|
|
|
self.patches = self.load_patches(obj, self.name)
|
|
|
|
self.hooks = self.load_hooks(obj, self.name)
|
|
|
|
|
|
|
|
templates_root = get_callable_attr(obj, "templates", default=None)
|
|
|
|
if templates_root is not None:
|
|
|
|
assert isinstance(templates_root, str)
|
|
|
|
self.templates_root = templates_root
|
|
|
|
|
|
|
|
command = getattr(obj, "command", None)
|
|
|
|
if command is not None:
|
|
|
|
assert isinstance(command, click.Command)
|
|
|
|
self.command: click.Command = command
|
|
|
|
|
|
|
|
@staticmethod
|
2021-04-06 10:09:00 +00:00
|
|
|
def load_config(obj: Any, plugin_name: str) -> Dict[str, Config]:
|
2021-03-29 07:48:53 +00:00
|
|
|
"""
|
|
|
|
Load config and check types.
|
|
|
|
"""
|
|
|
|
config = get_callable_attr(obj, "config", {})
|
|
|
|
if not isinstance(config, dict):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid config in plugin {}. Expected dict, got {}.".format(
|
|
|
|
plugin_name, config.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
for name, subconfig in config.items():
|
|
|
|
if not isinstance(name, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid config entry '{}' in plugin {}. Expected str, got {}.".format(
|
|
|
|
name, plugin_name, config.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
if not isinstance(subconfig, dict):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid config entry '{}' in plugin {}. Expected str keys, got {}.".format(
|
|
|
|
name, plugin_name, config.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
for key in subconfig.keys():
|
|
|
|
if not isinstance(key, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid config entry '{}.{}' in plugin {}. Expected str, got {}.".format(
|
|
|
|
name, key, plugin_name, key.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return config
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def load_patches(obj: Any, plugin_name: str) -> Dict[str, str]:
|
|
|
|
"""
|
|
|
|
Load patches and check the types are right.
|
|
|
|
"""
|
|
|
|
patches = get_callable_attr(obj, "patches", {})
|
|
|
|
if not isinstance(patches, dict):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid patches in plugin {}. Expected dict, got {}.".format(
|
|
|
|
plugin_name, patches.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
for patch_name, content in patches.items():
|
|
|
|
if not isinstance(patch_name, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid patch name '{}' in plugin {}. Expected str, got {}.".format(
|
|
|
|
patch_name, plugin_name, patch_name.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
if not isinstance(content, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid patch '{}' in plugin {}. Expected str, got {}.".format(
|
|
|
|
patch_name, plugin_name, content.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return patches
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def load_hooks(
|
|
|
|
obj: Any, plugin_name: str
|
|
|
|
) -> Dict[str, Union[Dict[str, str], List[str]]]:
|
|
|
|
"""
|
|
|
|
Load hooks and check types.
|
|
|
|
"""
|
|
|
|
hooks = get_callable_attr(obj, "hooks", default={})
|
|
|
|
if not isinstance(hooks, dict):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid hooks in plugin {}. Expected dict, got {}.".format(
|
|
|
|
plugin_name, hooks.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
for hook_name, hook in hooks.items():
|
|
|
|
if not isinstance(hook_name, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid hook name '{}' in plugin {}. Expected str, got {}.".format(
|
|
|
|
hook_name, plugin_name, hook_name.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
if isinstance(hook, list):
|
|
|
|
for service in hook:
|
|
|
|
if not isinstance(service, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid service in hook '{}' from plugin {}. Expected str, got {}.".format(
|
|
|
|
hook_name, plugin_name, service.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
elif isinstance(hook, dict):
|
|
|
|
for name, value in hook.items():
|
|
|
|
if not isinstance(name, str) or not isinstance(value, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid hook '{}' in plugin {}. Only str -> str entries are supported.".format(
|
|
|
|
hook_name, plugin_name
|
|
|
|
)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid hook '{}' in plugin {}. Expected dict or list, got {}.".format(
|
|
|
|
hook_name, plugin_name, hook.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return hooks
|
2020-01-14 12:32:45 +00:00
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def config_key(self, key: str) -> str:
|
2020-01-14 12:32:45 +00:00
|
|
|
"""
|
|
|
|
Config keys in the "add" and "defaults" dicts should be prefixed by the plugin name, in uppercase.
|
|
|
|
"""
|
|
|
|
return self.name.upper() + "_" + key
|
|
|
|
|
|
|
|
@property
|
2021-04-06 10:09:00 +00:00
|
|
|
def config_add(self) -> Config:
|
2020-01-14 12:32:45 +00:00
|
|
|
return self.config.get("add", {})
|
|
|
|
|
|
|
|
@property
|
2021-04-06 10:09:00 +00:00
|
|
|
def config_set(self) -> Config:
|
2020-01-14 12:32:45 +00:00
|
|
|
return self.config.get("set", {})
|
|
|
|
|
|
|
|
@property
|
2021-04-06 10:09:00 +00:00
|
|
|
def config_defaults(self) -> Config:
|
2020-01-14 12:32:45 +00:00
|
|
|
return self.config.get("defaults", {})
|
|
|
|
|
|
|
|
@property
|
2021-02-25 08:09:14 +00:00
|
|
|
def version(self) -> str:
|
2020-01-14 12:32:45 +00:00
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_installed(cls) -> Iterator["BasePlugin"]:
|
2020-10-15 14:28:55 +00:00
|
|
|
if not cls._IS_LOADED:
|
|
|
|
for plugin in cls.iter_load():
|
|
|
|
cls.INSTALLED.append(plugin)
|
|
|
|
cls._IS_LOADED = True
|
|
|
|
yield from cls.INSTALLED
|
|
|
|
|
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_load(cls) -> Iterator["BasePlugin"]:
|
2020-01-14 12:32:45 +00:00
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
class EntrypointPlugin(BasePlugin):
|
|
|
|
"""
|
|
|
|
Entrypoint plugins are regular python packages that have a 'tutor.plugin.v0' entrypoint.
|
|
|
|
|
|
|
|
The API for Tutor plugins is currently in development. The entrypoint will switch to
|
|
|
|
'tutor.plugin.v1' once it is stabilised.
|
2019-05-29 09:14:06 +00:00
|
|
|
"""
|
|
|
|
|
2019-06-06 19:58:21 +00:00
|
|
|
ENTRYPOINT = "tutor.plugin.v0"
|
2020-01-14 12:32:45 +00:00
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def __init__(self, entrypoint: pkg_resources.EntryPoint) -> None:
|
2020-01-14 12:32:45 +00:00
|
|
|
super().__init__(entrypoint.name, entrypoint.load())
|
|
|
|
self.entrypoint = entrypoint
|
|
|
|
|
|
|
|
@property
|
2021-02-25 08:09:14 +00:00
|
|
|
def version(self) -> str:
|
|
|
|
if not self.entrypoint.dist:
|
|
|
|
return "0.0.0"
|
2020-01-14 12:32:45 +00:00
|
|
|
return self.entrypoint.dist.version
|
|
|
|
|
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_load(cls) -> Iterator["EntrypointPlugin"]:
|
2020-01-14 12:32:45 +00:00
|
|
|
for entrypoint in pkg_resources.iter_entry_points(cls.ENTRYPOINT):
|
feat: better logging during plugin loading failure
When upgrading Tutor plugins to the next release, I often end up with a
virtualenv that contains plugins that depend on different versions of
tutor-openedx. This causes a crash that did not log the name of the responsible
package. For instance:
Traceback (most recent call last):
File "/home/regis/venvs/tutor/bin/tutor", line 11, in <module>
load_entry_point('tutor-openedx', 'console_scripts', 'tutor')()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/cli.py", line 37, in main
add_plugin_commands(cli)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/plugins.py", line 137, in add_plugin_commands
for plugin in plugins.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 401, in iter_installed
yield from Plugins.iter_installed()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 362, in iter_installed
for plugin in PluginClass.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 199, in iter_installed
for plugin in cls.iter_load():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 233, in iter_load
yield cls(entrypoint)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 220, in __init__
super().__init__(entrypoint.name, entrypoint.load())
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2442, in load
self.require(*args, **kwargs)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2465, in require
items = working_set.resolve(reqs, env, installer, extras=self.extras)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 791, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.VersionConflict: (tutor-openedx 11.2.11 (/home/regis/projets/overhang/repos/overhang/tutor), Requirement.parse('tutor-openedx<13.0.0,>=12.0.0'))
In this commit, we introduce an error log that displays the name and location
of the package. E.g:
Failed to load entrypoint 'minio = tutorminio.plugin' from distribution tutor-minio 12.0.0
2021-05-20 07:58:54 +00:00
|
|
|
try:
|
2021-11-01 19:35:58 +00:00
|
|
|
error: Optional[str] = None
|
feat: better logging during plugin loading failure
When upgrading Tutor plugins to the next release, I often end up with a
virtualenv that contains plugins that depend on different versions of
tutor-openedx. This causes a crash that did not log the name of the responsible
package. For instance:
Traceback (most recent call last):
File "/home/regis/venvs/tutor/bin/tutor", line 11, in <module>
load_entry_point('tutor-openedx', 'console_scripts', 'tutor')()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/cli.py", line 37, in main
add_plugin_commands(cli)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/plugins.py", line 137, in add_plugin_commands
for plugin in plugins.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 401, in iter_installed
yield from Plugins.iter_installed()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 362, in iter_installed
for plugin in PluginClass.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 199, in iter_installed
for plugin in cls.iter_load():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 233, in iter_load
yield cls(entrypoint)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 220, in __init__
super().__init__(entrypoint.name, entrypoint.load())
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2442, in load
self.require(*args, **kwargs)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2465, in require
items = working_set.resolve(reqs, env, installer, extras=self.extras)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 791, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.VersionConflict: (tutor-openedx 11.2.11 (/home/regis/projets/overhang/repos/overhang/tutor), Requirement.parse('tutor-openedx<13.0.0,>=12.0.0'))
In this commit, we introduce an error log that displays the name and location
of the package. E.g:
Failed to load entrypoint 'minio = tutorminio.plugin' from distribution tutor-minio 12.0.0
2021-05-20 07:58:54 +00:00
|
|
|
yield cls(entrypoint)
|
2021-11-01 19:35:58 +00:00
|
|
|
except pkg_resources.VersionConflict as e:
|
|
|
|
error = e.report()
|
|
|
|
except Exception as e:
|
|
|
|
error = str(e)
|
|
|
|
if error:
|
feat: better logging during plugin loading failure
When upgrading Tutor plugins to the next release, I often end up with a
virtualenv that contains plugins that depend on different versions of
tutor-openedx. This causes a crash that did not log the name of the responsible
package. For instance:
Traceback (most recent call last):
File "/home/regis/venvs/tutor/bin/tutor", line 11, in <module>
load_entry_point('tutor-openedx', 'console_scripts', 'tutor')()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/cli.py", line 37, in main
add_plugin_commands(cli)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/plugins.py", line 137, in add_plugin_commands
for plugin in plugins.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 401, in iter_installed
yield from Plugins.iter_installed()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 362, in iter_installed
for plugin in PluginClass.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 199, in iter_installed
for plugin in cls.iter_load():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 233, in iter_load
yield cls(entrypoint)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 220, in __init__
super().__init__(entrypoint.name, entrypoint.load())
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2442, in load
self.require(*args, **kwargs)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2465, in require
items = working_set.resolve(reqs, env, installer, extras=self.extras)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 791, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.VersionConflict: (tutor-openedx 11.2.11 (/home/regis/projets/overhang/repos/overhang/tutor), Requirement.parse('tutor-openedx<13.0.0,>=12.0.0'))
In this commit, we introduce an error log that displays the name and location
of the package. E.g:
Failed to load entrypoint 'minio = tutorminio.plugin' from distribution tutor-minio 12.0.0
2021-05-20 07:58:54 +00:00
|
|
|
fmt.echo_error(
|
2021-11-01 19:35:58 +00:00
|
|
|
"Failed to load entrypoint '{} = {}' from distribution {}: {}".format(
|
|
|
|
entrypoint.name, entrypoint.module_name, entrypoint.dist, error
|
feat: better logging during plugin loading failure
When upgrading Tutor plugins to the next release, I often end up with a
virtualenv that contains plugins that depend on different versions of
tutor-openedx. This causes a crash that did not log the name of the responsible
package. For instance:
Traceback (most recent call last):
File "/home/regis/venvs/tutor/bin/tutor", line 11, in <module>
load_entry_point('tutor-openedx', 'console_scripts', 'tutor')()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/cli.py", line 37, in main
add_plugin_commands(cli)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/commands/plugins.py", line 137, in add_plugin_commands
for plugin in plugins.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 401, in iter_installed
yield from Plugins.iter_installed()
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 362, in iter_installed
for plugin in PluginClass.iter_installed():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 199, in iter_installed
for plugin in cls.iter_load():
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 233, in iter_load
yield cls(entrypoint)
File "/home/regis/projets/overhang/repos/overhang/tutor/tutor/plugins.py", line 220, in __init__
super().__init__(entrypoint.name, entrypoint.load())
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2442, in load
self.require(*args, **kwargs)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 2465, in require
items = working_set.resolve(reqs, env, installer, extras=self.extras)
File "/home/regis/venvs/tutor/lib/python3.8/site-packages/pkg_resources/__init__.py", line 791, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.VersionConflict: (tutor-openedx 11.2.11 (/home/regis/projets/overhang/repos/overhang/tutor), Requirement.parse('tutor-openedx<13.0.0,>=12.0.0'))
In this commit, we introduce an error log that displays the name and location
of the package. E.g:
Failed to load entrypoint 'minio = tutorminio.plugin' from distribution tutor-minio 12.0.0
2021-05-20 07:58:54 +00:00
|
|
|
)
|
|
|
|
)
|
2020-01-14 12:32:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
class OfficialPlugin(BasePlugin):
|
|
|
|
"""
|
2020-10-15 14:28:55 +00:00
|
|
|
Official plugins have a "plugin" module which exposes a __version__ attribute.
|
|
|
|
Official plugins should be manually added by calling `OfficialPlugin.load()`.
|
2020-01-14 12:32:45 +00:00
|
|
|
"""
|
|
|
|
|
2020-10-15 14:28:55 +00:00
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def load(cls, name: str) -> BasePlugin:
|
2020-10-15 14:28:55 +00:00
|
|
|
plugin = cls(name)
|
|
|
|
cls.INSTALLED.append(plugin)
|
|
|
|
return plugin
|
2020-01-14 12:32:45 +00:00
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def __init__(self, name: str):
|
2020-01-14 12:32:45 +00:00
|
|
|
self.module = importlib.import_module("tutor{}.plugin".format(name))
|
|
|
|
super().__init__(name, self.module)
|
|
|
|
|
|
|
|
@property
|
2021-02-25 08:09:14 +00:00
|
|
|
def version(self) -> str:
|
|
|
|
version = getattr(self.module, "__version__")
|
|
|
|
if not isinstance(version, str):
|
|
|
|
raise TypeError("OfficialPlugin __version__ must be 'str'")
|
|
|
|
return version
|
2020-01-14 12:32:45 +00:00
|
|
|
|
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_load(cls) -> Iterator[BasePlugin]:
|
2020-10-15 14:28:55 +00:00
|
|
|
yield from []
|
2020-01-14 12:32:45 +00:00
|
|
|
|
|
|
|
|
2020-01-14 14:42:20 +00:00
|
|
|
class DictPlugin(BasePlugin):
|
|
|
|
ROOT_ENV_VAR_NAME = "TUTOR_PLUGINS_ROOT"
|
|
|
|
ROOT = os.path.expanduser(
|
|
|
|
os.environ.get(ROOT_ENV_VAR_NAME, "")
|
2021-09-16 14:48:16 +00:00
|
|
|
) or appdirs.user_data_dir(appname=__app__ + "-plugins")
|
2020-01-14 14:42:20 +00:00
|
|
|
|
2021-04-06 10:09:00 +00:00
|
|
|
def __init__(self, data: Config):
|
|
|
|
name = data["name"]
|
|
|
|
if not isinstance(name, str):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid plugin name: '{}'. Expected str, got {}".format(
|
|
|
|
name, name.__class__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Create a generic object (sort of a named tuple) which will contain all key/values from data
|
|
|
|
class Module:
|
|
|
|
pass
|
|
|
|
|
|
|
|
obj = Module()
|
|
|
|
for key, value in data.items():
|
|
|
|
setattr(obj, key, value)
|
|
|
|
|
|
|
|
super().__init__(name, obj)
|
|
|
|
|
|
|
|
version = data["version"]
|
|
|
|
if not isinstance(version, str):
|
|
|
|
raise TypeError("DictPlugin.__version__ must be str")
|
|
|
|
self._version: str = version
|
2020-01-14 14:42:20 +00:00
|
|
|
|
|
|
|
@property
|
2021-02-25 08:09:14 +00:00
|
|
|
def version(self) -> str:
|
2020-01-14 14:42:20 +00:00
|
|
|
return self._version
|
|
|
|
|
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_load(cls) -> Iterator[BasePlugin]:
|
2020-01-14 14:42:20 +00:00
|
|
|
for path in glob(os.path.join(cls.ROOT, "*.yml")):
|
|
|
|
with open(path) as f:
|
|
|
|
data = serialize.load(f)
|
|
|
|
if not isinstance(data, dict):
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid plugin: {}. Expected dict.".format(path)
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
yield cls(data)
|
|
|
|
except KeyError as e:
|
|
|
|
raise exceptions.TutorError(
|
|
|
|
"Invalid plugin: {}. Missing key: {}".format(path, e.args[0])
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-01-14 12:32:45 +00:00
|
|
|
class Plugins:
|
2021-02-25 08:09:14 +00:00
|
|
|
PLUGIN_CLASSES: List[Type[BasePlugin]] = [
|
|
|
|
OfficialPlugin,
|
|
|
|
EntrypointPlugin,
|
|
|
|
DictPlugin,
|
|
|
|
]
|
2019-06-06 19:58:21 +00:00
|
|
|
|
2021-04-06 10:09:00 +00:00
|
|
|
def __init__(self, config: Config):
|
2019-07-10 08:20:43 +00:00
|
|
|
self.config = deepcopy(config)
|
2021-03-29 07:48:53 +00:00
|
|
|
# patches has the following structure:
|
|
|
|
# {patch_name -> {plugin_name -> "content"}}
|
2021-02-25 08:09:14 +00:00
|
|
|
self.patches: Dict[str, Dict[str, str]] = {}
|
2021-03-29 07:48:53 +00:00
|
|
|
# some hooks have a dict-like structure, like "build", others are list of services.
|
2021-02-25 08:09:14 +00:00
|
|
|
self.hooks: Dict[str, Dict[str, Union[Dict[str, str], List[str]]]] = {}
|
|
|
|
self.template_roots: Dict[str, str] = {}
|
2019-06-06 19:58:21 +00:00
|
|
|
|
2020-01-14 12:32:45 +00:00
|
|
|
for plugin in self.iter_enabled():
|
|
|
|
for patch_name, content in plugin.patches.items():
|
2019-06-06 19:58:21 +00:00
|
|
|
if patch_name not in self.patches:
|
|
|
|
self.patches[patch_name] = {}
|
2020-01-14 12:32:45 +00:00
|
|
|
self.patches[patch_name][plugin.name] = content
|
2019-06-06 19:58:21 +00:00
|
|
|
|
2020-01-14 12:32:45 +00:00
|
|
|
for hook_name, services in plugin.hooks.items():
|
2019-06-06 19:58:21 +00:00
|
|
|
if hook_name not in self.hooks:
|
|
|
|
self.hooks[hook_name] = {}
|
2020-01-14 12:32:45 +00:00
|
|
|
self.hooks[hook_name][plugin.name] = services
|
2019-06-06 19:58:21 +00:00
|
|
|
|
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def clear(cls) -> None:
|
2020-10-15 14:28:55 +00:00
|
|
|
for PluginClass in cls.PLUGIN_CLASSES:
|
|
|
|
PluginClass.INSTALLED.clear()
|
2019-05-29 09:14:06 +00:00
|
|
|
|
2019-06-06 19:58:21 +00:00
|
|
|
@classmethod
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_installed(cls) -> Iterator[BasePlugin]:
|
2020-01-14 12:32:45 +00:00
|
|
|
"""
|
2020-10-15 14:28:55 +00:00
|
|
|
Iterate on all installed plugins. Plugins are deduplicated by name. The list of installed plugins is cached to
|
|
|
|
prevent too many re-computations, which happens a lot.
|
2020-01-14 12:32:45 +00:00
|
|
|
"""
|
|
|
|
installed_plugin_names = set()
|
2021-11-01 19:42:23 +00:00
|
|
|
plugins = []
|
2020-10-15 14:28:55 +00:00
|
|
|
for PluginClass in cls.PLUGIN_CLASSES:
|
2020-01-14 12:32:45 +00:00
|
|
|
for plugin in PluginClass.iter_installed():
|
|
|
|
if plugin.name not in installed_plugin_names:
|
|
|
|
installed_plugin_names.add(plugin.name)
|
2021-11-01 19:42:23 +00:00
|
|
|
plugins.append(plugin)
|
|
|
|
plugins = sorted(plugins, key=lambda plugin: plugin.name)
|
|
|
|
yield from plugins
|
2019-06-06 19:58:21 +00:00
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_enabled(self) -> Iterator[BasePlugin]:
|
2020-01-14 12:32:45 +00:00
|
|
|
for plugin in self.iter_installed():
|
|
|
|
if is_enabled(self.config, plugin.name):
|
|
|
|
yield plugin
|
2019-06-06 19:58:21 +00:00
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_patches(self, name: str) -> Iterator[Tuple[str, str]]:
|
2019-06-06 19:58:21 +00:00
|
|
|
plugin_patches = self.patches.get(name, {})
|
2019-05-29 09:14:06 +00:00
|
|
|
plugins = sorted(plugin_patches.keys())
|
|
|
|
for plugin in plugins:
|
|
|
|
yield plugin, plugin_patches[plugin]
|
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_hooks(
|
|
|
|
self, hook_name: str
|
|
|
|
) -> Iterator[Tuple[str, Union[Dict[str, str], List[str]]]]:
|
2019-07-02 20:16:44 +00:00
|
|
|
yield from self.hooks.get(hook_name, {}).items()
|
2019-06-06 19:58:21 +00:00
|
|
|
|
2019-05-29 09:14:06 +00:00
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def get_callable_attr(
|
|
|
|
plugin: Any, attr_name: str, default: Optional[Any] = None
|
|
|
|
) -> Optional[Any]:
|
2019-06-05 18:07:41 +00:00
|
|
|
attr = getattr(plugin, attr_name, default)
|
2019-05-29 09:14:06 +00:00
|
|
|
if callable(attr):
|
|
|
|
attr = attr()
|
|
|
|
return attr
|
|
|
|
|
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def is_installed(name: str) -> bool:
|
2020-09-18 10:39:22 +00:00
|
|
|
for plugin in iter_installed():
|
|
|
|
if name == plugin.name:
|
|
|
|
return True
|
|
|
|
return False
|
2019-05-29 09:14:06 +00:00
|
|
|
|
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_installed() -> Iterator[BasePlugin]:
|
2019-06-06 19:58:21 +00:00
|
|
|
yield from Plugins.iter_installed()
|
2019-05-29 09:14:06 +00:00
|
|
|
|
|
|
|
|
2021-04-06 10:09:00 +00:00
|
|
|
def enable(config: Config, name: str) -> None:
|
2019-05-29 09:14:06 +00:00
|
|
|
if not is_installed(name):
|
|
|
|
raise exceptions.TutorError("plugin '{}' is not installed.".format(name))
|
|
|
|
if is_enabled(config, name):
|
|
|
|
return
|
2021-04-06 10:09:00 +00:00
|
|
|
enabled = enabled_plugins(config)
|
|
|
|
enabled.append(name)
|
|
|
|
enabled.sort()
|
2019-05-29 09:14:06 +00:00
|
|
|
|
|
|
|
|
2021-06-14 07:37:58 +00:00
|
|
|
def disable(config: Config, plugin: BasePlugin) -> None:
|
|
|
|
# Remove plugin-specific set config
|
|
|
|
for key in plugin.config_set.keys():
|
|
|
|
config.pop(key, None)
|
|
|
|
|
|
|
|
# Remove plugin from list of enabled plugins
|
2021-04-06 10:09:00 +00:00
|
|
|
enabled = enabled_plugins(config)
|
2021-06-14 07:37:58 +00:00
|
|
|
while plugin.name in enabled:
|
|
|
|
enabled.remove(plugin.name)
|
|
|
|
|
|
|
|
|
|
|
|
def get_enabled(config: Config, name: str) -> BasePlugin:
|
|
|
|
for plugin in iter_enabled(config):
|
|
|
|
if plugin.name == name:
|
|
|
|
return plugin
|
|
|
|
raise ValueError("Enabled plugin {} could not be found.".format(plugin.name))
|
2019-06-05 13:43:51 +00:00
|
|
|
|
|
|
|
|
2021-04-06 10:09:00 +00:00
|
|
|
def iter_enabled(config: Config) -> Iterator[BasePlugin]:
|
2020-10-15 14:28:55 +00:00
|
|
|
yield from Plugins(config).iter_enabled()
|
2019-05-29 09:14:06 +00:00
|
|
|
|
|
|
|
|
2021-04-06 10:09:00 +00:00
|
|
|
def is_enabled(config: Config, name: str) -> bool:
|
|
|
|
return name in enabled_plugins(config)
|
|
|
|
|
|
|
|
|
|
|
|
def enabled_plugins(config: Config) -> List[str]:
|
|
|
|
if not config.get(CONFIG_KEY):
|
|
|
|
config[CONFIG_KEY] = []
|
|
|
|
plugins = get_typed(config, CONFIG_KEY, list)
|
|
|
|
return plugins
|
2019-05-29 09:14:06 +00:00
|
|
|
|
|
|
|
|
2021-04-06 10:09:00 +00:00
|
|
|
def iter_patches(config: Config, name: str) -> Iterator[Tuple[str, str]]:
|
2020-10-15 14:28:55 +00:00
|
|
|
yield from Plugins(config).iter_patches(name)
|
2019-05-29 09:14:06 +00:00
|
|
|
|
|
|
|
|
2021-02-25 08:09:14 +00:00
|
|
|
def iter_hooks(
|
2021-04-06 10:09:00 +00:00
|
|
|
config: Config, hook_name: str
|
2021-02-25 08:09:14 +00:00
|
|
|
) -> Iterator[Tuple[str, Union[Dict[str, str], List[str]]]]:
|
2020-10-15 14:28:55 +00:00
|
|
|
yield from Plugins(config).iter_hooks(hook_name)
|