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):
49 self.setting_section = '%s plugin' % self.name
52 def dependencies(self):
53 """Return a list of :class:`Plugin`\s we require."""
56 def default_settings(self):
57 """Return a list of :class:`hooke.config.Setting`\s for any
58 configurable plugin settings.
60 The suggested section setting is::
62 Setting(section=self.setting_section, help=self.__doc__)
67 """Return a list of :class:`Commands` provided."""
72 # Commands and arguments
74 class CommandExit (Exception):
76 return self.__class__.__name__
78 class Success (CommandExit):
81 class Failure (CommandExit):
84 class Command (object):
85 """One-line command description here.
87 >>> c = Command(name='test', help='An example Command.')
88 >>> status = c.run(NullQueue(), PrintQueue(), help=True)
93 help HELP (bool) Print a help message.
99 def __init__(self, name, aliases=None, arguments=[], help=''):
103 self.aliases = aliases
105 Argument(name='help', type='bool', default=False, count=1,
106 callback=StoreValue(True), help='Print a help message.'),
110 def run(self, inqueue=None, outqueue=None, **kwargs):
111 """`Normalize inputs and handle <Argument help> before punting
115 inqueue = NullQueue()
117 outqueue = NullQueue()
119 params = self.handle_arguments(inqueue, outqueue, kwargs)
120 if params['help'] == True:
121 outqueue.put(self.help())
123 self._run(inqueue, outqueue, params)
124 except CommandExit, e:
125 if isinstance(e, Failure):
126 outqueue.put(e.message)
132 def _run(self, inqueue, outqueue, params):
133 """This is where the command-specific magic will happen.
137 def handle_arguments(self, inqueue, outqueue, params):
138 """Normalize and validate input parameters (:class:`Argument` values).
140 for argument in self.arguments:
141 names = [argument.name] + argument.aliases
142 settings = [(name,v) for name,v in params.items() if name in names]
143 if len(settings) == 0:
144 if argument.optional == True or argument.count == 0:
145 settings = [(argument.name, argument.default)]
147 raise Failure('Required argument %s not set.'
149 if len(settings) > 1:
150 raise Failure('Multiple settings for %s:\n %s'
152 '\n '.join(['%s: %s' % (name,value)
153 for name,value in sorted(settings)])))
154 name,value = settings[0]
155 if name != argument.name:
157 params[argument.name] = value
158 if argument.callback != None:
159 value = argument.callback(self, argument, value)
160 params[argument.name] = value
161 argument.validate(value)
164 def help(self, *args):
165 name_part = 'Command: %s' % self.name
166 if len(self.aliases) > 0:
167 name_part += ' (%s)' % ', '.join(self.aliases)
168 argument_part = ['Arguments:'] + [a.help() for a in self.arguments]
169 argument_part = '\n'.join(argument_part)
170 help_part = self._help
171 return '\n\n'.join([name_part, argument_part, help_part])
173 class Argument (object):
174 """Structured user input for :class:`Command`\s.
176 TODO: ranges for `count`?
178 def __init__(self, name, aliases=None, type='string', metavar=None,
179 default=None, optional=True, count=1,
180 completion_callback=None, callback=None, help=''):
184 self.aliases = aliases
187 metavar = type.upper()
188 self.metavar = metavar
189 self.default = default
190 self.optional = optional
192 self.completion_callback = completion_callback
193 self.callback = callback
197 return '<%s %s>' % (self.__class__.__name__, self.name)
200 return self.__str__()
203 parts = ['%s ' % self.name]
204 if self.metavar != None:
205 parts.append('%s ' % self.metavar)
206 parts.extend(['(%s) ' % self.type, self._help])
207 return ''.join(parts)
209 def validate(self, value):
210 """If `value` is not appropriate, raise `ValueError`.
212 pass # TODO: validation
214 # TODO: type conversion
216 # TODO: type extensions?
220 class StoreValue (object):
221 def __init__(self, value):
223 def __call__(self, command, argument, fragment=None):
226 class NullQueue (queue.Queue):
227 """The :class:`queue.Queue` equivalent of `/dev/null`.
229 This is a bottomless pit. Items go in, but never come out.
231 def get(self, block=True, timeout=None):
232 """Raise queue.Empty.
234 There's really no need to override the base Queue.get, but I
235 want to know if someone tries to read from a NullQueue. With
236 the default implementation they would just block silently
241 def put(self, item, block=True, timeout=None):
242 """Dump an item into the void.
244 Block and timeout are meaningless, because there is always a
245 free slot available in a bottomless pit.
249 class PrintQueue (NullQueue):
250 """Debugging :class:`NullQueue` that prints items before dropping
253 def put(self, item, block=True, timeout=None):
254 """Print `item` and then dump it into the void.
256 print 'ITEM:\n%s' % item
259 # Construct plugin dependency graph and load default plugins.
262 """(name,instance) :class:`dict` of all possible :class:`Plugin`\s.
265 for plugin_modname,default_include in PLUGIN_MODULES:
266 assert len([mod_name for mod_name,di in PLUGIN_MODULES]) == 1, \
267 'Multiple %s entries in PLUGIN_MODULES' % mod_name
268 this_mod = __import__(__name__, fromlist=[plugin_modname])
269 plugin_mod = getattr(this_mod, plugin_modname)
270 for objname in dir(plugin_mod):
271 obj = getattr(plugin_mod, objname)
273 subclass = issubclass(obj, Plugin)
276 if subclass == True and obj != Plugin:
278 if p.name != plugin_modname:
279 raise Exception('Plugin name %s does not match module name %s'
280 % (p.name, plugin_modname))
283 PLUGIN_GRAPH = Graph([Node([PLUGINS[name] for name in p.dependencies()],
285 for p in PLUGINS.values()])
286 PLUGIN_GRAPH.topological_sort()
289 def default_settings():
291 'plugins', help='Enable/disable default plugins.')]
292 for pnode in PLUGIN_GRAPH:
294 default_include = [di for mod_name,di in PLUGIN_MODULES
295 if mod_name == plugin.name][0]
296 help = 'Commands: ' + ', '.join([c.name for c in p.commands()])
297 settings.append(Setting(
300 value=str(default_include),
303 for pnode in PLUGIN_GRAPH:
305 settings.extend(plugin.default_settings())