From be716bf228685f11742dcf15a0d9189dddd3d6a8 Mon Sep 17 00:00:00 2001 From: Dmitri Bogomolov <4glitch@gmail.com> Date: Fri, 10 Mar 2017 16:45:46 +0200 Subject: [PATCH] Improved and documented plugin module --- src/bitmessageqt/__init__.py | 16 +++++++++------- src/plugins/plugin.py | 29 +++++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 44dcb8ec..39202d17 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -86,7 +86,7 @@ import throttle from version import softwareVersion try: - from plugins.plugin import get_plugins + from plugins.plugin import get_plugin, get_plugins except ImportError: get_plugins = False @@ -1441,19 +1441,21 @@ class MyForm(settingsmixin.SMainWindow): self.tray.showMessage(title, subtitle, 1, 2000) self._notifier = _simple_notify + # does nothing if isAvailable returns false self._player = QtGui.QSound.play if not get_plugins: return - for plugin in get_plugins('notification.message'): - self._notifier = plugin - break + _plugin = get_plugin('notification.message') + if _plugin: + self._notifier = _plugin if not QtGui.QSound.isAvailable(): - for plugin in get_plugins('notification.sound'): - self._player = plugin - break + _plugin = get_plugin( + 'notification.sound', 'file', fallback='file.fallback') + if _plugin: + self._player = _plugin else: logger.warning("No sound player plugin found!") diff --git a/src/plugins/plugin.py b/src/plugins/plugin.py index 395f0e9d..ba14b836 100644 --- a/src/plugins/plugin.py +++ b/src/plugins/plugin.py @@ -3,12 +3,33 @@ import pkg_resources -def get_plugins(group, point='', name=None): - for plugin in pkg_resources.iter_entry_points(group): - if plugin.name == name or plugin.name.startswith(point): +def get_plugins(group, point='', name=None, fallback=None): + """ + 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: - yield plugin.load().connect_plugin + plugin = ep.load().connect_plugin + if ep.name == fallback: + _fallback = plugin + else: + yield plugin except (AttributeError, + ImportError, + ValueError, pkg_resources.DistributionNotFound, pkg_resources.UnknownExtra): 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