sbsv2/raptor/python/pluginbox.py
changeset 0 044383f39525
child 3 e1eecf4d390d
equal deleted inserted replaced
-1:000000000000 0:044383f39525
       
     1 #
       
     2 # Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
       
     3 # All rights reserved.
       
     4 # This component and the accompanying materials are made available
       
     5 # under the terms of the License "Eclipse Public License v1.0"
       
     6 # which accompanies this distribution, and is available
       
     7 # at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8 #
       
     9 # Initial Contributors:
       
    10 # Nokia Corporation - initial contribution.
       
    11 #
       
    12 # Contributors:
       
    13 #
       
    14 # Description: 
       
    15 # PluginBox module - finds classes 
       
    16 #
       
    17 
       
    18 from os import listdir
       
    19 import re
       
    20 from types import TypeType, ModuleType
       
    21 import sys
       
    22 
       
    23 class PluginModule(object):
       
    24 	"""Represents a module containing plugin classes """
       
    25 	def __init__(self, file):
       
    26 		self.module = __import__(file)
       
    27 		self.classes = []
       
    28 		self.__findclasses(self.module)
       
    29 
       
    30 	def __findclasses(self,module):
       
    31 		for c in module.__dict__:
       
    32 			mbr = module.__dict__[c]
       
    33 			if type(mbr) == TypeType:
       
    34 				self.classes.append(mbr)
       
    35 
       
    36 class PluginBox(object):
       
    37 	"""
       
    38 	A container that locates all the classes in a directory.
       
    39 	Example usage:
       
    40 
       
    41 		from person import Person
       
    42 		ps = PluginBox("plugins")
       
    43 		people = []
       
    44 		for i in ps.classesof(Person):
       
    45 			people.append(i())
       
    46 
       
    47 	"""
       
    48 	plugfilenamere=re.compile('^(.*)\.py$',re.I)
       
    49 	def __init__(self, plugindirectory):
       
    50 		self.pluginlist = []
       
    51 		self.plugindir = plugindirectory
       
    52 		sys.path.append(str(self.plugindir))
       
    53 		for f in listdir(plugindirectory):
       
    54 			m = PluginBox.plugfilenamere.match(f)
       
    55 			if m is not None:
       
    56 				self.pluginlist.append(PluginModule(m.groups()[0]))
       
    57 		sys.path = sys.path[:-1]
       
    58 
       
    59 	def classesof(self, classtype):
       
    60 		"""return a list of all classes that are subclasses of <classtype>"""
       
    61 		classes = []
       
    62 		for p in self.pluginlist:
       
    63 			for c in p.classes:
       
    64 				if issubclass(c, classtype):
       
    65 					if c.__name__ != classtype.__name__:
       
    66 						classes.append(c)
       
    67 		return classes
       
    68