2 """The plugin module provides optional submodules that add new Hooke
5 All of the science happens in here.
11 from ..config import Setting
12 from ..util.graph import Node, Graph
16 # ('curvetools', True),
19 # ('flatfilts-rolf', True),
20 # ('flatfilts', True),
21 # ('generalclamp', True),
22 # ('generaltccd', True),
23 # ('generalvclamp', True),
26 # ('massanalysis', True),
27 # ('multidistance', True),
30 # ('procplots', True),
32 # ('showconvoluted', True),
33 # ('superimpose', True),
37 """List of plugin modules and whether they should be included by
38 default. TODO: autodiscovery
41 # Plugins and settings
44 """The pluggable collection of Hooke commands.
46 Fulfills the same role for Hooke that a software package does for
51 def dependencies(self):
52 """Return a list of Plugins we require."""
55 def default_settings(self):
56 """Return a list of hooke.config.Settings() for any
57 configurable module settings."""
61 """Return a list of Commands provided."""
65 """(name,instance) :class:`dict` of all possible :class:`Plugin`\s.
69 for plugin_modname,value in PLUGIN_MODULES:
70 this_mod = __import__(__name__, fromlist=[plugin_modname])
71 plugin_mod = getattr(this_mod, plugin_modname)
72 for objname in dir(plugin_mod):
73 obj = getattr(plugin_mod, objname)
74 if type(obj) == Plugin:
75 obj.module_name = plugin_modname
78 PLUGIN_GRAPH = Graph([Node([PLUGINS[name] for name in p.dependencies()])
79 for p in PLUGINS.values()])
80 PLUGIN_GRAPH.topological_sort()
83 def default_settings(self):
85 'plugins', help='Enable/disable default plugins.')]
86 for pnode in PLUGIN_GRAPH:
87 settings.append(Setting(p.name, str(PLUGIN_MODULES[p.module_name][1])))
88 for pnode in PLUGIN_GRAPH:
90 settings.extend(plugin.default_settings())
94 # Commands and arguments
96 class CommandExit (Exception):
98 return self.__class__.__name__
100 class Success (CommandExit):
103 class Failure (CommandExit):
107 class Argument (object):
108 """Structured user input for :class:`Command`\s.
110 TODO: ranges for `count`?
112 def __init__(self, name, type='string', metavar=None, default=None,
113 optional=True, count=1, completion_callback=None,
114 callback=None, aliases=None, help=''):
118 metavar = name.upper()
119 self.metavar = metavar
120 self.default = default
121 self.optional = optional
123 self.completion_callback = completion_callback
124 self.callback = callback
127 self.aliases = aliases
131 return '<%s %s>' % (self.__class__.__name__, self.name)
134 return self.__str__()
137 parts = ['%s ' % self.name]
138 if self.metavar != None:
139 parts.append('%s ' % self.metavar)
140 parts.extend(['(%s) ' % self.type, self._help])
141 return ''.join(parts)
143 def validate(self, value):
144 """If `value` is not appropriate, raise `ValueError`.
146 pass # TODO: validation
148 # TODO: type conversion
150 # TODO: type extensions?
154 class StoreValue (object):
155 def __init__(self, value):
157 def __call__(self, command, argument, fragment=None):
160 class NullQueue (queue.Queue):
161 """The :class:`queue.Queue` equivalent of `/dev/null`.
163 This is a bottomless pit. Items go in, but never come out.
165 def get(self, block=True, timeout=None):
166 """Raise queue.Empty.
168 There's really no need to override the base Queue.get, but I
169 want to know if someone tries to read from a NullQueue. With
170 the default implementation they would just block silently
175 def put(self, item, block=True, timeout=None):
176 """Dump an item into the void.
178 Block and timeout are meaningless, because there is always a
179 free slot available in a bottomless pit.
183 class PrintQueue (NullQueue):
184 """Debugging :class:`NullQueue` that prints items before dropping
187 def put(self, item, block=True, timeout=None):
188 """Print `item` and then dump it into the void.
190 print 'ITEM:\n%s' % item
192 class Command (object):
193 """One-line command description here.
195 >>> c = Command(name='test', help='An example Command.')
196 >>> status = c.run(NullQueue(), PrintQueue(), help=True)
201 help HELP (bool) Print a help message.
207 def __init__(self, name, arguments=[], aliases=None, help=''):
210 Argument(name='help', type='bool', default=False, count=1,
211 callback=StoreValue(True), help='Print a help message.'),
215 self.aliases = aliases
218 def run(self, inqueue=None, outqueue=None, **kwargs):
219 """`Normalize inputs and handle <Argument help> before punting
223 inqueue = NullQueue()
225 outqueue = NullQueue()
227 params = self.handle_arguments(inqueue, outqueue, kwargs)
228 if params['help'] == True:
229 outqueue.put(self.help())
231 self._run(inqueue, outqueue, params)
232 except CommandExit, e:
233 if isinstance(e, Failure):
234 outqueue.put(e.message)
240 def _run(self, inqueue, outqueue, params):
241 """This is where the command-specific magic will happen.
245 def handle_arguments(self, inqueue, outqueue, params):
246 """Normalize and validate input parameters (:class:`Argument` values).
248 for argument in self.arguments:
249 names = [argument.name] + argument.aliases
250 settings = [(name,v) for name,v in params.items() if name in names]
251 if len(settings) == 0:
252 if argument.optional == True or argument.count == 0:
253 settings = [(argument.name, argument.default)]
255 raise Failure('Required argument %s not set.'
257 if len(settings) > 1:
258 raise Failure('Multiple settings for %s:\n %s'
260 '\n '.join(['%s: %s' % (name,value)
261 for name,value in sorted(settings)])))
262 name,value = settings[0]
263 if name != argument.name:
265 params[argument.name] = value
266 if argument.callback != None:
267 value = argument.callback(self, argument, value)
268 params[argument.name] = value
269 argument.validate(value)
272 def help(self, *args):
273 name_part = 'Command: %s' % self.name
274 if len(self.aliases) > 0:
275 name_part += ' (%s)' % ', '.join(self.aliases)
276 argument_part = ['Arguments:'] + [a.help() for a in self.arguments]
277 argument_part = '\n'.join(argument_part)
278 help_part = self._help
279 return '\n\n'.join([name_part, argument_part, help_part])