loader.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. self.action = None
  30. def get_action(self):
  31. return self.action
  32. def get_plugin(self, name):
  33. return self.hash[name]['instance']
  34. def iterate_plugins(self, is_reversed = False):
  35. if is_reversed == False:
  36. for item in self.plugins:
  37. yield item['instance']
  38. else:
  39. for item in reversed(self.plugins):
  40. yield item['instance']
  41. def load(self, command, directories, args):
  42. class IniContainer(object):
  43. def __init__(self):
  44. self.plugins = []
  45. self.actions = []
  46. self.hash = {}
  47. def load_recursively(inicontainer, directory):
  48. active_plugins = []
  49. pattern = re.compile(r'.*[.]ini$', flags=re.IGNORECASE)
  50. dirList = os.listdir(directory)
  51. for fname in dirList:
  52. fname = os.path.join(directory, fname)
  53. if os.path.isdir(fname):
  54. active_plugins += load_recursively(inicontainer, fname)
  55. elif re.match(pattern, fname):
  56. config = ConfigParser.ConfigParser()
  57. config.read(fname)
  58. item = {'package': config.get('Plugin', 'package'),
  59. 'module': config.get('Plugin', 'module'),
  60. 'class': config.get('Plugin', 'class'),
  61. 'version': config.get('Plugin', 'version'),
  62. 'depends': config.get('Plugin', 'depends'),
  63. 'actions': config.get('Plugin', 'actions'),
  64. 'enabled': config.getboolean('Plugin', 'enabled'),
  65. 'instance': None}
  66. if item['enabled']:
  67. item['actions'] = item['actions'].split(',')
  68. for (ind, action) in enumerate(item['actions']):
  69. action = action.strip()
  70. item['actions'][ind] = action
  71. if action not in inicontainer.actions + ['*', 'None', 'none', 'False', 'false']:
  72. inicontainer.actions.append(action)
  73. if action == '*' or action == command:
  74. active_plugins.append(item['package'] + '.' + item['module'])
  75. inicontainer.plugins.append(item)
  76. inicontainer.hash[item['package'] + '.' + item['module']] = item
  77. return active_plugins
  78. def list_dependants_recursively(inicontainer, required_plugin_name):
  79. assert required_plugin_name in inicontainer.hash.keys(), \
  80. "depends section requires unknown plugin: " + required_plugin_name
  81. item = inicontainer.hash[required_plugin_name]
  82. if item['depends'] in ('None', 'none', 'False', 'false'):
  83. return []
  84. result = []
  85. for child in item['depends'].split(','):
  86. child = child.strip()
  87. result += list_dependants_recursively(inicontainer, child)
  88. result.append(child)
  89. return result
  90. # configure python path for loading
  91. std_ext_dir = os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], 'ext')
  92. std_ext_priority_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  93. for each in [std_ext_dir] + directories:
  94. sys.path.append(each)
  95. inicontainer = IniContainer()
  96. # load available plugin ini files
  97. required_plugins = []
  98. for each in ([std_ext_priority_dir, std_ext_dir] + directories):
  99. required_plugins += load_recursively(inicontainer, each)
  100. # upgrade the list of required plugins
  101. required_and_dependant_plugins = []
  102. for name in required_plugins:
  103. for each in list_dependants_recursively(inicontainer, name):
  104. if each not in required_and_dependant_plugins:
  105. required_and_dependant_plugins.append(each)
  106. required_and_dependant_plugins.append(name)
  107. # load
  108. for plugin_name in required_and_dependant_plugins:
  109. item = inicontainer.hash[plugin_name]
  110. plugin = __import__(item['package'], globals(), locals(), [item['module']], -1)
  111. module_attr = plugin.__getattribute__(item['module'])
  112. class_attr = module_attr.__getattribute__(item['class'])
  113. item['instance'] = class_attr.__new__(class_attr)
  114. item['instance'].__init__()
  115. item['instance'].set_name(item['package'] + "." + item['module'])
  116. item['instance'].set_version(item['version'])
  117. item['instance'].set_plugin_loader(self)
  118. self.plugins.append(item)
  119. self.hash[plugin_name] = item
  120. optparser = mpp.cmdparser.MultiOptionParser(
  121. usage = "Usage: python %prog --help\n" +
  122. " python %prog <action> --help\n" +
  123. " python %prog <action> [options] -- [path 1] ... [path N]\n" +
  124. "\n" +
  125. "Actions: \n " + "\n ".join(inicontainer.actions))
  126. if command in ['--help', '--h', '-h']:
  127. optparser.print_help()
  128. exit(0)
  129. if command.strip() == "":
  130. optparser.error("Mandatory action argument required")
  131. if command not in inicontainer.actions:
  132. optparser.error("Unknown action: {action}".format(action=command))
  133. self.action = command
  134. optparser =mpp.cmdparser.MultiOptionParser(
  135. usage="Usage: python %prog --help\n"
  136. " python %prog {command} --help\n"
  137. " python %prog {command} [options] -- [path 1] ... [path N]".format(command=command))
  138. for item in self.iterate_plugins():
  139. if (isinstance(item, mpp.api.IConfigurable)):
  140. item.declare_configuration(optparser)
  141. (options, args) = optparser.parse_args(args)
  142. for item in self.iterate_plugins():
  143. if (isinstance(item, mpp.api.IConfigurable)):
  144. item.configure(options)
  145. for item in self.iterate_plugins():
  146. item.initialize()
  147. return args
  148. def unload(self):
  149. for item in self.iterate_plugins(is_reversed = True):
  150. item.terminate()
  151. def run(self, args):
  152. exit_code = 0
  153. for item in self.iterate_plugins():
  154. if (isinstance(item, mpp.api.IRunable)):
  155. exit_code += item.run(args)
  156. return exit_code
  157. def __repr__(self):
  158. result = object.__repr__(self) + ' with loaded:'
  159. for item in self.iterate_plugins():
  160. result += '\n\t' + item.__repr__()
  161. if isinstance(item, mpp.api.Parent):
  162. result += ' with subscribed:'
  163. for child in item.iterate_children():
  164. result += '\n\t\t' + child.__repr__()
  165. return result