Rework hooke.driver and hooke.driver.tutorial along the lines of hooke.plugin.
[hooke.git] / hooke / plugin / __init__.py
1 """The plugin module provides optional submodules that add new Hooke
2 commands.
3
4 All of the science happens in here.
5 """
6
7 import Queue as queue
8
9 from ..config import Setting
10 from ..util.graph import Node, Graph
11
12 PLUGIN_MODULES = [
13 #    ('autopeak', True),
14 #    ('curvetools', True),
15     ('cut', True),
16 #    ('fit', True),
17 #    ('flatfilts-rolf', True),
18 #    ('flatfilts', True),
19 #    ('generalclamp', True),
20 #    ('generaltccd', True),
21 #    ('generalvclamp', True),
22 #    ('jumpstat', True),
23 #    ('macro', True),
24 #    ('massanalysis', True),
25 #    ('multidistance', True),
26 #    ('multifit', True),
27 #    ('pcluster', True),
28 #    ('procplots', True),
29 #    ('review', True),
30 #    ('showconvoluted', True),
31 #    ('superimpose', True),
32 #    ('tutorial', True),
33 #    ('viewer', True),
34     ]
35 """List of plugin modules and whether they should be included by
36 default.  TODO: autodiscovery
37 """
38
39 # Plugins and settings
40
41 class Plugin (object):
42     """The pluggable collection of Hooke commands.
43
44     Fulfills the same role for Hooke that a software package does for
45     an operating system.
46     """
47     def __init__(self, name):
48         self.name = name
49
50     def dependencies(self):
51         """Return a list of :class:`Plugin`\s we require."""
52         return []
53
54     def default_settings(self):
55         """Return a list of :class:`hooke.config.Setting`\s for any
56         configurable plugin settings.
57
58         The suggested section setting is::
59
60             Setting(section='%s plugin' % self.name, help=self.__doc__)
61         """
62         return []
63
64     def commands(self):
65         """Return a list of :class:`Commands` provided."""
66         return []
67
68
69
70 # Commands and arguments
71
72 class CommandExit (Exception):
73     def __str__(self):
74         return self.__class__.__name__
75
76 class Success (CommandExit):
77     pass
78
79 class Failure (CommandExit):
80     pass
81
82 class Command (object):
83     """One-line command description here.
84
85     >>> c = Command(name='test', help='An example Command.')
86     >>> status = c.run(NullQueue(), PrintQueue(), help=True)
87     ITEM:
88     Command: test
89     <BLANKLINE>
90     Arguments:
91     help HELP (bool) Print a help message.
92     <BLANKLINE>
93     An example Command.
94     ITEM:
95     Success
96     """
97     def __init__(self, name, aliases=None, arguments=[], help=''):
98         self.name = name
99         if aliases == None:
100             aliases = []
101         self.aliases = aliases
102         self.arguments = [
103             Argument(name='help', type='bool', default=False, count=1,
104                      callback=StoreValue(True), help='Print a help message.'),
105             ] + arguments
106         self._help = help
107
108     def run(self, inqueue=None, outqueue=None, **kwargs):
109         """`Normalize inputs and handle <Argument help> before punting
110         to :meth:`_run`.
111         """
112         if inqueue == None:
113             inqueue = NullQueue()
114         if outqueue == None:
115             outqueue = NullQueue()
116         try:
117             params = self.handle_arguments(inqueue, outqueue, kwargs)
118             if params['help'] == True:
119                 outqueue.put(self.help())
120                 raise(Success())
121             self._run(inqueue, outqueue, params)
122         except CommandExit, e:
123             if isinstance(e, Failure):
124                 outqueue.put(e.message)
125                 outqueue.put(e)
126                 return 1
127         outqueue.put(e)
128         return 0
129
130     def _run(self, inqueue, outqueue, params):
131         """This is where the command-specific magic will happen.
132         """
133         pass
134
135     def handle_arguments(self, inqueue, outqueue, params):
136         """Normalize and validate input parameters (:class:`Argument` values).
137         """
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)]
144                 else:
145                     raise Failure('Required argument %s not set.'
146                                   % argument.name)
147             if len(settings) > 1:
148                 raise Failure('Multiple settings for %s:\n  %s'
149                     % (argument.name,
150                        '\n  '.join(['%s: %s' % (name,value)
151                                     for name,value in sorted(settings)])))
152             name,value = settings[0]
153             if name != argument.name:
154                 params.remove(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)
160         return params
161
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])
170
171 class Argument (object):
172     """Structured user input for :class:`Command`\s.
173     
174     TODO: ranges for `count`?
175     """
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=''):
179         self.name = name
180         if aliases == None:
181             aliases = []
182         self.aliases = aliases
183         self.type = type
184         if metavar == None:
185             metavar = type.upper()
186         self.metavar = metavar
187         self.default = default
188         self.optional = optional
189         self.count = count
190         self.completion_callback = completion_callback
191         self.callback = callback
192         self._help = help
193
194     def __str__(self):
195         return '<%s %s>' % (self.__class__.__name__, self.name)
196
197     def __repr__(self):
198         return self.__str__()
199
200     def help(self):
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)
206
207     def validate(self, value):
208         """If `value` is not appropriate, raise `ValueError`.
209         """
210         pass # TODO: validation
211
212     # TODO: type conversion
213
214 # TODO: type extensions?
215
216 # Useful callbacks
217
218 class StoreValue (object):
219     def __init__(self, value):
220         self.value = value
221     def __call__(self, command, argument, fragment=None):
222         return self.value
223
224 class NullQueue (queue.Queue):
225     """The :class:`queue.Queue` equivalent of `/dev/null`.
226
227     This is a bottomless pit.  Items go in, but never come out.
228     """
229     def get(self, block=True, timeout=None):
230         """Raise queue.Empty.
231         
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
235         forever :(.
236         """
237         raise queue.Empty
238
239     def put(self, item, block=True, timeout=None):
240         """Dump an item into the void.
241
242         Block and timeout are meaningless, because there is always a
243         free slot available in a bottomless pit.
244         """
245         pass
246
247 class PrintQueue (NullQueue):
248     """Debugging :class:`NullQueue` that prints items before dropping
249     them.
250     """
251     def put(self, item, block=True, timeout=None):
252         """Print `item` and then dump it into the void.
253         """
254         print 'ITEM:\n%s' % item
255
256
257 # Construct plugin dependency graph and load default plugins.
258
259 PLUGINS = {}
260 """(name,instance) :class:`dict` of all possible :class:`Plugin`\s.
261 """
262
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)
270         try:
271             subclass = issubclass(obj, Plugin)
272         except TypeError:
273             continue
274         if subclass == True and obj != Plugin:
275             p = obj()
276             if p.name != plugin_modname:
277                 raise Exception('Plugin name %s does not match module name %s'
278                                 % (p.name, plugin_modname))
279             PLUGINS[p.name] = p
280
281 PLUGIN_GRAPH = Graph([Node([PLUGINS[name] for name in p.dependencies()],
282                            data=p)
283                       for p in PLUGINS.values()])
284 PLUGIN_GRAPH.topological_sort()
285
286
287 def default_settings():
288     settings = [Setting(
289             'plugins', help='Enable/disable default plugins.')]
290     for pnode in PLUGIN_GRAPH:
291         plugin = pnode.data
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(
296                 section='plugins',
297                 option=plugin.name,
298                 value=str(default_include),
299                 help=help,
300                 ))
301     for pnode in PLUGIN_GRAPH:
302         plugin = pnode.data
303         settings.extend(plugin.default_settings())
304     return settings