1 """The plugin module provides optional submodules that add new Hooke
4 All of the science happens in here.
9 from ..config import Setting
10 from ..util.graph import Node, Graph
14 # ('curvetools', True),
17 # ('flatfilts-rolf', True),
18 # ('flatfilts', True),
19 # ('generalclamp', True),
20 # ('generaltccd', True),
21 # ('generalvclamp', True),
24 # ('massanalysis', True),
25 # ('multidistance', True),
28 # ('procplots', True),
30 # ('showconvoluted', True),
31 # ('superimpose', True),
35 """List of plugin modules and whether they should be included by
36 default. TODO: autodiscovery
39 # Plugins and settings
41 class Plugin (object):
42 """The pluggable collection of Hooke commands.
44 Fulfills the same role for Hooke that a software package does for
47 def __init__(self, name):
50 def dependencies(self):
51 """Return a list of :class:`Plugin`\s we require."""
54 def default_settings(self):
55 """Return a list of :class:`hooke.config.Setting`\s for any
56 configurable plugin settings.
58 The suggested section setting is::
60 Setting(section='%s plugin' % self.name, help=self.__doc__)
65 """Return a list of :class:`Commands` provided."""
70 # Commands and arguments
72 class CommandExit (Exception):
74 return self.__class__.__name__
76 class Success (CommandExit):
79 class Failure (CommandExit):
82 class Command (object):
83 """One-line command description here.
85 >>> c = Command(name='test', help='An example Command.')
86 >>> status = c.run(NullQueue(), PrintQueue(), help=True)
91 help HELP (bool) Print a help message.
97 def __init__(self, name, aliases=None, arguments=[], help=''):
101 self.aliases = aliases
103 Argument(name='help', type='bool', default=False, count=1,
104 callback=StoreValue(True), help='Print a help message.'),
108 def run(self, inqueue=None, outqueue=None, **kwargs):
109 """`Normalize inputs and handle <Argument help> before punting
113 inqueue = NullQueue()
115 outqueue = NullQueue()
117 params = self.handle_arguments(inqueue, outqueue, kwargs)
118 if params['help'] == True:
119 outqueue.put(self.help())
121 self._run(inqueue, outqueue, params)
122 except CommandExit, e:
123 if isinstance(e, Failure):
124 outqueue.put(e.message)
130 def _run(self, inqueue, outqueue, params):
131 """This is where the command-specific magic will happen.
135 def handle_arguments(self, inqueue, outqueue, params):
136 """Normalize and validate input parameters (:class:`Argument` values).
138 for argument in self.arguments:
139 names = [argument.name] + argument.aliases
140 settings = [(name,v) for name,v in params.items() if name in names]
141 if len(settings) == 0:
142 if argument.optional == True or argument.count == 0:
143 settings = [(argument.name, argument.default)]
145 raise Failure('Required argument %s not set.'
147 if len(settings) > 1:
148 raise Failure('Multiple settings for %s:\n %s'
150 '\n '.join(['%s: %s' % (name,value)
151 for name,value in sorted(settings)])))
152 name,value = settings[0]
153 if name != argument.name:
155 params[argument.name] = value
156 if argument.callback != None:
157 value = argument.callback(self, argument, value)
158 params[argument.name] = value
159 argument.validate(value)
162 def help(self, *args):
163 name_part = 'Command: %s' % self.name
164 if len(self.aliases) > 0:
165 name_part += ' (%s)' % ', '.join(self.aliases)
166 argument_part = ['Arguments:'] + [a.help() for a in self.arguments]
167 argument_part = '\n'.join(argument_part)
168 help_part = self._help
169 return '\n\n'.join([name_part, argument_part, help_part])
171 class Argument (object):
172 """Structured user input for :class:`Command`\s.
174 TODO: ranges for `count`?
176 def __init__(self, name, aliases=None, type='string', metavar=None,
177 default=None, optional=True, count=1,
178 completion_callback=None, callback=None, help=''):
182 self.aliases = aliases
185 metavar = type.upper()
186 self.metavar = metavar
187 self.default = default
188 self.optional = optional
190 self.completion_callback = completion_callback
191 self.callback = callback
195 return '<%s %s>' % (self.__class__.__name__, self.name)
198 return self.__str__()
201 parts = ['%s ' % self.name]
202 if self.metavar != None:
203 parts.append('%s ' % self.metavar)
204 parts.extend(['(%s) ' % self.type, self._help])
205 return ''.join(parts)
207 def validate(self, value):
208 """If `value` is not appropriate, raise `ValueError`.
210 pass # TODO: validation
212 # TODO: type conversion
214 # TODO: type extensions?
218 class StoreValue (object):
219 def __init__(self, value):
221 def __call__(self, command, argument, fragment=None):
224 class NullQueue (queue.Queue):
225 """The :class:`queue.Queue` equivalent of `/dev/null`.
227 This is a bottomless pit. Items go in, but never come out.
229 def get(self, block=True, timeout=None):
230 """Raise queue.Empty.
232 There's really no need to override the base Queue.get, but I
233 want to know if someone tries to read from a NullQueue. With
234 the default implementation they would just block silently
239 def put(self, item, block=True, timeout=None):
240 """Dump an item into the void.
242 Block and timeout are meaningless, because there is always a
243 free slot available in a bottomless pit.
247 class PrintQueue (NullQueue):
248 """Debugging :class:`NullQueue` that prints items before dropping
251 def put(self, item, block=True, timeout=None):
252 """Print `item` and then dump it into the void.
254 print 'ITEM:\n%s' % item
257 # Construct plugin dependency graph and load default plugins.
260 """(name,instance) :class:`dict` of all possible :class:`Plugin`\s.
263 for plugin_modname,default_include in PLUGIN_MODULES:
264 assert len([mod_name for mod_name,di in PLUGIN_MODULES]) == 1, \
265 'Multiple %s entries in PLUGIN_MODULES' % mod_name
266 this_mod = __import__(__name__, fromlist=[plugin_modname])
267 plugin_mod = getattr(this_mod, plugin_modname)
268 for objname in dir(plugin_mod):
269 obj = getattr(plugin_mod, objname)
271 subclass = issubclass(obj, Plugin)
274 if subclass == True and obj != Plugin:
276 if p.name != plugin_modname:
277 raise Exception('Plugin name %s does not match module name %s'
278 % (p.name, plugin_modname))
281 PLUGIN_GRAPH = Graph([Node([PLUGINS[name] for name in p.dependencies()],
283 for p in PLUGINS.values()])
284 PLUGIN_GRAPH.topological_sort()
287 def default_settings():
289 'plugins', help='Enable/disable default plugins.')]
290 for pnode in PLUGIN_GRAPH:
292 default_include = [di for mod_name,di in PLUGIN_MODULES
293 if mod_name == plugin.name][0]
294 help = 'Commands: ' + ', '.join([c.name for c in p.commands()])
295 settings.append(Setting(
298 value=str(default_include),
301 for pnode in PLUGIN_GRAPH:
303 settings.extend(plugin.default_settings())