summaryrefslogtreecommitdiff
path: root/portato/plugin.py
diff options
context:
space:
mode:
authorRené 'Necoro' Neumann <necoro@necoro.net>2008-07-08 15:00:20 +0200
committerRené 'Necoro' Neumann <necoro@necoro.net>2008-07-08 15:00:20 +0200
commit276451a383052ffdc67f561082825cc84aa83bd7 (patch)
treea148e31c8d201ecc61903eae18a495b9cfdf80be /portato/plugin.py
parent0a8814713917548767f0ff823e34d412061b3ffe (diff)
parent8b6db38a2d27fca00d0fe037e86eefc941d559e4 (diff)
downloadportato-276451a383052ffdc67f561082825cc84aa83bd7.tar.gz
portato-276451a383052ffdc67f561082825cc84aa83bd7.tar.bz2
portato-276451a383052ffdc67f561082825cc84aa83bd7.zip
Merged in the new plugin system
Diffstat (limited to 'portato/plugin.py')
-rw-r--r--portato/plugin.py825
1 files changed, 423 insertions, 402 deletions
diff --git a/portato/plugin.py b/portato/plugin.py
index 5926922..0119909 100644
--- a/portato/plugin.py
+++ b/portato/plugin.py
@@ -3,349 +3,421 @@
# File: portato/plugin.py
# This file is part of the Portato-Project, a graphical portage-frontend.
#
-# Copyright (C) 2007 René 'Necoro' Neumann
+# Copyright (C) 2008 René 'Necoro' Neumann
# This is free software. You may redistribute copies of it under the terms of
# the GNU General Public License version 2.
# There is NO WARRANTY, to the extent permitted by law.
#
# Written by René 'Necoro' Neumann <necoro@necoro.net>
-"""A module containing the management of the plugin system."""
+"""
+A module managing the plugins for Portato.
+"""
from __future__ import absolute_import
-
-import os, os.path
-from xml.dom.minidom import parse
-from lxml import etree
-
-from .constants import PLUGIN_DIR, XSD_LOCATION
-from .helper import debug, info, warning, error, flatten
-
-class PluginImportException (ImportError):
+__docformat__ = "restructuredtext"
+
+import os
+import os.path as osp
+import traceback
+from collections import defaultdict
+from functools import wraps
+
+from .helper import debug, warning, info, error
+from .constants import PLUGIN_DIR
+from .backend import system
+from . import plugins as plugin_module
+
+class PluginLoadException (Exception):
+ """
+ Exception signaling a failed plugin loading.
+ """
pass
-class Options (object):
- """The <options>-element."""
+class Menu (object):
+ """
+ One single menu entry.
- __options = ("disabled", "blocking")
+ :IVariables:
- def __init__ (self, options = None):
+ label : string
+ The label of the entry. Can have underscores to define the shortcut.
- self.disabled = False
- self.blocking = False
+ call
+ The function to call, if the entry is clicked.
+ """
+ __slots__ = ("label", "call")
- if options:
- self.parse(options)
-
- def parse (self, options):
- for opt in options:
- nodes = opt.childNodes
- type = str(nodes[0].nodeValue.strip())
- if type in self.__options:
- self.set(type, True)
+ def __init__ (self, label, call):
+ self.label = label
+ self.call = call
- def get (self, name):
- return self.__getattribute__(name)
+class Call (object):
+ """
+ This class represents an object, which is attached to a specified hook.
- def set (self, name, value):
- return self.__setattr__(name, value)
+ :IVariables:
-class Menu:
- """A single <menu>-element."""
- def __init__ (self, plugin, label, call):
- """Constructor.
+ plugin : `Plugin`
+ The plugin where this call belongs to.
- @param plugin: the plugin this menu belongs to
- @type plugin: Plugin
- @param label: the label to show
- @type label: string
- @param call: the function to call relative to the import statement
- @type call: string
+ hook : string
+ The name of the corresponding hook.
- @raises PluginImportException: if the plugin's import could not be imported"""
+ call
+ The function to call.
- self.label = label
- self.plugin = plugin
+ type : string
+ This is either ``before``, ``after`` or ``override`` and defines the type of the call:
- if self.plugin.needs_import(): # get import
- imp = self.plugin.get_import()
- try:
- mod = __import__(imp, globals(), locals(), [call])
- except ImportError:
- raise PluginImportException, imp
+ before
+ access before the original function
+ override
+ access *instead of* the original function. **USE THIS ONLY IF YOU KNOW WHAT YOU ARE DOING**
+ after
+ access after the original function has been called
- try:
- self.call = eval("mod."+call) # build function
- except AttributeError:
- raise PluginImportException, imp
- else:
- try:
- self.call = eval(call)
- except AttributeError:
- raise PluginImportException, imp
+ Default: ``before``
-class Connect:
- """A single <connect>-element."""
+ dep : string
+ This defines a plugin which should be executed after/before this one.
+ ``"*"`` means all and ``"-*"`` means none.
+ """
+ __slots__ = ("plugin", "hook", "call", "type", "dep")
- def __init__ (self, hook, type, depend_plugin):
- """Constructor.
+ def __init__ (self, plugin, hook, call, type = "before", dep = None):
+ self.plugin = plugin
+ self.hook = hook
+ self.call = call
+ self.type = type
+ self.dep = dep
- @param hook: the parent Hook
- @type hook: Hook
- @param type: the type of the connect ("before", "after", "override")
- @type type: string
- @param depend_plugin: a plugin we are dependant on
- @type depend_plugin: string or None"""
+class Hook (object):
+ """
+ Representing a hook with all the `Call` s for the different types.
+ """
+
+ __slots__ = ("before", "override", "after")
- self.type = type
- self.hook = hook
- self.depend_plugin = depend_plugin
+ def __init__ (self):
+ self.before = []
+ self.override = None
+ self.after = []
- def is_before_type (self):
- return self.type == "before"
+class Plugin (object):
+ """
+ This is the main plugin object. It is used where ever a plugin is wanted, and it is the one, which needs to be subclassed by plugin authors.
- def is_after_type (self):
- return self.type == "after"
+ :CVariables:
- def is_override_type (self):
- return self.type == "override"
+ STAT_DISABLED : status
+ Status: Disabled.
-class Hook:
- """A single <hook>-element."""
+ STAT_TEMP_ENABLED : status
+ Status: Enabled for this session only.
- def __init__ (self, plugin, hook, call):
- """Constructor.
+ STAT_ENABLED : status
+ Status: Enabled.
- @param plugin: the parent Plugin
- @type plugin: Plugin
- @param hook: the hook to add to
- @type hook: string
- @param call: the call to make
- @type call: string"""
+ STAT_TEMP_DISABLED : status
+ Status: Disabled for this session only.
- self.plugin = plugin
- self.hook = hook
- self.call = call
- self.connects = []
+ STAT_HARD_DISABLED : status
+ Status: Forced disabled by program (i.e. because of errors in the plugin).
+ """
- def parse_connects (self, connects):
- """This gets a list of <connect>-elements and parses them.
-
- @param connects: the list of <connect>'s
- @type connects: NodeList"""
-
- if not connects: # no connects - assume "before" connect
- self.connects.append(Connect(self, "before", None))
+ (STAT_DISABLED, STAT_TEMP_ENABLED, STAT_ENABLED, STAT_TEMP_DISABLED) = range(4)
+ STAT_HARD_DISABLED = -1
+
+ def __init__ (self, disable = False):
+ """
+ :param disable: Forcefully disable the plugin
+ :type disable: bool
+ """
+ self.__menus = [] #: List of `Menu`
+ self.__calls = [] #: List of `Call`
+ self._unresolved_deps = False #: Does this plugin has unresolved dependencies?
+
+ self.status = self.STAT_ENABLED #: The status of this plugin
- for c in connects:
- type = c.getAttribute("type")
- if type == '':
- type = "before"
-
- # get dep_plugin if available
- dep_plugin = None
- if c.hasChildNodes():
- nodes = c.childNodes
- dep_plugin = nodes[0].nodeValue.strip()
-
- connect = Connect(self, type, dep_plugin)
- self.connects.append(connect)
+ if disable:
+ self.status = self.STAT_HARD_DISABLED
+
+ def _init (self):
+ """
+ Method called from outside to init the extension parts of this plugin.
+ If the current status is `STAT_HARD_DISABLED` or there are unresolved dependencies, the init process is not started.
+ """
+
+ for d in self.deps:
+ if not system.find_packages(d, pkgSet="installed", with_version = False):
+ self._unresolved_deps = True
+ break
-class Plugin:
- """A complete plugin."""
-
- (STAT_DISABLED, STAT_TEMP_ENABLED, STAT_ENABLED, STAT_TEMP_DISABLED) = range(4)
-
- def __init__ (self, file, name, author):
- """Constructor.
-
- @param file: the file name of the plugin.xml
- @type file: string
- @param name: the name of the plugin
- @type name: Node
- @param author: the author of the plugin
- @type author: Node"""
+ if self.status != self.STAT_HARD_DISABLED and not self._unresolved_deps:
+ self.init()
+
+ def init (self):
+ """
+ This method is called by `_init` and should be overriden by the plugin author.
+
+ :precond: No unresolved deps and the status is not `STAT_HARD_DISABLED`.
+ """
+ pass
+
+ @property
+ def author (self):
+ """
+ Returns the plugin's author.
+ The author is given by the ``__author__`` variable.
+
+ :rtype: string
+ """
+ return getattr(self, "__author__", "")
+
+ @property
+ def description (self):
+ """
+ Returns the description of this plugin.
+ It is given by either a ``__description__`` variable or by the normal class docstring.
+
+ :rtype: string
+ """
+ if hasattr(self, "__description__"):
+ return self.__description__
+ else:
+ doc = getattr(self, "__doc__", "")
- self.file = file
- self.name = name.firstChild.nodeValue.strip()
- self.author = author.firstChild.nodeValue.strip()
- self._import = None
- self.hooks = []
- self.menus = []
- self.options = Options()
+ if not doc or doc == Plugin.__doc__:
+ return ""
+ else:
+ return doc
+
+ @property
+ def name (self):
+ """
+ The name of the plugin. If no ``__name__`` variable is given, the class name is taken.
+
+ :rtype: string
+ """
+ return getattr(self, "__name__", self.__class__.__name__)
+
+ @property
+ def menus (self):
+ """
+ Returns an iterator over the menus for this plugin.
+
+ :rtype: iter<`Menu`>
+ """
+ return iter(self.__menus)
+
+ @property
+ def calls (self):
+ """
+ Returns an iterator over the registered calls for this plugin.
+
+ :rtype: iter<`Call`>
+ """
+ return iter(self.__calls)
+
+ @property
+ def deps (self):
+ """
+ Returns an iterator of the dependencies or ``[]`` if there are none.
+ The dependencies are given in the ``__dependency__`` variable.
+
+ :rtype: [] or iter<string>
+ """
+ if hasattr(self, "__dependency__"):
+ return iter(self.__dependency__)
+ else:
+ return []
- self.status = self.STAT_ENABLED
+ @property
+ def enabled (self):
+ """
+ Returns ``True`` if the plugin is enabled.
- def parse_hooks (self, hooks):
- """Gets an <hooks>-elements and parses it.
+ :rtype: boolean
+ :see: `status`
+ """
+ return (self.status in (self.STAT_ENABLED, self.STAT_TEMP_ENABLED))
+
+ def add_menu (self, label, callable):
+ """
+ Adds a new menu item for this plugin.
- @param hooks: the hooks node
- @type hooks: NodeList"""
+ :see: `Menu`
+ """
+ self.__menus.append(Menu(label, callable))
- if hooks:
- for h in hooks[0].getElementsByTagName("hook"):
- hook = Hook(self, str(h.getAttribute("type")), str(h.getAttribute("call")))
- hook.parse_connects(h.getElementsByTagName("connect"))
- self.hooks.append(hook)
+ def add_call (self, hook, callable, type = "before", dep = None):
+ """
+ Adds a new call for this plugin.
- def parse_menus (self, menus):
- """Get a list of <menu>-elements and parses them.
+ :see: `Call`
+ """
+ self.__calls.append(Call(self, hook, callable, type, dep))
- @param menus: the menu nodelist
- @type menus: NodeList"""
- if menus:
- for item in menus[0].getElementsByTagName("item"):
- menu = Menu(self, item.firstChild.nodeValue.strip(), str(item.getAttribute("call")))
- self.menus.append(menu)
+class PluginQueue (object):
+ """
+ Class managing and loading the plugins.
+
+ :IVariables:
- def parse_options (self, options):
- if options:
- for o in options:
- self.options.parse(o.getElementsByTagName("option"))
+ plugins : `Plugin` []
+ The list of managed plugins.
- self.status = self.STAT_DISABLED if self.options.get("disabled") else self.STAT_ENABLED
-
- def set_import (self, imports):
- """This gets a list of imports and parses them - setting the import needed to call the plugin.
+ hooks : string -> `Hook`
+ For each hook name map to a `Hook` object holding the corresponding `Call` objects.
+ """
- @param imports: list of imports
- @type imports: NodeList
-
- @raises PluginImportException: if the plugin's import could not be imported"""
+ def __init__ (self):
+ """
+ Constructor.
+ """
- if imports:
- self._import = str(imports[0].firstChild.nodeValue.strip())
+ self.plugins = []
+ self.hooks = defaultdict(Hook)
- try: # try loading
- mod = __import__(self._import)
- del mod
- except ImportError:
- raise PluginImportException, self._import
+ def get_plugins (self, list_disabled = True):
+ """
+ Returns the plugins.
- def needs_import (self):
- """Returns True if an import is required prior to calling the plugin.
- @rtype: bool"""
- return self._import is not None
+ :param list_disabled: Also list disabled plugins.
+ :type list_disabled: boolean
- def get_import (self):
- """Returns the module to import.
- @rtype: string"""
- return self._import
+ :rtype: iter<`Plugin`>
+ """
+ return (x for x in self.plugins if (x.enabled or list_disabled))
- def get_option(self, name):
- return self.options.get(name)
+ def load (self):
+ """
+ Load the plugins.
+
+ This method scans the `portato.constants.PLUGIN_DIR` for python modules and tries to load them. If the modules are real plugins,
+ they have called `register` and thus the plugins are added.
+ """
+
+ # look them up
+ plugins = []
+ for f in os.listdir(PLUGIN_DIR):
+ path = osp.join(PLUGIN_DIR, f)
+ if osp.isdir(path):
+ if osp.isfile(osp.join(path, "__init__.py")):
+ plugins.append(f)
+ else:
+ debug("'%s' is not a plugin: __init__.py missing", path)
+ else:
+ if f.endswith(".py"):
+ plugins.append(f[:-3])
+ elif f.endswith(".pyc") or f.endswith(".pyo"):
+ pass # ignore .pyc and .pyo
+ else:
+ debug("'%s' is not a plugin: not a .py file", path)
+
+ # some magic ...
+ plugin_module.__path__.insert(0, PLUGIN_DIR.rstrip("/")) # make the plugins loadable as "portato.plugins.name"
+ # add Plugin and register to the builtins, so the plugins always have the correct version :)
+ plugin_module.__builtins__["Plugin"] = Plugin
+ plugin_module.__builtins__["register"] = register
+
+ for p in plugins: # import them
+ try:
+ exec "from portato.plugins import %s" % p in {}
+ except PluginLoadException, e:
+ error(_("Loading plugin '%(plugin)s' failed: %(error)s"), {"plugin" : p, "error" : e.message})
+ except:
+ tb = traceback.format_exc()
+ error(_("Loading plugin '%(plugin)s' failed: %(error)s"), {"plugin" : p, "error" : tb})
- def set_option (self, name, value):
- return self.options.set(name, value)
+ self._organize()
- def is_enabled (self):
- return (self.status in (self.STAT_ENABLED, self.STAT_TEMP_ENABLED))
+ def add (self, plugin, disable = False):
+ """
+ Adds a plugin to the internal list.
-class PluginQueue:
- """Class managing and loading the plugins."""
+ :Parameters:
- def __init__ (self, frontend, load = True):
- """Constructor.
-
- @param frontend: the frontend used
- @type frontend: string
- @param load: if False nothing is loaded
- @type load: bool"""
+ plugin : `Plugin`
+ ``Plugin`` subclass or instance to add. If a class is passed, it is instantiated.
- self.frontend = frontend
- self.list = []
- self.hooks = {}
- if load:
- self._load()
+ disable : boolean
+ Disable the plugin.
- def get_plugins (self, list_disabled = True):
- return [x for x in self.list if (x.is_enabled() or list_disabled)]
+ :raise PluginLoadException: passed plugin is not of class `Plugin`
+ """
- def get_plugin_data (self, list_disabled = False):
- return [(x.name, x.author) for x in self.list if (x.is_enabled() or list_disabled)]
+ if callable(plugin) and Plugin in plugin.__bases__:
+ p = plugin(disable = disable) # need an instance and not the class
+ elif isinstance(plugin, Plugin):
+ p = plugin
+ if disable:
+ p.status = p.STAT_HARD_DISABLED
+ else:
+ raise PluginLoadException, "Is neither a subclass nor an instance of Plugin."
- def get_plugin_menus (self, list_disabled = False):
- return flatten([x.menus for x in self.list if (x.is_enabled() or list_disabled)])
+ p._init()
- def hook (self, hook, *hargs, **hkwargs):
- """This is a method taking care of calling the plugins.
+ self.plugins.append(p)
- B{Example}::
-
- @pluginQueue.hook("some_hook", data)
- def function (a, b, c):
- orig_call(b,c,data)
-
- def function (a, b, c):
- hook = pluginQueue.hook("some_hook", data)
- hook(orig_call)(b,c,data)
+ if p.status == p.STAT_HARD_DISABLED:
+ msg = _("Plugin is disabled!")
+ elif p._unresolved_deps:
+ msg = _("Plugin has unresolved dependencies - disabled!")
+ else:
+ msg = ""
+
+ info("%s %s", _("Plugin '%s' loaded.") % p.name, msg)
- @param hook: the name of the hook
- @type hook: string"""
-
- def call (cmd):
- """Convienience function for calling a connect.
- @param cmd: the actual Connect
- @type cmd: Connect"""
-
- imp = ""
- if cmd.hook.plugin.needs_import(): # get import
- imp = cmd.hook.plugin.get_import()
- try:
- mod = __import__(imp, globals(), locals(), [cmd.hook.call])
- except ImportError:
- error(_("%s cannot be imported."), imp)
- return
-
- try:
- f = eval("mod."+cmd.hook.call) # build function
- except AttributeError:
- error(_("%s cannot be imported."), cmd.hook.call)
- else:
- try:
- f = eval(cmd.hook.call)
- except AttributeError:
- error(_("%s cannot be imported."), cmd.hook.call)
+ def hook (self, hook, *hargs, **hkwargs):
+ """
+ The decorator to use in the program.
+ All parameters except ``hook`` are passed to plugins.
- return f(*hargs, **hkwargs) # call function
+ :param hook: the name of the hook
+ :type hook: string
+ """
def hook_decorator (func):
- """This is the real decorator."""
-
- if hook in self.hooks:
- list = self.hooks[hook]
- else:
- list = ([],[],[])
+ """
+ The real decorator.
+ """
+ h = self.hooks[hook]
+
+ active = Hook()
# remove disabled
- _list = ([],[],[])
- for i in range(len(list)):
- for cmd in list[i]:
- if cmd.hook.plugin.is_enabled():
- _list[i].append(cmd)
-
- list = _list
+ for type in ("before", "after"):
+ calls = getattr(h, type)
+ aCalls = getattr(active, type)
+ for call in calls:
+ if call.plugin.enabled:
+ aCalls.append(call)
+
+ if h.override and h.override.plugin.enabled:
+ active.override = h.override
+ @wraps(func)
def wrapper (*args, **kwargs):
-
ret = None
# before
- for cmd in list[0]:
- debug(_("Accessing hook '%(hook)s' of plugin '%(plugin)s' (before)."), {"hook" : hook, "plugin": cmd.hook.plugin.name})
- call(cmd)
+ for call in active.before:
+ debug("Accessing hook '%(hook)s' of plugin '%(plugin)s' (before).", {"hook" : hook, "plugin": call.plugin.name})
+ call.call(*hargs, **hkwargs)
- if list[1]: # override
- info(_("Overriding hook '%(hook)s' with plugin '%(plugin)s'."), {"hook": hook, "plugin": list[1][0].hook.plugin.name})
- ret = call(list[1][0])
+ if active.override: # override
+ info(_("Overriding hook '%(hook)s' with plugin '%(plugin)s'."), {"hook": hook, "plugin": active.override.plugin.name})
+ ret = active.override.call(*hargs, **hkwargs)
else: # normal
ret = func(*args, **kwargs)
# after
- for cmd in list[2]:
- debug(_("Accessing hook '%(hook)s' of plugin '%(plugin)s' (after)."), {"hook":hook, "plugin": cmd.hook.plugin.name})
- call(cmd)
+ for call in active.after:
+ debug("Accessing hook '%(hook)s' of plugin '%(plugin)s' (after).", {"hook": hook, "plugin": call.plugin.name})
+ call.call(*hargs, **hkwargs)
return ret
@@ -353,178 +425,127 @@ class PluginQueue:
return hook_decorator
- def _load (self):
- """Load the plugins."""
- plugins = filter(lambda x: x.endswith(".xml"), os.listdir(PLUGIN_DIR))
- plugins = map(lambda x: os.path.join(PLUGIN_DIR, x), plugins)
- schema = etree.XMLSchema(file = XSD_LOCATION)
-
- for p in plugins:
-
- try:
- schema.assertValid(etree.parse(p))
- except etree.XMLSyntaxError:
- error(_("Loading plugin '%s' failed. Invalid XML syntax."), p)
- continue
- except etree.DocumentInvalid:
- error(_("Loading plugin '%s' failed. Plugin does not comply with schema."), p)
- continue
-
- doc = parse(p)
-
- try:
- list = doc.getElementsByTagName("plugin")
- elem = list[0]
-
- frontendOK = None
- frontends = elem.getElementsByTagName("frontends")
- if frontends:
- nodes = frontends[0].childNodes
- for f in nodes[0].nodeValue.strip().split():
- if f == self.frontend:
- frontendOK = True # one positive is enough
- break
- elif frontendOK is None: # do not make negative if we already have a positive
- frontendOK = False
-
- if frontendOK is None or frontendOK == True:
- plugin = Plugin(p, elem.getElementsByTagName("name")[0], elem.getElementsByTagName("author")[0])
- plugin.parse_hooks(elem.getElementsByTagName("hooks"))
- plugin.set_import(elem.getElementsByTagName("import"))
- plugin.parse_menus(elem.getElementsByTagName("menu"))
- plugin.parse_options(elem.getElementsByTagName("options"))
-
- self.list.append(plugin)
- info(_("Plugin '%s' loaded."), p)
-
- except PluginImportException, e:
- error(_("Loading plugin '%(plugin)s' failed: Could not import %(import)s"), {"plugin": p, "import": e[0]})
- finally:
- doc.unlink()
-
- self._organize()
-
def _organize (self):
- """Creates the lists of connects in a way, that all dependencies are fullfilled."""
- unresolved_before = {}
- unresolved_after = {}
- star_before = {} # should be _before_ all other
- star_after = {} # should be _after_ all other
-
- for plugin in self.list: # plugins
- for hook in plugin.hooks: # hooks in plugin
- if not hook.hook in self.hooks:
- self.hooks[hook.hook] = ([], [], [])
-
- for connect in hook.connects: # connects in hook
-
- # type="before"
- if connect.is_before_type():
- if connect.depend_plugin is None: # no dependency -> straight add
- self.hooks[hook.hook][0].append(connect)
- elif connect.depend_plugin == "*":
- self.hooks[hook.hook][0][0:0] = [connect]
- elif connect.depend_plugin == "-*":
- if not hook.hook in star_before:
- star_before[hook.hook] = []
-
- star_before[hook.hook].append(connect)
+ """
+ Organizes the lists of `Call` in a way, that all dependencies are fullfilled.
+ """
+ unresolved_before = defaultdict(list)
+ unresolved_after = defaultdict(list)
+ star_before = defaultdict(Hook) # should be _before_ all other
+ star_after = defaultdict(Hook) # should be _after_ all other
+
+ for plugin in self.plugins: # plugins
+ for call in plugin.calls: # hooks in plugin
+ if call.type == "before":
+ if call.dep is None: # no dependency -> straight add
+ self.hooks[call.hook].before.append(call)
+ elif call.dep == "*":
+ self.hooks[call.hook].before.insert(0, call)
+ elif call.dep == "-*":
+ star_before[call.hook].append(call)
+ else:
+ named = [x.plugin.name for x in self.hooks[call.hook].before]
+ if call.dep in named:
+ self.hooks[call.hook].before.insert(named.index(call.dep), call)
else:
- named = [x.plugin.name for x in self.hooks[hook.hook][0]]
- if connect.depend_plugin in named:
- self.hooks[hook.hook][0].insert(named.index(connect.depend_plugin), connect)
- else:
- if not hook.hook in unresolved_before:
- unresolved_before[hook.hook] = []
-
- unresolved_before[hook.hook].append(connect)
-
- # type = "after"
- elif connect.is_after_type():
- if connect.depend_plugin is None: # no dependency -> straight add
- self.hooks[hook.hook][2].append(connect)
- elif connect.depend_plugin == "*":
- if not hook.hook in star_after:
- star_after[hook.hook] = []
-
- star_after[hook.hook].append(connect)
- elif connect.depend_plugin == "-*":
- self.hooks[hook.hook][2][0:0] = [connect]
+ unresolved_before[call.hook].append(call)
+
+ elif call.type == "after":
+ if call.dep is None: # no dependency -> straight add
+ self.hooks[call.hook].after.append(call)
+ elif call.dep == "*":
+ star_after[call.hook].append(call)
+ elif call.dep == "-*":
+ self.hooks[call.hook].after.insert(0, call)
+ else:
+ named = [x.plugin.name for x in self.hooks[call.hook].after]
+ if call.dep in named:
+ self.hooks[call.hook].after.insert(named.index(call.dep)+1, call)
else:
- named = [x.hook.plugin.name for x in self.hooks[hook.hook][2]]
- if connect.depend_plugin in named:
- self.hooks[hook.hook][2].insert(named.index(connect.depend_plugin)+1, connect)
- else:
- if not hook.hook in unresolved_after:
- unresolved_after[hook.hook] = []
-
- unresolved_after[hook.hook].append(connect)
+ unresolved_after[call.hook].append(call)
+
+ # type = "override"
+ elif call.type == "override":
+ if self.hooks[call.hook].override:
+ warning(_("For hook '%(hook)s' an override is already defined by plugin '%(plugin)s'!"), {"hook": call.hook, "plugin": self.hooks[call.hook].override.plugin.name})
+ warning(_("It is now replaced by the one from plugin '%s'!"), call.plugin.name)
- # type = "override"
- elif connect.is_override_type():
- if self.hooks[hook.hook][1]:
- warning(_("For hook '%(hook)s' an override is already defined by plugin '%(plugin)s'!"), {"hook": hook.hook, "plugin": self.hooks[hook.hook][1][0]})
-
- self.hooks[hook.hook][1][:1] = [connect]
- continue
+ self.hooks[call.hook].override = call
+ continue
self._resolve_unresolved(unresolved_before, unresolved_after)
- for hook in star_before:
- self.hooks[hook][0].extend(star_before[hook]) # append the list
+ for hook, calls in star_before.iteritems():
+ self.hooks[hook].before.extend(calls) # append the list
- for hook in star_after:
- self.hooks[hook][2].extend(star_after[hook]) # append the list
+ for hook, calls in star_after.iteritems():
+ self.hooks[hook].after.extend(calls) # append the list
def _resolve_unresolved (self, before, after):
- def resolve(hook, list, idx, add):
+ def resolve(hook, list, type, add):
if not list:
return
- changed = False
- for connect in list[:]:
- named = [x.plugin.name for x in self.hooks[hook][idx]]
- if connect.depend_plugin in named:
- changed = True
- self.hooks[hook][idx].insert(named.index(connect.depend_plugin)+add, connect)
- list.remove(connect)
+ callList = getattr(self.hooks[hook], type)
+ named = [x.plugin.name for x in callList]
- if changed:
- resolve(hook, list, idx, add)
+ while list and named:
+ newNamed = [] # use newNamed, so in each iteration only the plugins inserted last are searched
+ for call in list[:]:
+ if call.dep in named:
+ callList.insert(named.index(call.dep)+add, call)
+ list.remove(call)
+ newNamed.append(call.plugin.name)
+
+ named = newNamed
for l in list:
- warning("Command for hook '%(hook)s' in plugin '%(plugin)s' could not be added due to missing dependant: '%(dep)s'!", {"hook": hook, "plugin": l.hook.plugin.name, "dep": l.depend_plugin})
+ warning(_("Command for hook '%(hook)s' in plugin '%(plugin)s' could not be added due to missing dependant: '%(dep)s'!"), {"hook": hook, "plugin": l.plugin.name, "dep": l.dep})
for hook in before:
- resolve(hook, before[hook], 0, 0)
+ resolve(hook, before[hook], "before", 0)
for hook in after:
- resolve(hook, after[hook], 2, 1)
+ resolve(hook, after[hook], "after", 1)
__plugins = None
-def load_plugins(frontend):
- """Loads the plugins for a given frontend.
- @param frontend: The frontend. See L{constants.FRONTENDS} for the correct list of values.
- @type frontend: string"""
-
+def load_plugins():
+ """
+ Loads the plugins.
+ """
+
global __plugins
- if __plugins is None or __plugins.frontend != frontend:
- __plugins = PluginQueue(frontend)
+ if __plugins is None:
+ __plugins = PluginQueue()
+ __plugins.load()
+
def get_plugin_queue():
- """Returns the actual L{PluginQueue}. If it is C{None}, they are not being loaded yet.
+ """
+ Returns the actual `PluginQueue`. If it is ``None``, they are not being loaded yet.
- @returns: the actual L{PluginQueue} or C{None}
- @rtype: PluginQueue"""
+ :rtype: `PluginQueue` or ``None``"""
return __plugins
def hook(hook, *args, **kwargs):
+ """
+ Shortcut to `PluginQueue.hook`. If no `PluginQueue` is loaded, this does nothing.
+ """
if __plugins is None:
def pseudo_decorator(f):
return f
return pseudo_decorator
else:
return __plugins.hook(hook, *args, **kwargs)
+
+def register (plugin, disable = False):
+ """
+ Registers a plugin.
+
+ :see: `PluginQueue.add`
+ """
+ if __plugins is not None:
+ __plugins.add(plugin, disable)