4d5cd01f0aeec343c584c43991e27d55d46369ae
[hooke.git] / hooke / command_stack.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
5 # Hooke is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke.  If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """The ``command_stack`` module provides tools for managing and
20 executing stacks of :class:`~hooke.engine.CommandMessage`\s.
21 """
22
23 import os
24 import os.path
25
26 import yaml
27
28 from .engine import CommandMessage
29
30
31 class CommandStack (list):
32     """Store a stack of commands.
33
34     Examples
35     --------
36     >>> c = CommandStack([CommandMessage('CommandA', {'param':'A'})])
37     >>> c.append(CommandMessage('CommandB', {'param':'B'}))
38     >>> c.append(CommandMessage('CommandA', {'param':'C'}))
39     >>> c.append(CommandMessage('CommandB', {'param':'D'}))
40
41     Implement a dummy :meth:`execute_command` for testing.
42
43     >>> def execute_cmd(hooke, command_message, stack=None):
44     ...     cm = command_message
45     ...     print 'EXECUTE', cm.command, cm.arguments
46     >>> c.execute_command = execute_cmd
47
48     >>> c.execute(hooke=None)  # doctest: +ELLIPSIS
49     EXECUTE CommandA {'param': 'A'}
50     EXECUTE CommandB {'param': 'B'}
51     EXECUTE CommandA {'param': 'C'}
52     EXECUTE CommandB {'param': 'D'}
53
54     :meth:`filter` allows you to select which commands get executed.
55     If, for example, you are applying a set of commands to the current
56     :class:`~hooke.curve.Curve`, you may only want to execute
57     instances of :class:`~hooke.plugin.curve.CurveCommand`.  Here we
58     only execute commands named `CommandB`.
59     
60     >>> def filter(hooke, command_message):
61     ...     return command_message.command == 'CommandB'
62
63     Apply the stack to the current curve.
64
65     >>> c.execute(hooke=None, filter=filter)  # doctest: +ELLIPSIS
66     EXECUTE CommandB {'param': 'B'}
67     EXECUTE CommandB {'param': 'D'}
68
69     Execute a new command and add it to the stack.
70
71     >>> cm = CommandMessage('CommandC', {'param':'E'})
72     >>> c.execute_command(hooke=None, command_message=cm)
73     EXECUTE CommandC {'param': 'E'}
74     >>> c.append(cm)
75     >>> print [repr(cm) for cm in c]  # doctest: +NORMALIZE_WHITESPACE
76     ['<CommandMessage CommandA {param: A}>',
77      '<CommandMessage CommandB {param: B}>',
78      '<CommandMessage CommandA {param: C}>',
79      '<CommandMessage CommandB {param: D}>',
80      '<CommandMessage CommandC {param: E}>']
81
82     The data-type is also pickleable, which ensures we can move it
83     between processes with :class:`multiprocessing.Queue`\s and easily
84     save it to disk.  We must remove the unpickleable dummy executor
85     before testing though.
86
87     >>> c.execute_command  # doctest: +ELLIPSIS
88     <function execute_cmd at 0x...>
89     >>> del(c.__dict__['execute_command'])
90     >>> c.execute_command  # doctest: +ELLIPSIS
91     <bound method CommandStack.execute_command of ...>
92     
93     Lets also attach a child command message to demonstrate recursive
94     serialization (we can't append `c` itself because of
95     `Python issue 1062277`_).
96
97     .. _Python issue 1062277: http://bugs.python.org/issue1062277
98
99     >>> import copy
100     >>> c.append(CommandMessage('CommandD', {'param': copy.deepcopy(c)}))
101
102     Run the pickle (and YAML) tests.
103
104     >>> import pickle
105     >>> s = pickle.dumps(c)
106     >>> z = pickle.loads(s)
107     >>> print '\\n'.join([repr(cm) for cm in c]
108     ...     )  # doctest: +NORMALIZE_WHITESPACE,
109     <CommandMessage CommandA {param: A}>
110     <CommandMessage CommandB {param: B}>
111     <CommandMessage CommandA {param: C}>
112     <CommandMessage CommandB {param: D}>
113     <CommandMessage CommandC {param: E}>
114     <CommandMessage CommandD {param:
115       [<CommandMessage CommandA {param: A}>,
116        <CommandMessage CommandB {param: B}>,
117        <CommandMessage CommandA {param: C}>,
118        <CommandMessage CommandB {param: D}>,
119        <CommandMessage CommandC {param: E}>]}>
120     >>> import yaml
121     >>> print yaml.dump(c)
122     !!python/object/new:hooke.command_stack.CommandStack
123     listitems:
124     - !!python/object:hooke.engine.CommandMessage
125       arguments: {param: A}
126       command: CommandA
127     - !!python/object:hooke.engine.CommandMessage
128       arguments: {param: B}
129       command: CommandB
130     - !!python/object:hooke.engine.CommandMessage
131       arguments: {param: C}
132       command: CommandA
133     - !!python/object:hooke.engine.CommandMessage
134       arguments: {param: D}
135       command: CommandB
136     - !!python/object:hooke.engine.CommandMessage
137       arguments: {param: E}
138       command: CommandC
139     - !!python/object:hooke.engine.CommandMessage
140       arguments:
141         param: !!python/object/new:hooke.command_stack.CommandStack
142           listitems:
143           - !!python/object:hooke.engine.CommandMessage
144             arguments: {param: A}
145             command: CommandA
146           - !!python/object:hooke.engine.CommandMessage
147             arguments: {param: B}
148             command: CommandB
149           - !!python/object:hooke.engine.CommandMessage
150             arguments: {param: C}
151             command: CommandA
152           - !!python/object:hooke.engine.CommandMessage
153             arguments: {param: D}
154             command: CommandB
155           - !!python/object:hooke.engine.CommandMessage
156             arguments: {param: E}
157             command: CommandC
158       command: CommandD
159     <BLANKLINE>
160
161     There is also a convenience function for clearing the stack.
162
163     >>> c.clear()
164     >>> print [repr(cm) for cm in c]
165     []
166
167     YAMLize a curve argument.
168
169     >>> from .curve import Curve
170     >>> c.append(CommandMessage('curve info', {'curve': Curve(path=None)}))
171     >>> print yaml.dump(c)
172     !!python/object/new:hooke.command_stack.CommandStack
173     listitems:
174     - !!python/object:hooke.engine.CommandMessage
175       arguments:
176         curve: !!python/object:hooke.curve.Curve
177           command_stack: !!python/object:hooke.command_stack.CommandStack {}
178           data: null
179           driver: null
180           info: {}
181           name: null
182           path: null
183       command: curve info
184     <BLANKLINE>
185     """
186     def execute(self, hooke, filter=None, stack=False):
187         """Execute a stack of commands.
188
189         See Also
190         --------
191         execute_command, filter
192         """
193         if filter == None:
194             filter = self.filter
195         for command_message in self:
196             if filter(hooke, command_message) == True:
197                 self.execute_command(
198                     hooke=hooke, command_message=command_message, stack=stack)
199
200     def filter(self, hooke, command_message):
201         """Return `True` to execute `command_message`, `False` otherwise.
202
203         The default implementation always returns `True`.
204         """
205         return True
206
207     def execute_command(self, hooke, command_message, stack=False):
208         arguments = dict(command_message.arguments)
209         arguments['stack'] = stack
210         hooke.run_command(command=command_message.command,
211                           arguments=arguments)
212
213     def clear(self):
214         while len(self) > 0:
215             self.pop()
216
217
218 class FileCommandStack (CommandStack):
219     """A file-backed :class:`CommandStack`.
220     """
221     version = '0.1'
222
223     def __init__(self, *args, **kwargs):
224         super(FileCommandStack, self).__init__(*args, **kwargs)
225         self.name = self.path = None
226
227     def __setstate__(self, state):
228         self.name = self.path = None
229         for key,value in state.items:
230             setattr(self, key, value)
231         self.set_path(state.get('path', None))
232
233     def set_path(self, path):
234         """Set the path (and possibly the name) of the command  stack.
235
236         Examples
237         --------
238         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
239
240         :attr:`name` is set only if it starts out equal to `None`.
241         >>> c.name == None
242         True
243         >>> c.set_path(os.path.join('path', 'to', 'my', 'command', 'stack'))
244         >>> c.path
245         'path/to/my/command/stack'
246         >>> c.name
247         'stack'
248         >>> c.set_path(os.path.join('another', 'path'))
249         >>> c.path
250         'another/path'
251         >>> c.name
252         'stack'
253         """
254         if path != None:
255             self.path = path
256             if self.name == None:
257                 self.name = os.path.basename(path)
258
259     def save(self, path=None, makedirs=True):
260         """Saves the command stack to `path`.
261         """
262         self.set_path(path)
263         dirname = os.path.dirname(self.path) or '.'
264         if makedirs == True and not os.path.isdir(dirname):
265             os.makedirs(dirname)
266         with open(self.path, 'w') as f:
267             f.write(self.flatten())
268
269     def load(self, path=None):
270         """Load a command stack from `path`.
271         """
272         self.set_path(path)
273         with open(self.path, 'r') as f:
274             text = f.read()
275         self.from_string(text)
276
277     def flatten(self):
278         """Create a string representation of the command stack.
279
280         A playlist is a YAML document with the following syntax::
281
282             - arguments: {param: A}
283               command: CommandA
284             - arguments: {param: B, ...}
285               command: CommandB
286             ...
287
288         Examples
289         --------
290         >>> c = FileCommandStack([CommandMessage('CommandA', {'param':'A'})])
291         >>> c.append(CommandMessage('CommandB', {'param':'B'}))
292         >>> c.append(CommandMessage('CommandA', {'param':'C'}))
293         >>> c.append(CommandMessage('CommandB', {'param':'D'}))
294         >>> print c.flatten()
295         - arguments: {param: A}
296           command: CommandA
297         - arguments: {param: B}
298           command: CommandB
299         - arguments: {param: C}
300           command: CommandA
301         - arguments: {param: D}
302           command: CommandB
303         <BLANKLINE>
304         """
305         return yaml.dump([{'command':cm.command,'arguments':cm.arguments}
306                           for cm in self])
307
308     def from_string(self, string):
309         """Load a playlist from a string.
310
311         .. warning:: This is *not safe* with untrusted input.
312
313         Examples
314         --------
315
316         >>> string = '''- arguments: {param: A}
317         ...   command: CommandA
318         ... - arguments: {param: B}
319         ...   command: CommandB
320         ... - arguments: {param: C}
321         ...   command: CommandA
322         ... - arguments: {param: D}
323         ...   command: CommandB
324         ... '''
325         >>> c = FileCommandStack()
326         >>> c.from_string(string)
327         >>> print [repr(cm) for cm in c]  # doctest: +NORMALIZE_WHITESPACE
328         ['<CommandMessage CommandA {param: A}>',
329          '<CommandMessage CommandB {param: B}>',
330          '<CommandMessage CommandA {param: C}>',
331          '<CommandMessage CommandB {param: D}>']
332         """
333         for x in yaml.load(string):
334             self.append(CommandMessage(command=x['command'],
335                                        arguments=x['arguments']))