loader.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://metrixplusplus.sourceforge.net
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. # Metrix++ is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 3 of the License.
  10. #
  11. # Metrix++ is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Metrix++. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import mpp.api
  20. import mpp.cmdparser
  21. import os
  22. import sys
  23. import ConfigParser
  24. import re
  25. class Loader(object):
  26. def __init__(self):
  27. self.plugins = []
  28. self.hash = {}
  29. def get_plugin(self, name):
  30. return self.hash[name]['instance']
  31. def iterate_plugins(self, is_reversed = False):
  32. if is_reversed == False:
  33. for item in self.plugins:
  34. yield item['instance']
  35. else:
  36. for item in reversed(self.plugins):
  37. yield item['instance']
  38. def load(self, command, directories, args):
  39. class IniContainer(object):
  40. def __init__(self):
  41. self.plugins = []
  42. self.actions = []
  43. self.hash = {}
  44. def load_recursively(inicontainer, directory):
  45. active_plugins = []
  46. pattern = re.compile(r'.*[.]ini$', flags=re.IGNORECASE)
  47. dirList = os.listdir(directory)
  48. for fname in dirList:
  49. fname = os.path.join(directory, fname)
  50. if os.path.isdir(fname):
  51. active_plugins += load_recursively(inicontainer, fname)
  52. elif re.match(pattern, fname):
  53. config = ConfigParser.ConfigParser()
  54. config.read(fname)
  55. item = {'package': config.get('Plugin', 'package'),
  56. 'module': config.get('Plugin', 'module'),
  57. 'class': config.get('Plugin', 'class'),
  58. 'version': config.get('Plugin', 'version'),
  59. 'depends': config.get('Plugin', 'depends'),
  60. 'actions': config.get('Plugin', 'actions'),
  61. 'enabled': config.getboolean('Plugin', 'enabled'),
  62. 'instance': None}
  63. if item['enabled']:
  64. item['actions'] = item['actions'].split(',')
  65. for (ind, action) in enumerate(item['actions']):
  66. action = action.strip()
  67. item['actions'][ind] = action
  68. if action not in inicontainer.actions + ['*', 'None', 'none', 'False', 'false']:
  69. inicontainer.actions.append(action)
  70. if action == '*' or action == command:
  71. active_plugins.append(item['package'] + '.' + item['module'])
  72. inicontainer.plugins.append(item)
  73. inicontainer.hash[item['package'] + '.' + item['module']] = item
  74. return active_plugins
  75. def list_dependants_recursively(inicontainer, required_plugin_name):
  76. assert required_plugin_name in inicontainer.hash.keys(), \
  77. "depends section requires unknown plugin: " + required_plugin_name
  78. item = inicontainer.hash[required_plugin_name]
  79. if item['depends'] in ('None', 'none', 'False', 'false'):
  80. return []
  81. result = []
  82. for child in item['depends'].split(','):
  83. child = child.strip()
  84. result += list_dependants_recursively(inicontainer, child)
  85. result.append(child)
  86. return result
  87. # configure python path for loading
  88. std_ext_dir = os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], 'ext')
  89. std_ext_priority_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  90. for each in [std_ext_dir] + directories:
  91. sys.path.append(each)
  92. inicontainer = IniContainer()
  93. # load available plugin ini files
  94. required_plugins = []
  95. for each in ([std_ext_priority_dir, std_ext_dir] + directories):
  96. required_plugins += load_recursively(inicontainer, each)
  97. # upgrade the list of required plugins
  98. required_and_dependant_plugins = []
  99. for name in required_plugins:
  100. for each in list_dependants_recursively(inicontainer, name):
  101. if each not in required_and_dependant_plugins:
  102. required_and_dependant_plugins.append(each)
  103. required_and_dependant_plugins.append(name)
  104. # load
  105. for plugin_name in required_and_dependant_plugins:
  106. item = inicontainer.hash[plugin_name]
  107. plugin = __import__(item['package'], globals(), locals(), [item['module']], -1)
  108. module_attr = plugin.__getattribute__(item['module'])
  109. class_attr = module_attr.__getattribute__(item['class'])
  110. item['instance'] = class_attr.__new__(class_attr)
  111. item['instance'].__init__()
  112. item['instance'].set_name(item['package'] + "." + item['module'])
  113. item['instance'].set_version(item['version'])
  114. item['instance'].set_plugin_loader(self)
  115. self.plugins.append(item)
  116. self.hash[plugin_name] = item
  117. optparser =mpp.cmdparser.MultiOptionParser(
  118. usage="Usage: %prog {command} [options] -- [path 1] ... [path N]".format(command=command))
  119. if command not in inicontainer.actions:
  120. optparser.error("Unknown action: {action}".format(action={command}))
  121. for item in self.iterate_plugins():
  122. if (isinstance(item, mpp.api.IConfigurable)):
  123. item.declare_configuration(optparser)
  124. (options, args) = optparser.parse_args(args)
  125. for item in self.iterate_plugins():
  126. if (isinstance(item, mpp.api.IConfigurable)):
  127. item.configure(options)
  128. for item in self.iterate_plugins():
  129. item.initialize()
  130. return args
  131. def unload(self):
  132. for item in self.iterate_plugins(is_reversed = True):
  133. item.terminate()
  134. def run(self, args):
  135. exit_code = 0
  136. for item in self.iterate_plugins():
  137. if (isinstance(item, mpp.api.IRunable)):
  138. exit_code += item.run(args)
  139. return exit_code
  140. def __repr__(self):
  141. result = object.__repr__(self) + ' with loaded:'
  142. for item in self.iterate_plugins():
  143. result += '\n\t' + item.__repr__()
  144. if isinstance(item, mpp.api.Parent):
  145. result += ' with subscribed:'
  146. for child in item.iterate_children():
  147. result += '\n\t\t' + child.__repr__()
  148. return result