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