1 """The plugin module provides optional submodules that add new Hooke
4 All of the science happens in here.
10 from ..config import Setting
11 from ..util.graph import Node, Graph
15 # ('curvetools', True),
18 # ('flatfilts-rolf', True),
19 # ('flatfilts', True),
20 # ('generalclamp', True),
21 # ('generaltccd', True),
22 # ('generalvclamp', True),
25 # ('massanalysis', True),
26 # ('multidistance', True),
29 # ('procplots', True),
31 # ('showconvoluted', True),
32 # ('superimpose', True),
36 """List of plugin modules and whether they should be included by
37 default. TODO: autodiscovery
40 # Plugins and settings
43 """The pluggable collection of Hooke commands.
45 Fulfills the same role for Hooke that a software package does for
48 def __init__(self, name):
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):
106 class Command (object):
107 """One-line command description here.
109 >>> c = Command(name='test', help='An example Command.')
110 >>> status = c.run(NullQueue(), PrintQueue(), help=True)
115 help HELP (bool) Print a help message.
121 def __init__(self, name, aliases=None, arguments=[], help=''):
125 self.aliases = aliases
127 Argument(name='help', type='bool', default=False, count=1,
128 callback=StoreValue(True), help='Print a help message.'),
132 def run(self, inqueue=None, outqueue=None, **kwargs):
133 """`Normalize inputs and handle <Argument help> before punting
137 inqueue = NullQueue()
139 outqueue = NullQueue()
141 params = self.handle_arguments(inqueue, outqueue, kwargs)
142 if params['help'] == True:
143 outqueue.put(self.help())
145 self._run(inqueue, outqueue, params)
146 except CommandExit, e:
147 if isinstance(e, Failure):
148 outqueue.put(e.message)
154 def _run(self, inqueue, outqueue, params):
155 """This is where the command-specific magic will happen.
159 def handle_arguments(self, inqueue, outqueue, params):
160 """Normalize and validate input parameters (:class:`Argument` values).
162 for argument in self.arguments:
163 names = [argument.name] + argument.aliases
164 settings = [(name,v) for name,v in params.items() if name in names]
165 if len(settings) == 0:
166 if argument.optional == True or argument.count == 0:
167 settings = [(argument.name, argument.default)]
169 raise Failure('Required argument %s not set.'
171 if len(settings) > 1:
172 raise Failure('Multiple settings for %s:\n %s'
174 '\n '.join(['%s: %s' % (name,value)
175 for name,value in sorted(settings)])))
176 name,value = settings[0]
177 if name != argument.name:
179 params[argument.name] = value
180 if argument.callback != None:
181 value = argument.callback(self, argument, value)
182 params[argument.name] = value
183 argument.validate(value)
186 def help(self, *args):
187 name_part = 'Command: %s' % self.name
188 if len(self.aliases) > 0:
189 name_part += ' (%s)' % ', '.join(self.aliases)
190 argument_part = ['Arguments:'] + [a.help() for a in self.arguments]
191 argument_part = '\n'.join(argument_part)
192 help_part = self._help
193 return '\n\n'.join([name_part, argument_part, help_part])
195 class Argument (object):
196 """Structured user input for :class:`Command`\s.
198 TODO: ranges for `count`?
200 def __init__(self, name, aliases=None, type='string', metavar=None,
201 default=None, optional=True, count=1,
202 completion_callback=None, callback=None, help=''):
206 self.aliases = aliases
209 metavar = type.upper()
210 self.metavar = metavar
211 self.default = default
212 self.optional = optional
214 self.completion_callback = completion_callback
215 self.callback = callback
219 return '<%s %s>' % (self.__class__.__name__, self.name)
222 return self.__str__()
225 parts = ['%s ' % self.name]
226 if self.metavar != None:
227 parts.append('%s ' % self.metavar)
228 parts.extend(['(%s) ' % self.type, self._help])
229 return ''.join(parts)
231 def validate(self, value):
232 """If `value` is not appropriate, raise `ValueError`.
234 pass # TODO: validation
236 # TODO: type conversion
238 # TODO: type extensions?
242 class StoreValue (object):
243 def __init__(self, value):
245 def __call__(self, command, argument, fragment=None):
248 class NullQueue (queue.Queue):
249 """The :class:`queue.Queue` equivalent of `/dev/null`.
251 This is a bottomless pit. Items go in, but never come out.
253 def get(self, block=True, timeout=None):
254 """Raise queue.Empty.
256 There's really no need to override the base Queue.get, but I
257 want to know if someone tries to read from a NullQueue. With
258 the default implementation they would just block silently
263 def put(self, item, block=True, timeout=None):
264 """Dump an item into the void.
266 Block and timeout are meaningless, because there is always a
267 free slot available in a bottomless pit.
271 class PrintQueue (NullQueue):
272 """Debugging :class:`NullQueue` that prints items before dropping
275 def put(self, item, block=True, timeout=None):
276 """Print `item` and then dump it into the void.
278 print 'ITEM:\n%s' % item