Ironed out kinks in plugin/driver loading and configuring.
[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         self.setting_section = '%s plugin' % self.name
50         self.config = {}
51
52     def dependencies(self):
53         """Return a list of :class:`Plugin`\s we require."""
54         return []
55
56     def default_settings(self):
57         """Return a list of :class:`hooke.config.Setting`\s for any
58         configurable plugin settings.
59
60         The suggested section setting is::
61
62             Setting(section=self.setting_section, help=self.__doc__)
63         """
64         return []
65
66     def commands(self):
67         """Return a list of :class:`Commands` provided."""
68         return []
69
70
71
72 # Commands and arguments
73
74 class CommandExit (Exception):
75     def __str__(self):
76         return self.__class__.__name__
77
78 class Success (CommandExit):
79     pass
80
81 class Failure (CommandExit):
82     pass
83
84 class Command (object):
85     """One-line command description here.
86
87     >>> c = Command(name='test', help='An example Command.')
88     >>> status = c.run(NullQueue(), PrintQueue(), help=True)
89     ITEM:
90     Command: test
91     <BLANKLINE>
92     Arguments:
93     help HELP (bool) Print a help message.
94     <BLANKLINE>
95     An example Command.
96     ITEM:
97     Success
98     """
99     def __init__(self, name, aliases=None, arguments=[], help=''):
100         self.name = name
101         if aliases == None:
102             aliases = []
103         self.aliases = aliases
104         self.arguments = [
105             Argument(name='help', type='bool', default=False, count=1,
106                      callback=StoreValue(True), help='Print a help message.'),
107             ] + arguments
108         self._help = help
109
110     def run(self, inqueue=None, outqueue=None, **kwargs):
111         """`Normalize inputs and handle <Argument help> before punting
112         to :meth:`_run`.
113         """
114         if inqueue == None:
115             inqueue = NullQueue()
116         if outqueue == None:
117             outqueue = NullQueue()
118         try:
119             params = self.handle_arguments(inqueue, outqueue, kwargs)
120             if params['help'] == True:
121                 outqueue.put(self.help())
122                 raise(Success())
123             self._run(inqueue, outqueue, params)
124         except CommandExit, e:
125             if isinstance(e, Failure):
126                 outqueue.put(e.message)
127                 outqueue.put(e)
128                 return 1
129         outqueue.put(e)
130         return 0
131
132     def _run(self, inqueue, outqueue, params):
133         """This is where the command-specific magic will happen.
134         """
135         pass
136
137     def handle_arguments(self, inqueue, outqueue, params):
138         """Normalize and validate input parameters (:class:`Argument` values).
139         """
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)]
146                 else:
147                     raise Failure('Required argument %s not set.'
148                                   % argument.name)
149             if len(settings) > 1:
150                 raise Failure('Multiple settings for %s:\n  %s'
151                     % (argument.name,
152                        '\n  '.join(['%s: %s' % (name,value)
153                                     for name,value in sorted(settings)])))
154             name,value = settings[0]
155             if name != argument.name:
156                 params.remove(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)
162         return params
163
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])
172
173 class Argument (object):
174     """Structured user input for :class:`Command`\s.
175     
176     TODO: ranges for `count`?
177     """
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=''):
181         self.name = name
182         if aliases == None:
183             aliases = []
184         self.aliases = aliases
185         self.type = type
186         if metavar == None:
187             metavar = type.upper()
188         self.metavar = metavar
189         self.default = default
190         self.optional = optional
191         self.count = count
192         self.completion_callback = completion_callback
193         self.callback = callback
194         self._help = help
195
196     def __str__(self):
197         return '<%s %s>' % (self.__class__.__name__, self.name)
198
199     def __repr__(self):
200         return self.__str__()
201
202     def help(self):
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)
208
209     def validate(self, value):
210         """If `value` is not appropriate, raise `ValueError`.
211         """
212         pass # TODO: validation
213
214     # TODO: type conversion
215
216 # TODO: type extensions?
217
218 # Useful callbacks
219
220 class StoreValue (object):
221     def __init__(self, value):
222         self.value = value
223     def __call__(self, command, argument, fragment=None):
224         return self.value
225
226 class NullQueue (queue.Queue):
227     """The :class:`queue.Queue` equivalent of `/dev/null`.
228
229     This is a bottomless pit.  Items go in, but never come out.
230     """
231     def get(self, block=True, timeout=None):
232         """Raise queue.Empty.
233         
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
237         forever :(.
238         """
239         raise queue.Empty
240
241     def put(self, item, block=True, timeout=None):
242         """Dump an item into the void.
243
244         Block and timeout are meaningless, because there is always a
245         free slot available in a bottomless pit.
246         """
247         pass
248
249 class PrintQueue (NullQueue):
250     """Debugging :class:`NullQueue` that prints items before dropping
251     them.
252     """
253     def put(self, item, block=True, timeout=None):
254         """Print `item` and then dump it into the void.
255         """
256         print 'ITEM:\n%s' % item
257
258
259 # Construct plugin dependency graph and load default plugins.
260
261 PLUGINS = {}
262 """(name,instance) :class:`dict` of all possible :class:`Plugin`\s.
263 """
264
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)
272         try:
273             subclass = issubclass(obj, Plugin)
274         except TypeError:
275             continue
276         if subclass == True and obj != Plugin:
277             p = obj()
278             if p.name != plugin_modname:
279                 raise Exception('Plugin name %s does not match module name %s'
280                                 % (p.name, plugin_modname))
281             PLUGINS[p.name] = p
282
283 PLUGIN_GRAPH = Graph([Node([PLUGINS[name] for name in p.dependencies()],
284                            data=p)
285                       for p in PLUGINS.values()])
286 PLUGIN_GRAPH.topological_sort()
287
288
289 def default_settings():
290     settings = [Setting(
291             'plugins', help='Enable/disable default plugins.')]
292     for pnode in PLUGIN_GRAPH:
293         plugin = pnode.data
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(
298                 section='plugins',
299                 option=plugin.name,
300                 value=str(default_include),
301                 help=help,
302                 ))
303     for pnode in PLUGIN_GRAPH:
304         plugin = pnode.data
305         settings.extend(plugin.default_settings())
306     return settings