Improved and documented plugin module

This commit is contained in:
Dmitri Bogomolov 2017-03-10 16:45:46 +02:00
parent ef8f40ccc4
commit be716bf228
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13
2 changed files with 34 additions and 11 deletions

View File

@ -86,7 +86,7 @@ import throttle
from version import softwareVersion from version import softwareVersion
try: try:
from plugins.plugin import get_plugins from plugins.plugin import get_plugin, get_plugins
except ImportError: except ImportError:
get_plugins = False get_plugins = False
@ -1441,19 +1441,21 @@ class MyForm(settingsmixin.SMainWindow):
self.tray.showMessage(title, subtitle, 1, 2000) self.tray.showMessage(title, subtitle, 1, 2000)
self._notifier = _simple_notify self._notifier = _simple_notify
# does nothing if isAvailable returns false
self._player = QtGui.QSound.play self._player = QtGui.QSound.play
if not get_plugins: if not get_plugins:
return return
for plugin in get_plugins('notification.message'): _plugin = get_plugin('notification.message')
self._notifier = plugin if _plugin:
break self._notifier = _plugin
if not QtGui.QSound.isAvailable(): if not QtGui.QSound.isAvailable():
for plugin in get_plugins('notification.sound'): _plugin = get_plugin(
self._player = plugin 'notification.sound', 'file', fallback='file.fallback')
break if _plugin:
self._player = _plugin
else: else:
logger.warning("No sound player plugin found!") logger.warning("No sound player plugin found!")

View File

@ -3,12 +3,33 @@
import pkg_resources import pkg_resources
def get_plugins(group, point='', name=None): def get_plugins(group, point='', name=None, fallback=None):
for plugin in pkg_resources.iter_entry_points(group): """
if plugin.name == name or plugin.name.startswith(point): Iterate through plugins (`connect_plugin` attribute of entry point)
which name starts with `point` or equals to `name`.
If `fallback` kwarg specified, plugin with that name yield last.
"""
for ep in pkg_resources.iter_entry_points(group):
if name and ep.name == name or ep.name.startswith(point):
try: try:
yield plugin.load().connect_plugin plugin = ep.load().connect_plugin
if ep.name == fallback:
_fallback = plugin
else:
yield plugin
except (AttributeError, except (AttributeError,
ImportError,
ValueError,
pkg_resources.DistributionNotFound, pkg_resources.DistributionNotFound,
pkg_resources.UnknownExtra): pkg_resources.UnknownExtra):
continue continue
try:
yield _fallback
except NameError:
pass
def get_plugin(*args, **kwargs):
"""Returns first available plugin `from get_plugins()` if any."""
for plugin in get_plugins(*args, **kwargs):
return plugin